如何在PowerShell中循环将某些文件与字符串匹配?

时间:2019-07-16 05:07:46

标签: powershell

我在文件夹中有一些文件,格式名称文件就是这样

US0908ABC
US0908DEF
US0908GHI

我想循环检查那些文件是否与我已经初始化的2个变量匹配。 如果文件与我的变量匹配,它将返回匹配的文件。

这就是我所做的。我使用了这段代码,我可以将这些文件与我的变量匹配,但是只检查1个变量,而不检查我的两个变量。

$Variable_1 = "US"
$Variable_2 = "0908"
$Path = "C:\Doc\File"
$SW = Get-ChildItem -Path $Path
if($SW -match $Variable_1 -and $Variable_2)
{   $SW
    Write-Host "Found"
}
else {
    Write-Host "Check Again!"
}

已更新

Function Check
{
    $n = 0
    while (-not (Test-Path -Path $Path)) {
        Start-Sleep -s 5
        $n++
        Foreach($File in $SW) {
            If(($File.Name -match $Variable_1) -and ($File.Name -match $Variable_2)){
                Write-Host ">>file Found: $File"
            }
        }
    }
    Write-Host ">>File found after $n attempts"
    return $true
}

$Variable_1 = "US"
$Variable_2 = "0908"
$Path = "C:\Doc\File"
$SW = Get-ChildItem -Path $Path
If(Check)
{
    Write-Host ">>Found"
}
else {
    Write-Host "Not Found"
}

3 个答案:

答案 0 :(得分:2)

您可以选择:

$Variable_1 = "US"
$Variable_2 = "0908"
$Path = "C:\Doc\File"
$SW = Get-ChildItem -Path $Path

$SW | ForEach-Object {
    if ($_.Name.Contains($Variable_1) -and $_.Name.Contains($Variable_2)) {   
        $_
        Write-Host "Found"
    }
    else {
        Write-Host "Check Again!"
    }
}

一种更简单的方法可以在一行中进行编码:

  $foundFiles = Get-ChildItem -Path "C:\Doc\File" | Where-Object {$_.Name.Contains("US") -and $_.Name.Contains("0908") }

$foundFiles的类型为array,包括所有过滤的文件。您可以通过for loopforeach loop通过$foundFiles进行迭代,也可以通过ForEach-Object cmdlet与管道操作(例如$foundFiles | ForEach-Object { Write-Host "$_" }, where $ _ `在管道中包含实际的文件对象。

如果要过滤文件结尾,可以将-Include参数添加到Get-ChildItem。如果要在嵌套文件夹中查找文件,可以添加-Recurse开关。

因此您的上述示例可以简化为一个cmdlet调用:

Get-ChildItem -Path "C:\Doc\File" -Include "*US*0908*" -Recurse

输出:

 Get-ChildItem -Path "C:\Doc\File" -Include "*US*0908*" -Recurse


 Directory: C:\Doc\File

  Mode                LastWriteTime         Length Name
  ----                -------------         ------ ----
  -a----        16.07.2019    07:27              0 US0908ABC
  -a----        16.07.2019    07:27              0 US0908DEF
  -a----        16.07.2019    07:28              0 US0908GHI

答案 1 :(得分:1)

尝试一下:

$Variable_1 = "US"
$Variable_2 = "0908"
$Path = "C:\Doc\File"
$SW = Get-ChildItem -Path $Path

for ($i=0; $i -lt $SW.Count; $i++) {

 $outfile = $SW[$i].FullName
 if($outfile -match $Variable_1 -and $outfile -match $Variable_2)
 {   $outfile
    Write-Host "Found"
 }
 else {
  $outfile
  Write-Host "Check Again!"
 }
}

答案 2 :(得分:1)

假设您正在$Path中查找文件,那么这将为您做准备。您可以通过将其中一个文件从US0908...更改为US0907...来确认。

$Variable_1 = "US"
$Variable_2 = "0908"
$Path = "C:\Doc\File"
$SW = Get-ChildItem -Path $Path

Foreach($File in $SW) {
    If(($File.Name -match $Variable_1) -and ($File.Name -match $Variable_2)) {
        Write-Host "Found"
    } Else {
        Write-Host "Check Again!"
    }
}