我正在尝试使用以下 powershell 代码将 foreach 循环输出重定向到文件:
PS C:\> foreach ( $dir in "c:\ProgramData", "c:\Program Files", "c:\Program Files (x86)" ) { echo "=> $dir :" ; dir -r -fo $dir 2>$null | % FullName | sls 'exe$' } > C:\temp\VDI_Exclustion_List.txt
但输出显示在标准输出上,我收到此错误:
> : The term '>' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:157
+ ... ir :" ; dir -r -fo $dir 2>$null | % FullName | sls 'exe$' } > C:\temp ...
+ ~
+ CategoryInfo : ObjectNotFound: (>:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\> ls C:\temp\VDI_Exclustion_List.txt
ls : Cannot find path 'C:\temp\VDI_Exclustion_List.txt' because it does not exist.
At line:1 char:1
+ ls C:\temp\VDI_Exclustion_List.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\temp\VDI_Exclustion_List.txt:String) [Get-ChildItem], ItemNotFoundEx
ception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
PS C:\>
首先,我尝试用>
以下方式替换重定向 | Out-File C:\temp\VDI_Exclustion_List.txt
,但这不起作用:
At line:1 char:138
+ ... 6)" ) { dir -r -fo $dir 2>$null | % FullName | sls 'exe$' } | Out-Fil ...
+ ~
An empty pipe element is not allowed.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : EmptyPipeElement
PS C:\>
然后我尝试用(在这里找到>
)替换重定向,但这也不起作用: 6>&1 | Out-File C:\temp\VDI_Exclustion_List.txt
PS C:\> foreach ( $dir in "c:\ProgramData", "c:\Program Files", "c:\Program Files (x86)" ) { echo "=> $dir :" ; dir -r -fo $dir 2>$null | % FullName | sls 'exe$' } 6>&1 | Out-File C:\temp\VDI_Exclustion_List.txt
......
6>&1 : The term '6>&1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:157
+ ... :" ; dir -r -fo $dir 2>$null | % FullName | sls 'exe$' } 6>&1 | Out-F ...
+ ~~~~
+ CategoryInfo : ObjectNotFound: (6>&1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\>
我希望输出位于文件 C:\temp\VDI_Exclustion_List.txt 内,但该文件甚至没有创建。
正如您已经发现的,流程控制语句不能用来代替命令或值表达式 - 但您可以将它们包装在脚本块中,然后重定向调用它的输出:
话虽如此,这里实际上并不需要循环!
您可以将输入数据直接通过管道传输到
Get-ChildItem
,发现的文件Get-ChildItem
又可以通过管道传输Where-Object
到其扩展名进行过滤,此时我们可以FullName
使用以下命令从每个结果文件子集中获取属性值ForEach-Object
: