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.