我需要在每个foreach循环结果之间获取-and
来创建一个数组。这意味着我不能在数组末尾使用它!
我的脚本是这样的:
Param (
[Parameter(Mandatory=$false)]
[string]$IncludeFilesCSVPath = "\\mypath\IncludeFiles.csv"
)
$includeFilesCsv = Import-CSV $IncludeFilesCSVPath
$includeFilesList = New-Object -TypeName "System.Collections.Generic.List[string]"
foreach ($item in $includeFilesCsv) {
$includeFilesList.Add('(-not (Attachment -like "*' + $item.Godkjent + '"))')
}
$includeFiles = $includeFilesList.ToArray()
Write-Host $IncludeFiles
CSV文件的标题为:Godkjent
而且每一行都包含文件结尾,例如.EXE .TXT .PS1
现在输出为:
(-not (Attachment -like "*.DOC")) (-not (Attachment -like "*.DOCX")) (-not (Attachment -like "*.TXT")) (-not (Attachment -like "*.CSV"))
但是我需要:
(-not (Attachment -like "*.DOC")) -and (-not (Attachment -like "*.DOCX")) -and (-not (Attachment -like "*.TXT")) -and (-not (Attachment -like "*.CSV"))
答案 0 :(得分:0)
您无需显式收集foreach
项目输出 在列表中-将该语句整体用作隐式表达式返回输出为 array 。
要将-join
运算符与一个分隔符一起组成一个数组的元素,请使用$includeFiles = $(foreach ($item in $includeFilesCsv) {
'(-not (Attachment -like "*' + $item.Godkjent + '"))'
}) -join ' -and '
运算符。
$(...)
请注意,需要在foreach
循环周围使用@(...)
,以使其成为较大表达式的一部分。 (为了保证数组,$(...)
也可以在这里工作,但是没有任何实际区别)。
在this GitHub issue中讨论了对(...)
而不是example_data
的令人惊讶的需求。
答案 1 :(得分:0)
尝试以下代码:
Param (
[Parameter(Mandatory=$false)]
[string]$IncludeFilesCSVPath = "\\mypath\IncludeFiles.csv"
)
$includeFilesCsv = Import-CSV $IncludeFilesCSVPath
$Total = $includeFilesCsv.count
$counter = 0
$includeFilesList = New-Object -TypeName "System.Collections.Generic.List[string]"
foreach ($item in $includeFilesCsv) {
$counter++
if ($counter -ne $Total) {
$includeFilesList.Add('(-not (Attachment -like "*' + $item.Godkjent + '")) -and')
}
else {
$includeFilesList.Add('(-not (Attachment -like "*' + $item.Godkjent + '"))')
}
}
$includeFiles = $includeFilesList.ToArray()
Write-Host $IncludeFiles
这是我的CSV文件的样子:
让我知道它是否无效。我会再试一次。