Thursday, 12 March 2015

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:\Share\test.txt"
if (Test-Path $FileName) 
{
  Remove-Item $FileName
}

Advertisements
Advertisements

4 comments:

  1. Remove-Item $FileName -ErrorAction Ignore

    ReplyDelete
  2. Did the job for me. Thanks Tom Ferguson

    ReplyDelete
  3. The path or file name has to be case sensitive. Is there a way to make it ignore case sensitivity?

    ReplyDelete
    Replies
    1. 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:\Share\test.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
      }
      }

      Delete