使用 Invoke-Command 调用脚本时在 PowerShell 中获取脚本目录 [英] Get script directory in PowerShell when script is invoked with Invoke-Command
问题描述
我有一组 PowerShell 脚本,其中包含一个位于同一文件夹中的通用"脚本,如下所示:
I have a set of PowerShell scripts that include a "common" script, located in the same folder, like this:
# some-script.ps1
$scriptDir = Split-Path -Parent $myinvocation.mycommand.path
. "$scriptDir\script-utils.ps1"
如果直接调用脚本就可以了,例如
This is fine if the script is called directly, e.g.
.\some-script.ps1
但是,如果使用 Invoke-Command 调用脚本,则这不起作用:
However, if the script is called with Invoke-Command, this does not work:
Invoke-Command -ComputerName server01 -FilePath "X:\some-script.ps1"
在这种情况下,事实上,$myinvocation.mycommand
包含脚本的内容,$myinvocation.mycommand.path
为空.
当使用 Invoke-Command 调用脚本时,如何以同样有效的方式确定脚本的目录?
In this case, infact, $myinvocation.mycommand
contains the contents of the script, and $myinvocation.mycommand.path
is null.
How can I determine the script's directory in a way that works also when the script is invoked with Invoke-Command?
注意
最后,这是我实际使用的解决方案:
NOTE
In the end, this is the solution I actually used:
Invoke-Command -ComputerName server01 `
{param($scriptArg); & X:\some-script.ps1 $scriptArg } `
-ArgumentList $something
这也允许向脚本传递参数.
This also allows passing parameters to the script.
推荐答案
我不相信您可以从调用的脚本中进行.来自 get-help invoke-command:
I don't believe you can, from within the invoked script. From get-help invoke-command:
-文件路径在一台或多台远程计算机上运行指定的本地脚本.输入脚本的路径和文件名,或通过管道将脚本路径传递给 Invoke-Command.脚本必须驻留在本地计算机或目录中本地电脑可以访问.使用 ArgumentList 参数指定脚本中的参数值.
-FilePath Runs the specified local script on one or more remote computers. Enter the path and file name of the script, or pipe a script path to Invoke-Command. The script must reside on the local computer or in a directory that the local computer can access. Use the ArgumentList parameter to specify the values of parameters in the script.
**When you use this parameter, Windows PowerShell converts the contents of the specified script file to a script
block, transmits the script block to the remote computer, and runs it on the remote computer.**
当您使用带 -filepath 参数的 invoke-command 时,将从本地计算机上的文件中读取脚本,将其转换为脚本块,然后将其传递给远程计算机.远程计算机无法知道该脚本块是否是从文件中读取的.
When you use invoke-command using the -filepath parameter, the script is read from the file on the local computer, converted to a script block, and that's what gets passed to the remote computer. The remote computer doesn't have any way of knowing if that script block was read from a file.
要让远程计算机知道原始文件路径是什么,您必须告诉它.我认为最简单的方法是编写一个函数来执行调用,并将文件名作为参数传递给调用的脚本.
For the remote computer to know what that original file path was, you'll have to tell it. I think the easiest way to do that would be to write a function to do the invocation, and have it pass the filename to the invoked script as a parameter.
这篇关于使用 Invoke-Command 调用脚本时在 PowerShell 中获取脚本目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!