PowerShell:从脚本目录运行命令 [英] PowerShell: Run command from script's directory

查看:78
本文介绍了PowerShell:从脚本目录运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PowerShell 脚本,它使用脚本的当前目录执行一些操作.因此,当在该目录中时,运行 .\script.ps1 可以正常工作.

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.

现在我想从不同的目录调用该脚本而不更改脚本的引用目录.所以我想调用 ..\..\dir\script.ps1 并且仍然希望该脚本按照从其目录内部调用的方式运行.

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?

推荐答案

您的意思是您想要脚本自己的路径,以便您可以引用脚本旁边的文件?试试这个:

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"

您可以从 $MyInvocation 及其属性中获取大量信息.

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

如果要引用当前工作目录中的文件,可以使用 Resolve-Path 或 Get-ChildItem:

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"

编辑(基于 OP 的评论):

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

可能还有其他使用 Invoke-Command 实现类似功能的方法.

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

这篇关于PowerShell:从脚本目录运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆