在PowerShell中运行包含“ Format-Table -AutoSize”的以下行时,将生成一个空的输出文件:
Get-ChildItem -Recurse | select FullName,Length | Format-Table -AutoSize | Out-File filelist.txt
之所以需要自动调整输出文件大小,是因为删除了Directoy中更长的文件名。我正在尝试为一个文件夹和子文件夹中的所有文件提取所有文件名和文件大小。删除-Autosize元素时,将生成带有截断文件名的输出文件:
Get-ChildItem -Recurse | select FullName,Length | Out-File filelist.txt
答案 0 :(得分:0)
就像AdminOfThings一样,使用Export-CSV
获取对象的未截断值。
Get-ChildItem -Recurse | select FullName,Length | Export-CSv -path $myPath -NoTypeInformation
我根本不使用Out-File
,仅将Format-Table
/ Format-List
用于交互式脚本。如果要将数据写入文件,Select-Object Column1,Column2 | Sort-Object Column1| Export-CSV
允许我选择要导出的导出对象的属性,并根据需要对记录进行排序。您可以将定界符从逗号更改为制表符/竖线/可能需要的其他任何内容。
答案 1 :(得分:0)
尽管其他答案可能解决了该问题,但您可能还有其他原因想要使用Out-File。外文件具有“宽度”参数。如果未设置,PowerShell默认为80个字符-因此会出现问题。这应该可以解决问题:
Get-ChildItem -Recurse | select FullName,Length | Out-File filelist.txt -Width 250 (or any other value)
答案 2 :(得分:0)
PowerShell中的Format-*
Commandlet仅打算在控制台中使用。它们实际上不会产生可通过管道传递给其他Commandlet的输出。
获取数据的常用方法是使用Export-Csv
。 CSV文件可以轻松导入其他脚本或电子表格中。
如果您确实需要输出格式正确的文本文件,则可以将.Net composite formatting与-f
(格式)运算符配合使用。这与C中的printf()
相似。这是一些示例代码:
# Get the files for the report
$files = Get-ChildItem $baseDirectory -Recurse
# Path column width
$nameWidth = $files.FullName |
ForEach-Object { $_.Length } |
Measure-Object -Maximum |
Select-Object -ExpandProperty Maximum
# Size column width
$longestFileSize = $files |
ForEach-Object { $_.Length.tostring().Length } |
Measure-Object -Maximum |
Select-Object -ExpandProperty Maximum
# Have to consider that some directories will have no files with
# length strings longer than "Size (Bytes)"
$sizeWidth = [System.Math]::Max($longestFileSize, "Size (Bytes)".Length)
# Right-align paths, left-align file size
$formatString = "{0,-$nameWidth} {1,$sizeWidth}"
# Build the report and write it to a file
# ArrayList are much more efficient than using += with arrays
$lines = [System.Collections.ArrayList]::new($files.Length + 3)
# The [void] cast are just to prevent ArrayList.add() from cluttering the
# console with the returned indices
[void]$lines.Add($formatString -f ("Path", "Size (Bytes)"))
[void]$lines.Add($formatString -f ("----", "------------"))
foreach ($file in $files) {
[void]$lines.Add($formatString -f ($file.FullName, $file.Length.ToString()))
}
$lines | Out-File "Report.txt"