powershell - Where-Object 和数组未正确过滤

标签 powershell

我无法让我的脚本正常工作。 我有三个数组。扩展数组确实可以正确过滤。然而,我的带有通配符的数组没有生成我想要的结果。我做错了什么?

# 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
    }
}

最佳答案

您可以编写自己的函数:

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)}

关于powershell - Where-Object 和数组未正确过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35708274/

相关文章:

powershell - Powershell将文件路径中最后出现的 '/'替换为 '.'

azure - 如何使用 Powershell 从 Azure Functions 获取 Azure Blob URI?

powershell - 使用变量间接访问 PSObject 属性

windows - Perl:与 Unix 相比,Windows 中的奇怪 Tie::File 行为

powershell - 使用 WMI 获取 IIS6 网站的所有虚拟目录

c# 远程 powershell 创建 AD/Exchange 用户帐户并修改

powershell - Get-InstalledModule 和 Get-Module -ListAvailable 有什么区别?

powershell - 如何抑制 PowerShell cmdlet (Move-VM) 结果?

json - 从 Powershell 中的超大文件中提取多行正则表达式

powershell - 错误:An attempt was made to add an object to the directory with a name that is already in use