简体   繁体   中英

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...

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 .

Its use is also demonstrated in example #9 of the New-Item documentation ...

Example 9: Use the -Force parameter to overwrite existing files ===============================================================

This example creates a file with a value and then recreates the file using -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. .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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