Out-File生成末尾空行及Export-CSV格式问题求助
解决Out-File末尾空行问题
你的命令中Select-Object -ExpandProperty HotFixID输出的是字符串数组,Out-File默认会给每个元素添加换行符,包括最后一个元素,因此文件末尾会多出空行。以下两种方法可以解决:
方法1:用Join-String合并后去除首尾空白再写入
gwmi win32_quickfixengineering | sort installedon -desc | ?{$_.InstalledOn -gt [datetime]::Today.AddDays(-30)} | Select-Object -ExpandProperty HotFixID | Join-String -Separator "`n" | Trim() | Out-File C:\OUTPUT\FILE.txt -Force
方法2:使用.NET的WriteAllLines方法(高效无额外空行)
$hotfixes = gwmi win32_quickfixengineering | sort installedon -desc | ?{$_.InstalledOn -gt [datetime]::Today.AddDays(-30)} | Select-Object -ExpandProperty HotFixID [System.IO.File]::WriteAllLines("C:\OUTPUT\FILE.txt", $hotfixes)
WriteAllLines会自动用换行符分隔数组元素,且不会在文件末尾添加额外空行。
解决Export-CSV输出Length列的问题
直接导出字符串数组时,PowerShell会把每个字符串当作System.String对象处理,该对象的默认可导出属性就是Length,因此会出现这类结果。需要把字符串包装成带有HotFixID属性的自定义对象再导出:
方法1:保留原对象结构导出
gwmi win32_quickfixengineering | sort installedon -desc | ?{$_.InstalledOn -gt [datetime]::Today.AddDays(-30)} | Select-Object HotFixID | # 不要用-ExpandProperty,保留对象结构 Export-Csv C:\OUTPUT\FILE.csv -NoTypeInformation -Force
方法2:已展开属性时重新构造对象
gwmi win32_quickfixengineering | sort installedon -desc | ?{$_.InstalledOn -gt [datetime]::Today.AddDays(-30)} | Select-Object -ExpandProperty HotFixID | ForEach-Object { [PSCustomObject]@{ HotFixID = $_ } } | Export-Csv C:\OUTPUT\FILE.csv -NoTypeInformation -Force
-NoTypeInformation参数可以去掉CSV开头的类型注释行,让输出更简洁。
内容的提问来源于stack exchange,提问作者Charles Waters
相关产品推荐
相关产品推荐

