约 2235 字

约 11 分钟

#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> - 要写入的对象,通常通过管道传入

#示例

将输出写入文件

> 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 查看结果。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2