使用 Invoke-Command 在虚拟机上运行脚本

问题描述

我写了这段代码

$vmName = $args[0]
$sign_check_tool = $args[1]
$arguments = $args[2]

$remote_session = New-PSSession -VMName $vmName -Credential $cred

try {
Invoke-Command -Session $remote_session -Block {

   $signcheck_output = ./$using:sign_check_tool /accepteula -c $using:arguments

   Write-Output "${signcheck_output }"

}
} catch [Exception] {
    Remove-PSSession $remote_session
    exit 1
}

Exit-PSSession

我想为作为参数接收的多个签名检查工具以及不同的安装程序运行此脚本。但我收到此错误

The term './$using:sign_check_tool' is not recognized as the name of a cmdlet,function,file,or operable 

我想将多种类型的工具作为参数传递给同一个安装程序运行,但我收到了之前的错误。如果您能帮助我,我将不胜感激。

解决方法

我认为您需要将 $using:sign_check_tool 传递给 -ArgumentList 才能被接走,例如:

Invoke-Command -Session $remote_session -Block -ArgumentList $using:sign_check_tool,$using:arguments {
   param($tool,$args)

   $signcheck_output = ./$tool /accepteula -c $args

   Write-Output "${signcheck_output }"

}