【问题标题】:Get script directory in PowerShell when script is invoked with Invoke-Command使用 Invoke-Command 调用脚本时在 PowerShell 中获取脚本目录
【发布时间】:2011-06-22 20:27:28
【问题描述】:

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

# some-script.ps1
$scriptDir = Split-Path -Parent $myinvocation.mycommand.path
. "$scriptDir\script-utils.ps1"

如果直接调用脚本就可以了,例如

.\some-script.ps1

但是,如果使用 Invoke-Command 调用脚本,这将不起作用:

Invoke-Command -ComputerName server01 -FilePath "X:\some-script.ps1"

在这种情况下,实际上$myinvocation.mycommand 包含脚本的内容,而$myinvocation.mycommand.path 为空。
当使用 Invoke-Command 调用脚本时,如何确定脚本的目录?

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

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

这也允许将参数传递给脚本。

【问题讨论】:

  • 任何有完整源代码的解决方案?

标签: powershell invoke-command


【解决方案1】:

我不相信你可以从调用的脚本中。从 get-help 调用命令:

-文件路径 在一台或多台远程计算机上运行指定的本地脚本。输入脚本的路径和文件名,或 通过管道将脚本路径传递给 Invoke-Command。该脚本必须驻留在本地计算机上或位于 本地计算机可以访问。使用 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-command 时,将从本地计算机上的文件中读取脚本,将其转换为脚本块,然后将其传递给远程计算机。远程计算机无法知道该脚本块是否是从文件中读取的。

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

【讨论】:

  • 不希望 PowerShell 有任何其他答案!
【解决方案2】:

或者,而不是使用文件路径.. 你可以传入一个脚本块,它从所有机器都可以访问的 UNC 路径中点源脚本。但是,每台机器都需要设置适当的执行策略,以便它们可以从 UNC 路径运行该脚本

让我明确一点,我并不是说从 UNC 路径运行脚本,就好像它执行远程处理一样,而是仍然使用调用命令或启动作业在远程计算机上运行脚本块。为了方便起见,该脚本块恰好会从 UNC 路径运行脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多