将 PS2 脚本的输出写入文本文件
Write output of PS2 script to textfile
我有以下脚本:
Get-ChildItem $rootPath -Recurse |
Where-Object {$_.PSIsContainer} |
Where-Object {(Get-ChildItem $_.FullName | Where-Object {!$_.PSIsContainer}| Measure-Object | Select-Object -ExpandProperty Count) -gt 0} |
ForEach-Object{
$files = Get-ChildItem $_.FullName
$props = @{
Path = $_.FullName
Size = "{0:N0}" -f (($files | Where-Object {!$_.PSIsContainer} | Measure-Object -Sum Length | Select-Object -ExpandProperty Sum))
Count = $files | Measure-Object | Select-Object -ExpandProperty Count
}
If ($files.Extension -match "L\d\d"){
# These are special files and we are assuming they are alone in the directory
# Change the path
$props.Path = $files | Select-Object -First 1 | Select-Object -ExpandProperty FullName
}
New-Object -TypeName PSCustomObject -Property $props
} | Select Path,Size,Count
如何将输出写入文本文件而不是控制台?
转发给 Out-File
。例如:
Get-ChildItem ...
<skipped>
} | Select Path,Size,Count | Out-File "files.txt"
几件事。您还有其他值得一提的选择。
} | Select Path,Size,Count | Set-Content "files.txt"
Set-Content
也可以工作,并且具有默认为 ACSII 编码的优点。如果性能发挥作用,那么使用 .Net StreamWriter 将击败 Set-Content
和 Out-File
。
更重要的是,此代码旨在输出对象。使用它你应该使用 Export-CSV
来获得格式良好的输出。
} | Select Path,Size,Count | Export-Csv -NoTypeInformation "files.csv"
我有以下脚本:
Get-ChildItem $rootPath -Recurse |
Where-Object {$_.PSIsContainer} |
Where-Object {(Get-ChildItem $_.FullName | Where-Object {!$_.PSIsContainer}| Measure-Object | Select-Object -ExpandProperty Count) -gt 0} |
ForEach-Object{
$files = Get-ChildItem $_.FullName
$props = @{
Path = $_.FullName
Size = "{0:N0}" -f (($files | Where-Object {!$_.PSIsContainer} | Measure-Object -Sum Length | Select-Object -ExpandProperty Sum))
Count = $files | Measure-Object | Select-Object -ExpandProperty Count
}
If ($files.Extension -match "L\d\d"){
# These are special files and we are assuming they are alone in the directory
# Change the path
$props.Path = $files | Select-Object -First 1 | Select-Object -ExpandProperty FullName
}
New-Object -TypeName PSCustomObject -Property $props
} | Select Path,Size,Count
如何将输出写入文本文件而不是控制台?
转发给 Out-File
。例如:
Get-ChildItem ...
<skipped>
} | Select Path,Size,Count | Out-File "files.txt"
几件事。您还有其他值得一提的选择。
} | Select Path,Size,Count | Set-Content "files.txt"
Set-Content
也可以工作,并且具有默认为 ACSII 编码的优点。如果性能发挥作用,那么使用 .Net StreamWriter 将击败 Set-Content
和 Out-File
。
更重要的是,此代码旨在输出对象。使用它你应该使用 Export-CSV
来获得格式良好的输出。
} | Select Path,Size,Count | Export-Csv -NoTypeInformation "files.csv"