I recently wrote a small PowerShell script to clean a Visual Studio solution. It's used by a small team of 5 persons on a regular basis. I built it in PowershellISE (GUI client) and it works great, but some time later I ran it from Cmd and then after completion I was to my big surprise not in the same directory as previously.

Now, the unexpected result was only an inconvenience. But as an avid fan of the StackExchangeNetwork I read a horror story about a script gone wrong. Its a really interesting read about well-intent script that deleted a users home directory.

  1. What can I do in my script to make it more resiliant to unwanted side-effects?
  2. What are common best practices in Powershell to prevent accidents?
  3. How can I remain in the same directory after script execution?`
#Change path here
$redQueenPath = "C:\Users\YourName\Source\Repos\RedQueen\"
$deletedDirCount = 0

cd $redQueenPath

Get-ChildItem .\ -include bin,obj -Recurse | ForEach-Object ($_) {
    Write-Host "Removing '$_'"
    Remove-Item $_.FullName -Force -Recurse 
    $deletedDirCount = $deletedDirCount + 1
Write-Host "=================================================================="
Write-Host "Total: $deletedDirCount dirs removed."


1 Answer 1


The issue you mentioned is far from being special to Powershell.

Any kind of program, regardless of the programming language, which implements batch operations on the file system, specificially delete operations, has a certain risk of destroying some data if you are not careful. One cannot bring this risk to zero, only reduce it. Here are some tactics how to deal with the issue:

  • Implement a "dry-run" or "preview" mode, so before doing the deletion, the user can check visually which files are going to be deleted (with their full path). Make sure the code which determines the files for the actual deletion is the same as the code which is used for the preview.

  • Avoid relying the current directory; instead, use absolute paths and make your script independent from the current directory where it is run

  • If you cannot avoid to change and rely the current directory, use pushd to change the directory, and popd to restore the original one (or equivalent operations in the specific language environment)

  • Let your code, especially critical sections, be reviewed by a second pair of eyes.

  • Make sure you test your deletion in a local folder intensively before applying it on larger sets in production.

  • Don't delete immediately - delete to to the "recycle bin", that gives you a chance to undo errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.