使用Invoke命令调用脚本时获取PowerShell中的脚本目录

使用Invoke命令调用脚本时获取PowerShell中的脚本目录,powershell,invoke-command,Powershell,Invoke Command,我有一组PowerShell脚本,其中包括位于同一文件夹中的“通用”脚本,如下所示: # some-script.ps1 $scriptDir = Split-Path -Parent $myinvocation.mycommand.path . "$scriptDir\script-utils.ps1" 如果直接调用脚本(例如 .\some-script.ps1 但是,如果使用Invoke命令调用脚本,则此操作不起作用: Invoke-Command -ComputerName serve

我有一组PowerShell脚本,其中包括位于同一文件夹中的“通用”脚本,如下所示:

# some-script.ps1
$scriptDir = Split-Path -Parent $myinvocation.mycommand.path
. "$scriptDir\script-utils.ps1"
如果直接调用脚本(例如

.\some-script.ps1
但是,如果使用Invoke命令调用脚本,则此操作不起作用:

Invoke-Command -ComputerName server01 -FilePath "X:\some-script.ps1"
在本例中,实际上,
$myinvocation.mycommand
包含脚本的内容,
$myinvocation.mycommand.path
为空。
当使用Invoke命令调用脚本时,如何以同样有效的方式确定脚本的目录

注意
最后,这就是我实际使用的解决方案:

Invoke-Command -ComputerName server01 `
  {param($scriptArg); & X:\some-script.ps1 $scriptArg } `
  -ArgumentList $something

这还允许向脚本传递参数。

我不相信您可以从调用的脚本中传递参数。从获取帮助调用命令:

 **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.**
-文件路径 在一台或多台远程计算机上运行指定的本地脚本。输入脚本的路径和文件名,或 管道脚本路径以调用命令。脚本必须驻留在本地计算机上或 本地计算机可以访问。使用ArgumentList参数指定脚本中参数的值

 **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命令时,将从本地计算机上的文件读取脚本,并将其转换为脚本块,这就是传递到远程计算机的内容。远程计算机无法知道该脚本块是否从文件中读取


要让远程计算机知道原始文件路径是什么,您必须告诉它。我认为最简单的方法是编写一个函数来执行调用,并让它将文件名作为参数传递给被调用的脚本。

或者,而不是使用filepath。。您可以传入一个scriptblock,它从所有计算机都有权访问的UNC路径获取脚本。但是,每台计算机都需要设置适当的executionpolicy,以便可以从UNC路径运行该脚本


不过,让我澄清一下,我并不是说要从UNC路径运行脚本,就像它执行远程处理一样,而是仍然使用invoke命令或start job在远程计算机上运行scriptblock。恰好,为了方便起见,该脚本块将从UNC路径运行该脚本。

有任何包含完整源代码的解决方案吗?PowerShell不会有任何其他答案!