首页 > 解决方案 > PS不是每次都创建一个新文件

问题描述

每次执行时,我都使用以下 PS cmdlet 创建一个新的 json 文件。应该覆盖现有的 json 文件

$jsonformatOutput = "JSON-BEGIN" + $jsonOutput + "JSON-END"
$jsonformatOutput | New-Item -path $myFileName -Force

但是,如果它们已经是具有相同文件名的现有文件,则不会创建新的 json 文件。

标签: windowspowershellpowershell-4.0powershell-remoting

解决方案


New-Item不是为这种情况选择的功能(因为它实际上应该只用于创建项目)。

你应该改用的是Out-File

$jsonformatOutput = "JSON-BEGIN" + $jsonOutput + "JSON-END"
$jsonformatOutput | Out-File -Filepath $myFileName

这会将变量写入文件$myFileName并覆盖该文件(如果它仍然存在)。

如果您想将内容添加到现有文件而不是覆盖它,您可以使用-Append.


推荐阅读