secure coding – Best practice to avoid unintentional side-effects in powershell-scripts

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
  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:UsersYourNameSourceReposRedQueen"
$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."