#PowerShell 的 Out-File 命令
Out-File
[-FilePath] <String>
[[-Encoding] <Encoding>]
[-Append]
[-Force]
[-NoClobber]
[-Width <Int32>]
[-NoNewline]
[-InputObject <PSObject>]
[-WhatIf]
[-Confirm]
[<CommonParameters>]
Out-File
[[-Encoding] <Encoding>]
-LiteralPath <String>
[-Append]
[-Force]
[-NoClobber]
[-Width <Int32>]
[-NoNewline]
[-InputObject <PSObject>]
[-WhatIf]
[-Confirm]
[<CommonParameters>]
功能
将命令输出以文本形式写入文件,默认使用 UTF-8 无 BOM 编码。
类型
Cmdlet,属于 Microsoft.PowerShell.Utility。
参数
[-FilePath] <String>- 输出文件的路径;位置 0-LiteralPath <String>- 输出文件的路径,按字面解释,不展开通配符[[-Encoding] <Encoding>]- 文件编码,常用值有utf8、utf8NoBOM、unicode、ascii-Append- 追加到现有文件末尾,而不是覆盖-Force- 覆盖只读文件-NoClobber- 文件已存在时不覆盖并报错-Width <Int32>- 指定每行输出的字符宽度-NoNewline- 不在输出末尾添加换行符-InputObject <PSObject>- 要写入的对象,通常通过管道传入
Out-File写入的是供人阅读的文本,不适合保存结构化数据;需要后续还原对象时,应使用Export-Csv或Export-Clixml。
#示例
将输出写入文件
> Get-Process | Out-File -FilePath processes.txt
- 未指定编码时使用默认的 UTF-8 无 BOM 编码,文件已存在会被覆盖。
追加内容到文件
> "开始处理" | Out-File -FilePath log.txt -Append
> Get-Date | Out-File -FilePath log.txt -Append
-Append会保留文件原有内容,将新内容写到末尾。
指定编码
> Get-ChildItem | Out-File -FilePath files.txt -Encoding utf8NoBOM
- 跨平台交换文本时建议显式指定
utf8NoBOM,避免 Windows 上的 BOM 问题。
防止覆盖已有文件
> "data" | Out-File -FilePath report.txt -NoClobber
- 文件已存在时,
-NoClobber会阻止覆盖并返回错误。
使用 LiteralPath 处理特殊字符路径
> "data" | Out-File -LiteralPath 'C:\temp\file[1].txt'
-LiteralPath不会把方括号等字符当作通配符。
验证写入结果
> Get-Content -Path log.txt
开始处理
2026/11/02 14:30:00
Out-File不使用-PassThru时不会向管道输出内容,可通过Get-Content查看结果。