Function Get-ScriptDirectory{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value;
if($Invocation.PSScriptRoot){
$Invocation.PSScriptRoot;
}
elseif($Invocation.MyCommand.Path){
Split-Path $Invocation.MyCommand.Path
}
elseif($Invocation.InvocationName.LastIndexOf("\") -gt 0){
$Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
}
else {
Get-PSDrive | Where-Object{$_.Provider.Name -eq 'FileSystem'} | Foreach-Object {
Join-Path -Path $_.Root -ChildPath $_.CurrentLocation
}
}
}
Returns the path of the script being executed. If unavailable, it will return the path of the PowerShell console.
PS C:\> Function Get-ScriptDirectory{
>> $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
>> if($Invocation.PSScriptRoot){
>> $Invocation.PSScriptRoot;
>> }
>> elseif($Invocation.MyCommand.Path){
>> Split-Path $Invocation.MyCommand.Path
>> }
>> elseif($Invocation.InvocationName.LastIndexOf("\") -gt 0){
>> $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
>> }
>> else {
>> Get-PSDrive | Where-Object{$_.Provider.Name -eq 'FileSystem'} | Foreach-Object {
>> Join-Path -Path $_.Root -ChildPath $_.CurrentLocation
>> }
>> }
>> }
>> Get-ScriptDirectory
C:\Scripts