PowerShell function to delete if exist and create empty folder

In our PowerShell scripts for different folder it’s required to delete if exist and create empty folder. To avoid to repeat folder name in three commands I’ve created a function

function DeleteIfExistsAndCreateEmptyFolder($dir )
{
      if ( Test-Path $dir ) {
               Get-ChildItem -Path  $dir -Force -Recurse | Remove-Item -force -recurse
               Remove-Item $dir -Force

  }

    New-Item -ItemType Directory -Force -Path $dir
}
 
I’ve also used this function in  answer for SuperUser question How can I copy a directory, overwriting its contents if it exists using Powershell?
Advertisements