在powershell脚本中使用“开头为”而不是包含?

ain*_*ara 3 powershell hashtable

在我当前的 powershell 脚本中,我有包含值的哈希表。我使用这个语法

$x = $f.contains("$k")
Run Code Online (Sandbox Code Playgroud)

但我最近发现这种方法有问题,我想知道powershell是否有一些“开头为”或相关的内容,它会通过“开头为”而不是“开头”来搜索哈希表contains

哈希表的示例:

"bio.txt" = "server1\datafiles\bio";
etc.......
Run Code Online (Sandbox Code Playgroud)

编辑评论中的示例

foreach ($key in $filehash.keys) { 
    $path = $filehash.get_Item($key)
    $filecount = 0
    foreach ($file in $FileArray) { 
        if ($file.LastWriteTime -lt($(GetDate).adddays(-1))) { 
            [string] $k = $key.ToLower()
            [string] $f = $file.name.ToLower() 
            if ($x = $f.contains("$k")) { } 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fro*_* F. 5

尝试使用-like检查字符串是否以 开头yourvalue。我在评论中重写了您的示例以使用它:

$filehash.GetEnumerator() | foreach {
    #$_ is now current object from hashtable(like foreach)
    #$_.key is key and $_.value is path
    $filecount = 0
    foreach ($file in $FileArray) {
        if ( ($file.LastWriteTime -lt $((Get-Date).AddDays(-1))) -and ($file.name -like "$($_.Key)*") ) {
            #process file

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • if ($x = $f.StartsWith("$k")) 这就是我一直在寻找的......谢谢大家:) (2认同)