gpt4 book ai didi

powershell - 使用Invoke-Command调用脚本时在PowerShell中获取脚本目录

转载 作者:行者123 更新时间:2023-12-04 18:15:01 24 4
gpt4 key购买 nike

我在同一文件夹中有一组PowerShell脚本,其中包括一个“common”脚本,如下所示:

# 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为null。
使用Invoke-Command调用脚本时,如何以一种也可以使用的方式确定脚本的目录?

注意
最后,这是我实际使用的解决方案:
Invoke-Command -ComputerName server01 `
{param($scriptArg); & X:\some-script.ps1 $scriptArg } `
-ArgumentList $something

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

最佳答案

我不相信您可以从调用的脚本中找到。从get-help invoke-command:

-文件路径
在一台或多台远程计算机上运行指定的本地脚本。输入脚本的路径和文件名,或者
通过管道将脚本路径传递给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 - 使用Invoke-Command调用脚本时在PowerShell中获取脚本目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5219461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com