IT:AD:Powershell:HowTo:gotchas/Different behaviour between ide and runtime
Summary
An IDE that can't run scripts as they would run in situ is….weird.
But that's what we have to work with
Tips
Knowing where you are
A lot of scripts rely on loading other scripts and files from the the same or descendent directories.
That means that the script has to figure out where it is first, in order to it's directory.
You would think that's easy… I wish it were.
You'll see lots of scripts state something akin to:
$currentDirectory = (Split-Path $MyInvocation.MyCommand.Path)[0];
But it only works when run not in the IDE!
And the workaround for Powershell v1 is not:
$currentDirectory = $MyInvocation.MyCommand.Path;
if (!$currentDirectory.Path){
# this is garbage...it totally depends where you opened the CLI from...
$currentDirectory = (Get-Location).Path
}
else {
$currentDirectory = (Split-Path $tmp)[0];
}
But in V3, the following do work in the IDE and runtime:
$PSCommandPath$PSScriptRoot- WARNING: saw this, but I disagree as it's working for me right now in Powershell 4:
Which is more or less the equivalent of (it it would have worked in the IDE as well):
$private:PSCommandPath = $MyInvocation.MyCommand.Path $private:PSScriptRoot = (Split-Path -Parent $PSCommandPath)