用 Set-Content 和 Add-Content 写入/追加文件
一对容易忘的命令:Set-Content 覆盖写入,Add-Content 追加,文件不存在都会自动创建。
用 Set-Content -Path <文件> -Value <文本> 写入,用相同参数的 Add-Content 追加。
01命令
命令
$ Set-Content -Path 'C:\Temp\out.txt' -Value 'first line' ; Add-Content -Path 'C:\Temp\out.txt' -Value 'another line'02作用说明
这两个 cmdlet 相当于 '>' 和 '>>',但更明确、可脚本化,且都支持管道:Get-Process | Set-Content procs.txt。Add-Content 在文件不存在时会直接创建而不是报错,适合逐行生成报告。-NoNewline 可去掉末尾换行,-Encoding 控制输出编码(不同 PowerShell 版本默认值不同)。
03风险
!注意: Set-Content 会不加提示地清空并覆盖已有文件,不要指向需要保留的文件。
04撤销
撤销
$ Remove-Item 'C:\Temp\out.txt'05来源
- Add-Content - PowerShell依据: SS64 describes Add-Content appending to a file and creating it if it doesn't exist, with -Encoding and -NoNewline options.
- Set-Content | Microsoft Learn依据: Microsoft documents Set-Content writing (overwriting) content to an item and Add-Content as the append counterpart.
最后验证: 2026-09-17 · 分类: 文件与文件夹