0

Let's say I type this in CMD from C:\source:

powershell.exe Set-ExecutionPolicy RemoteSigned -File C:\test\test.ps1

In test.ps1 I try to get C:\source as directory without success.

$script_folder = $PSScriptRoot
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$myDir
$PSScriptRoot

Both $myDir and $PSScriptRoot returns C:\test\ instead of C:\source.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user310291
  • 36,946
  • 82
  • 271
  • 487

3 Answers3

1

You could use $PWD which is the Automatic variable for Present Working Directory. When you open PowerShell it should continue to use the same working directory.

From about_automatic_variables

$PWD

Contains a path object that represents the full path of the current directory.

Also MS-DOS is an Operating System which cannot run PowerShell. This is different from cmd.exe aka Command Prompt in Windows.

Jeter-work
  • 782
  • 7
  • 22
BenH
  • 9,766
  • 1
  • 22
  • 35
1

The automatic variables you are using are information about the script invocation. The location from which the command to launch the script was initiated is part of the environment.

$PWD contains information about the present working directory (nod to posix pwd command). Specifically, $PWD.Path.

Per the about_automatic_variables page (or Get-Help about_automatic_variables), $PSScriptRoot, $PSCommandPath, are properties of $MyInvocation.

See here for an example of using Split-Path -Path $($Global:$MyInvocation.MyCommand.Path) to get the current path.

Recommend a test script:

# TestInvocationAndPWDPaths.ps1
function Test-MyInvocation {
    $MyInvocation  
}
function Test-PWD {
    $PWD
}
'$MyInvocation from script:'
$MyInvocation
'$MyInvocation from function:'
Test-MyInvocation

'$PWD from script:'
$PWD
'$PWD from function'
Test-PWD

Has interesting results. Running this from powershell console, and from ISE, and from command prompt will show you the differences in $MyInvocation.

Jeter-work
  • 782
  • 7
  • 22
1

$MyInvocation.PSScriptRoot gives you the caller scripts folder. When the caller is command line, this will return $null.

You should be able to use these two facts.

Just want to add that it is a general pitfall in powershell to use $pwd/get-location inside psm1 functions. Instead inject the full paths as parameters.

Casper Leon Nielsen
  • 2,528
  • 1
  • 28
  • 37