Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell PSScriptRoot is null

Tags:

When I run $PSScriptRoot it returns null. I am using PS version 4.

$val  = Join-Path -Path $PSScriptRoot WebPlatformInstaller_amd64_en-US.msi 

Error

Join-Path : Cannot bind argument to parameter 'Path' because it is an empty string.

like image 670
kumar Avatar asked Jun 10 '17 13:06

kumar


People also ask

Why is PSScriptRoot empty?

PowerShell PSScriptRoot Empty PowerShell PSScriptRoot is empty if it is used outside of PowerShell script or caller is not script or command.

What is PSScriptRoot?

PSScriptRoot - Contains the full path to the script that invoked the current command. The value of this property is populated only when the caller is a script.


2 Answers

If using ISE use:

$psISE.CurrentFile.FullPath

When ISE is launched, $psISE is created and can be used to determine the current path of the ISE instance. This was introduced in version 3.0.

See ISE Object Model Hierarchy

If you wanted to get the path in either shell or ISE you could use something like this:

if ($psISE) {     Split-Path -Path $psISE.CurrentFile.FullPath         } else {     $global:PSScriptRoot } 
like image 79
Xopher Avatar answered Sep 22 '22 13:09

Xopher


You have to make sure that this expression is in a saved .ps1 script.

This can happened in following cases:

  • You use this statement in PowerShell ISE console
  • You use this statement in PowerShell console without a script file
  • You marked only this expression for execution in PowerShell ISE
like image 29
k7s5a Avatar answered Sep 21 '22 13:09

k7s5a