1

I had an issue with one of my scripts that has a few calls to Remove-Item, here are all of them:

Remove-Item -r -force "$path_Docs\*"
Remove-Item -recurse -force ( join-path $PSScriptRoot "\logs\*" ) | Out-Null
Remove-Item -r -force "$MappingFilePath\*

These variables are set to:

$MappingFilePath = ( Join-Path $PSScriptRoot "\Table Mappings\")
$path_Docs = (join-path $settings.files.data_folder "\documents")

Basically what happened is, I started my script which is a schema migration script and takes around 3 hours for the database I was running it on. Went on lunch, came back and saw that my script had decided to try and recursively delete the entire C:\ drive. I can't think of any reason as to why this would have happened other than $PSScriptRoot being NULL, but then again i always Set-Location to the script root directory before running the script so i am not entirely sure.

Either way i have added the following to the top of my script main and ran it again a few times without issue:

## NOT AGAIN!!!
if ([string]::IsNullOrEmpty($PSScriptRoot)) {
    Set-Output "[!!!] Dodged a bullet on this one" -colour red -logfilepath $log_prerequisites 
    break;
}

And changed all Remove-Item calls to have a filter:

Remove-Item -r -force "$MappingFilePath\*.xlsx"
Remove-Item -recurse -force "$PSScriptRoot\logs\*.log"  | Out-Null

Is using $PSScriptRoot the best way of getting the script directory and if not what other methods are there? and how could the usage of the above commands have resulted in a recursive deletion of C:\?

Duplication Edit: This is less about the usage of $PSScriptRoot and more about how the recursive deletion could have happened.

Owain Esau
  • 1,876
  • 2
  • 21
  • 34
  • Possible duplicate of [What's the best way to determine the location of the current PowerShell script?](https://stackoverflow.com/questions/5466329/whats-the-best-way-to-determine-the-location-of-the-current-powershell-script) – rpm192 Oct 17 '18 at 06:34
  • see also https://stackoverflow.com/questions/48511874/how-can-i-customize-powershell-when-running-inside-of-the-vscode-integrated-term – Kory Gill Oct 17 '18 at 06:44
  • To demonstrate WHY try `Get-ChildItem "$null\*"`. That's what happens when your paths are null or empty. This is how windows paths work. "\" at the start of a path means "root of current drive". – marsze Oct 17 '18 at 07:24

0 Answers0