txt 文件只是一堆 UNC 路径,我试图在验证测试路径后将此文本文件中的 UNC 路径列表放入另一个文本文件中。它在屏幕上显示经过验证的路径,但不会填充文本文件。
$cfgs = Get-Content .\cfgpath.txt
$cfgs | % {
if (Test-Path $_) { write-host "$_" | Out-File -FilePath c:\temp\1.txt -Append }
}
来补充Zam 的有用答案 with 背景信息:
-
Write-Host writes to the host[1] (typically, the console aka terminal), which bypasses PowerShell's success output stream and therefore sends nothing trough the pipeline.
- 请参阅底部部分这个答案当
Write-Host
是适当的;简而言之:你通常应该只用它来仅显示 output.
-
Write-Output是用于生成的适当 cmdletdata output, but 很少有必要, 因为您可以信赖 PowerShell 的便捷性implicit输出行为,如 Zam 的回答所示并在这个答案.
Also, 你的命令会执行得更好如果你简单地管道%
(ForEach-Object) 命令的输出作为一个整体 to a single Out-File
call,而不是调用Out-File -Append
对于每个输入路径.
而不是使用%
通过条件显式输出,您可以使用以下命令更优雅地实现您的命令Where-Object cmdlet:
Get-Content .\cfgpath.txt |
Where-Object { Test-Path $_ } |
Out-File -FilePath c:\temp\1.txt
另请注意为了节省strings到文件,使用效率更高Set-Content代替
Out-File
,但请注意,在Windows PowerShell默认输出字符编码不同(在 PowerShell [Core] 6+ 中不再是问题,它始终默认为无 BOM UTF-8);看这个答案何时选择哪个 cmdlet。
相比之下,Out-File
and >
(其有效别名)使用PowerShell的格式化系统来编写用于显示输出文件的任何非字符串输入对象的表示,与默认情况下输出呈现到显示器的方式相同。
换句话说:以适合以后的方式将对象保存到文件中程序化处理,您需要使用结构化文件格式,例如 CSV (Export-Csv) 或 JSON (ConvertTo-Json,结合Set-Content
).
[1] In PowerShell 5.0 and higher, Write-Host
now writes to a new stream, the information stream (number 6
), which by default prints to the host. See about_Redirection.
Therefore, a 6>
redirection now technically does allow you to send Write-Host
output through the pipeline (though doing so is not a good idea) or capture / redirect it; e.g.,
Write-Host hi 6>&1 | % { "[$_]" }
. Note that the type of the objects output by this redirection is System.Management.Automation.InformationRecord.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)