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 :-(

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:

$private:PSCommandPath = $MyInvocation.MyCommand.Path
$private:PSScriptRoot = (Split-Path -Parent $PSCommandPath)

  • /home/skysigal/public_html/data/pages/it/ad/powershell/howto/gotchas_different_behaviour_between_ide_and_runtime.txt
  • Last modified: 2023/11/04 23:01
  • by 127.0.0.1