Powershell'where'语句-notcontains

问题描述 投票:1回答:5

我有一个较大的脚本的简单摘录,基本上,我正在尝试进行递归文件搜索,包括子目录(以及排除项的任何子项)。

clear
$Exclude = "T:\temp\Archive\cst"
$list = Get-ChildItem -Path T:\temp\Archive -Recurse -Directory
$list | where {$_.fullname -notlike $Exclude} | ForEach-Object {
Write-Host "--------------------------------------"
$_.fullname
Write-Host "--------------------------------------"
$files = Get-ChildItem -Path $_.fullname -File
$files.count
}

目前此脚本将排除T:\ temp \ Archive \ cst目录,但不包括T:\ temp \ Archive \ cst \ artwork目录。我正在努力克服这一简单的问题。

我已经尝试过-notlike(我本来并没有真正希望它能正常工作),但也尝试过我希望的-notcontains

任何人都可以提供任何建议,我认为这需要正则表达式匹配,我现在正在阅读,但不是很熟悉。

将来,$ exclude变量将是字符串(目录)的数组,但此刻只是试图使其与直字符串一起工作。

regex powershell where
5个回答
3
投票

尝试:

where {$_.fullname -notlike "$Exclude*"}

您也可以尝试

where {$_.fullname -notmatch [regex]::Escape($Exclude) }

但是不一样的方法更容易。


3
投票

[不带通配符使用时,-like运算符的作用与-eq运算符相同。如果要排除文件夹T:\temp\Archive\cst及其下面的所有内容,则需要类似以下内容:

$Exclude = 'T:\temp\Archive\cst'

Get-ChildItem -Path T:\temp\Archive -Recurse -Directory | ? {
  $_.FullName -ne $Exclude -and
  $_.FullName -notlike "$Exclude\*"
} | ...

[-notlike "$Exclude\*"仅排除$Exclude的子文件夹,不包括文件夹本身,-notlike "$Exclude*"也排除诸如T:\temp\Archive\cstring的文件夹,这可能是不希望的。

-contains运算符用于检查值列表是否包含特定值。它不检查字符串是否包含特定的子字符串。

请参见Get-Help about_Comparison_Operators以获取更多信息。


1
投票

尝试更改

Get-Help about_Comparison_Operators

收件人:

$Exclude = "T:\temp\Archive\cst"

这仍将返回文件夹CST,因为它是Archive的子项,但将不包含cst下的任何内容。

或:

$Exclude = "T:\temp\Archive\cst\*"

但是这也会排除存档中以“ cst”开头的所有文件。 Graimer的答案也一样,请注意结尾的\,如果这对您正在做的事情很重要


1
投票

对于那些正在寻找类似答案的人,我最终得到了什么(解析通配符匹配的数组路径):

 $Exclude = "T:\temp\Archive\cst*

提供我需要的东西。


0
投票

我想补充一下,因为最近我回答了类似的问题。您可以使用-notcontains条件,但有悖直觉的是$ exclude数组必须位于表达式的开头。

这里是一个例子。

如果执行以下操作,则不排除任何项目,并且返回“ a”,“ b”,“ c”,“ d”]

# Declare variables
[string]$rootdir = "T:\temp\Archive"
[String[]]$Exclude = "T:\temp\Archive\cst", "T:\temp\archive\as"
[int]$days = 90

# Create Directory list minus excluded directories and their children
$list = Get-ChildItem -Path $rootdir -Recurse -Directory | where {$path = $_.fullname; -not @($exclude | ? {$path -like $_ -or $path -like "$_\*" }) }

如果我在表达式中切换变量,那么它将起作用并返回“ a”,“ d”。

   $result = @()
   $ItemArray = @("a","b","c","d")
   $exclusionArray = @("b","c")
   $ItemArray | Where-Object { $_ -notcontains $exclusionArray }

我不确定为什么数组必须这样工作。如果还有其他人可以解释,那将是很好。

© www.soinside.com 2019 - 2024. All rights reserved.