此PowerShell函数完全可以实现我使用Write-Host写入控制台时想要的功能,我知道它可以进行一些默认格式设置。但是,我找不到任何方法可以将完全相同的输出保存到文本文件。
function Get-FileHashInfo
{
Param($mydir)
foreach ($item in Get-ChildItem -recurse -file $mydir -force)
{
$mypath = [string]$item.directory + "\" + [string]$item.name
$myhash = Get-FileHash -Path $mypath
Write-Host $myhash.hash $item.name $item.directory
}
}
F887266A20CAA2E44E63F1B4E26218FFD4D3541C7A7100ED9FBF3A45F03066A7 a.txt C:\data\tmp
6D21DED17244347CE2C02A96D5F81CED1CAB82343E26D7E3C57A00F0971B58C2 b.txt C:\data\tmp
2732A420088BBACD56DEB0E19D4EF5A28FA20F11B403ED3134EFDC0CC1EA0EC6 c.txt C:\data\tmp\subdir
我只需要将这些行完全按照控制台上显示的内容写入文本文件。但是,无论我如何尝试,最终都会在输出文件中产生大量其他数据,格式混乱,或者文本文件中根本没有任何数据。
正如@mklement0在注释中指出的,Write-Host
不是正确的工具,因为它的[[only用于显示目的。
Write-Host
这会将您的代码包装在脚本块中,并将输出重定向到表示形式。您也可以查看function Get-FileHashInfo { Param($mydir) & { foreach ($item in Get-ChildItem -recurse -file $mydir -force) { $mypath = [string]$item.directory + "\" + [string]$item.name $myhash = Get-FileHash -Path $mypath "$($myhash.hash) $($item.name) $($item.directory)" } } | Out-File -FilePath ".\output.txt" }
。此Cmdlet是执行标准输出重定向Out-File
运算符的PowerShell方法。如果它使用与控制台相同的格式,它还将保存其输入对象的for-display
Out-File
,以更好地解释>
的功能。 您在这里也不需要使用Out-File: Using PowerShell to Redirect Output to File,因为通过itself
提供字符串已经足够好,可以将其沿管道向下传递到Out-File
。您可以通过在上面的代码段中使用Write-Output
进行测试,请注意它的作用相同。 此外,要调用脚本块,您需要使用Call operator Write-Output
,在Out-File
中有更详细的说明。如果不使用它,最终将把Write-Output "$($myhash.hash) $($item.name) $($item.directory)"
循环代码块写入文件。
更新
如注释中&
的建议,从函数中删除About Operators并将其向下传递到foreach
是一个更好的主意。我只是为了快速演示而编写了前面的示例,但是下面的代码片段是实现此目的的更好方法。它也不再需要使用脚本块,但是无论如何,演示如何将其与管道结合使用对于学习目的是有好处的:)。