Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
26.7k views
in PowerShell by 3 4 6

I am using PowerShell test-path to check if file exists. but I want to check if the file does not exists create a file otherwise delete it!  my goal to overwrite the file if exists! so to keep it simple I need to know how can I overwrite a file if exists in PowerShell?

if(Test-path $FilePath)
 {
    # overwrite a file
 }

1 Answer

1 like 0 dislike
by 159 186 375
selected by
 
Best answer

test-path cmdlet in PowerShell

PowerShell test-path helps you to check if the file path exists or not. It specifically determines if all elements of the path exist, and returns $True if all elements exist and $False if any are missing.

Check if file exists in PowerShell

To check if file exists using PowerShell test-path, you have to use the below script:

if(Test-path $FilePath -PathType leaf)
 {
    # if true do something
 }
else
{
    # if false do something
}

leaf checks if the $FilePath lead to a file

Check if file does not exist in PowerShell

To check if file doesn't exist using PowerShell test-path, you have to use -not() function as below:

if(-not(Test-path $FilePath -PathType leaf))
 {
    # if the file doesn't exist do something
 }
else
{
    # if file exists do something
}

You can also use ! as an alternative to -not.

Overwrite a file if exists in PowerShell

In your case, you want to overwrite a file if exists in PowerShell, so you have to do the following:

$FilePath = "c:\debug.too.txt"
if(Test-path $FilePath -PathType leaf)
 {
    # delete a file
   Remove-Item $FilePath
 }

 # Add a new item
 New-Item -ItemType File -Path $FilePath
If you don’t ask, the answer is always NO!
...