'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
Solution 1:[1]
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 propertyPS> 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.
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |