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