简体   繁体   English

如何使用 PowerShell 覆盖文件?

[英]How do I overwrite a file using PowerShell?

New-Item -Path "C:\aws" -Name "script.ps1" -ItemType "file" -Value "text in file"

I am trying to create a file using the above command, if the file already exists I have to replace it with new file, it will have same file name.我正在尝试使用上述命令创建一个文件,如果该文件已经存在,我必须用新文件替换它,它将具有相同的文件名。 Please help请帮忙

Use the force — specifically, the -Force parameter...使用力——特别是-Force参数...

New-Item -Path "C:\aws" -Name "script.ps1" -ItemType "file" -Value "text in file" -Force

Whether script.ps1 already exists or not, upon success it will contain the exact content text in file .无论script.ps1是否已经存在,成功后它将包含text in file

Its use is also demonstrated in example #9 of the New-Item documentation ... New-Item文档示例 #9中也演示了它的使用...

Example 9: Use the -Force parameter to overwrite existing files ===============================================================示例 9:使用 -Force 参数覆盖现有文件 ======================================= ==========================

This example creates a file with a value and then recreates the file using -Force .此示例创建一个具有值的文件,然后使用-Force重新创建该文件。 This overwrites The existing file and it will lose it's content as you can see by the length property这会覆盖现有文件,它会丢失它的内容,正如您通过长度属性看到的那样

PS> New-Item./TestFile.txt -ItemType File -Value 'This is just a test file' Directory: C:\Source\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 5/1/2020 8:32 AM 24 TestFile.txt New-Item./TestFile.txt -ItemType File -Force Directory: C:\Source\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 5/1/2020 8:32 AM 0 TestFile.txt

Omitting -Force from the second invocation of New-Item produces the error New-Item: The file '...\TestFile.txt' already exists.在第二次调用New-Item时省略-Force会产生错误New-Item: The file '...\TestFile.txt' already exists. . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM