Powershell – Delete File If Exists

We can test and check if a file exist or not by using the PowerShell cmdlet Test-Path and we can remove/delete a file by using the cmdlet Remove-Item.

The below powershell script delete the file test.txt if it already exists under the path C:Share.

$FileName = "C:\Sharetest.txt"
if (Test-Path $FileName) 
{
  Remove-Item $FileName
}

Advertisement

4 thoughts on “Powershell – Delete File If Exists”

    • Sorry actually the Windows file system itself is designed as case-insensitive. It preserves case as typed, but it doesn't differentiate during comparisons. So all the powershell commands related with filesytem will work without considering the case sensitive. But don't know what is your actual need. If you want to check only whether file exists or not, then you use below commands to check filepath with case sensitive comparison.

      $Filepath = "C:Sharetest.txt"
      $FileObj = (Get-Item $Filepath*) # need to search with wildcard to return actual filename
      #As we have used the wildcard search, we may get multiple results so we need to iterate with foreach
      $FileObj | ForEach-Object {
      if ($_.FullName -ceq $Filepath)
      {
      Write-Host "File exist:" $_.FullName
      }
      }

      Reply

Leave a Comment