Is there a way to do this in PowerShell?
Thanks,
Gil
from a previous post, we know that you can do this:
$0 = $myInvocation.MyCommand.Definition
from there, we can get:
$dp0 = [System.IO.Path]::GetDirectoryName($0)
of course, you can name the var anything you want....
thanks,
mark
Is this part of some documentation anywhere? i.e. Is there someplace I
could find information like this aside from this forum?
> from a previous post, we know that you can do this:
>
> $0 = $myInvocation.MyCommand.Definition
>
> from there, we can get:
>
> $dp0 = [System.IO.Path]::GetDirectoryName($0)
Piggybacking on this, if you want simpler access to this information, there
are a couple of things you can do.
(1) Check out the Microsoft Connect site; Jeffrey Snover himself has noted
that supporting similar accelerators is an important feature to add if at
all possible, and I believe that the %~/d/p/n[#] accelerators have already
been pointed out. (I do the same thing myself to make WSH/Perl scripts run
with correct stdin redirection, by using "shadow" cmd scripts containing the
line 'cscript "%~dpn0.wsf" %*' or 'perl "%~dpn0.pl" %*').
(2) It is also possible to directly update the InvocationInfo type with a
scripted property to make this more easily accessible. For example, you can
add code to generate the script directory to your file usertypes.ps1xml, and
automatically load it from your profile by adding the line
Update-TypeData usertypes.ps1xml
The content for the file could look like this:
<?xml version="1.0" encoding="utf-8" ?>
<Types>
<Type>
<Name>System.Management.Automation.InvocationInfo</Name>
<Members>
<ScriptProperty>
<Name>ScriptDirectory</Name>
<GetScriptBlock>
[System.IO.Path]::GetDirectoryName($this.MyCommand.Definition)
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
</Types>
And you could then get the script directory as the property
$MyInvocation.ScriptDirectory
Not as compact as the cmd shell accelerator at this point, of course.