PowerShell: Run command from script's directory Ask Question

PowerShell: Run command from script's directory Ask Question

I have a PowerShell script that does some stuff using the script’s current directory. So when inside that directory, running .\script.ps1 works correctly.

Now I want to call that script from a different directory without changing the referencing directory of the script. So I want to call ..\..\dir\script.ps1 and still want that script to behave as it was called from inside its directory.

How do I do that, or how do I modify a script so it can run from any directory?

ベストアンサー1

Do you mean you want the script's own path so you can reference a file next to the script? Try this:

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Write-host "My directory is $dir"

You can get a lot of info from $MyInvocation and its properties.

If you want to reference a file in the current working directory, you can use Resolve-Path or Get-ChildItem:

$filepath = Resolve-Path "somefile.txt"

EDIT (based on comment from OP):

# temporarily change to the correct folder
Push-Location $dir

# do stuff, call ant, etc

# now back to previous directory
Pop-Location

There's probably other ways of achieving something similar using Invoke-Command as well.

おすすめ記事