Saturday, August 30, 2014

PowerShell: Getting the Drive Letter for a PowerShell Script

A quick search online reveals there are a large number of ways to return the current path of the PowerShell script being run. PowerShell 3 introduced the automatic variable, $PSCommandPath. An example is as follows (script file, ShowPathInfo.ps1):

Write-Output "`$PSCommandPath:  $PSCommandPath";

The output from this command is as follows:



In previous snippet of PowerShell note the use of the Grave accent character before $PSCommandPath (e,.g. `$PSCommandPath). This escape character suppresses $PSCommandPath being interpreted as a variable and instead prints the string literal. For those who cannot find the grave accent (it is to the left of the 1 key or as http://soinoticedthis.blogspot.com/ shows in one blog post):



Displaying the drive letter is a matter of executing (script file, ShowDriveLetter.ps1):

$DriveLetter = $PSCommandPath[0];
Write-Output "Drive Letter:  $DriveLetter";

The output from this is as follows:

The $PSCommandPath automatic variable will not work if you are using PowerShell 2. This version of PowerShell is native to Windows 7 and Windows Server 2008 R2. PowerShell 2 is available in Windows XP upgrade to Service Pack 3, Windows Server 2003 upgraded to Service Pack 2 and Windows Vista upgraded to Service Pack 1.

If you are limited to PowerShell 2 consider the following (script: ShowPathInfoPowerShell2.ps1):

function WhatHappensNestedInAFunction()
{
  Write-Output("Function invoked `$MyInvocation.ScriptName: " + 
    $MyInvocation.ScriptName);
  Write-Output("Function invoked `$MyInvocation.Path: " + 
    $MyInvocation.MyCommand.Path);  
}

Write-Output("Script invoked `$MyInvocation.ScriptName: " + 
  $MyInvocation.ScriptName);
Write-Output("Script invoked `$MyInvocation.Path: " + 
  $MyInvocation.MyCommand.Path);  
WhatHappensNestedInAFunction ;

The output from the script is as follows:


This means in PowerShell 2 you have to use the following to get the script name within the script:'s body:

$MyInvocation.MyCommand.Path  

It also means in PowerShell 2 you have to use the following to get the script name within a function:

$MyInvocation.ScriptName

To simplify this, it is simpler to just create a function that uses $MyInvocation.ScriptName to return the script path:

function GetScriptPath()
{
  return $MyInvocation.ScriptName;
}

Once the script path is know, getting the driver letter is trivial (as was previously demonstrated).

No comments :

Post a Comment