Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to convert %~dp0

112 views
Skip to first unread message

Gil Novak

unread,
Sep 7, 2006, 3:17:01 PM9/7/06
to

For those who may be unfamiliar, if I run a dos batch script that's not in
my current working directory, then I can include this in the script to refer
to the directory that the script is actually in:
%~dp0

Is there a way to do this in PowerShell?

Thanks,
Gil

Mark [exmsft]

unread,
Sep 7, 2006, 3:36:50 PM9/7/06
to
Hello 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


Gil Novak

unread,
Sep 7, 2006, 4:46:02 PM9/7/06
to

Thank you!

Is this part of some documentation anywhere? i.e. Is there someplace I
could find information like this aside from this forum?


/\/\o\/\/ [MVP]

unread,
Sep 7, 2006, 4:50:01 PM9/7/06
to
www.microsoft.com/PowerShell

Look also for documentation Set there

Greetings /\/\o\/\/

Alex K. Angelopoulos [MVP]

unread,
Sep 7, 2006, 5:18:52 PM9/7/06
to

"Mark [exmsft]" <MarkI...@nospam.nospam> wrote in message
news:c3aa33fbe50dc8...@msnews.microsoft.com...
> Hello 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)


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.


0 new messages