2016-02-29 51 views
2

我无法让脚本正常工作。 我有三个数组。 extensions数组过滤正确。然而我的通配符数组并没有产生我想要的结果。我究竟做错了什么?Where-Object和阵列未正确过滤

# Read List of Servers from flat file 
$data=Get-Content C:\myscripts\admin_servers.txt 

# Variables that will be used against search parameter 
$extensions = @(".ecc", ".exx", ".ezz", ".vvv") 
$wildcards = @("Help_*.txt", "How_*.txt", "Recovery+*") 
$exclude = @("help_text.txt", "Lxr*.exx", "help_contents.txt") 

# Loop each server one by one and do the following 
foreach ($server in $data) 
{ 
    # Search the server E:\ and all subdirectories for the following types of 
    # extensions or wildcards. 
    Get-ChildItem -path \\$server\e$ -Recurse | Where-Object { 
     (($extensions -contains $_.Extension) -or $_.Name -like $wildcards) -and 
     $_.Name -notlike $exclude 
    } 
} 
+2

'$ _名状$ wildcards'是比较'$ _ Name'来。数组。您需要将'$ _。Name'与数组中的每个值进行比较。 –

+0

所以我需要为每个值添加-or和 - 语句? [0],[1],[2]等?有没有办法来减少?我希望数组能够工作,而不必在where子句中指定每个值。 – Refried04

+0

这样做:'($ wildcards |%{“help_a.txt”-like $ _})。Contains($ true)'。可能有一个更简洁的方法。我硬编码一个文件名来测试它,但我认为你明白了。 –

回答

3

你可以写自己的函数:

function Like-Any { 
    param (
     [String] 
     $InputString, 

     [String[]] 
     $Patterns 
    ) 

    foreach ($pattern in $Patterns) { 
     if ($InputString -like $pattern) { 
      return $true 
     } 
    } 
    $false 
} 

然后调用它像这样:

Get-ChildItem -path \\$server\e$ -Recurse | 
Where-Object { ` 
    (($extensions -contains $_.Extension) -or (Like-Any $_.Name $wildcards)) ` 
    -and !(Like-Any $_.Name $exclude)} 
+0

谢谢杰森。完美的作品。我喜欢这个功能。它的工作原理就像我希望我的原始脚本能够工作。我只需要理解这个函数中的错误。我会做一些研究。 – Refried04

+0

很高兴我能帮到你。 –

1

如果您在正则表达式中得心应手,您可以使用-Match作比较。替换为您$Wildcards =$Exclude =线:

$wildcards = "Help_.*?\.txt|How_.*?\.txt|Recovery\+.*" 
$Exclude = "help_text\.txt|Lxr.*?\.exx|help_contents\.txt" 

然后你Where-Object符合:

Where-Object {(($extensions -contains $_.Extension) -or $_.Name -match $wildcards) -and $_.Name -notmatch $exclude} 

这应该为你做它。 $Wildcard =匹配的解释可在this RegEx101 link处获得。

+0

这也适用。我只是没有正则表达式的经验。感谢您的有用参考。我会花一些时间来更好地理解它。 – Refried04

+0

使用正则表达式确实需要一些学习,但在试图解析或匹配文本和模式时它们非常强大,而且与其他方法相比,它们非常快。我很高兴你找到了适合你的答案! – TheMadTechnician