【发布时间】:2018-07-05 23:05:53
【问题描述】:
我在机器 A 上有一个 powershell 脚本,它使用 PSSession 在机器 B 上调用命令。机器 B 有一个 powershell 脚本,它接受 4 个参数。当我使用 4 个参数作为变量(它们必须是)调用此脚本时,它们作为空字符串/null 传递。当我将它们作为字符串传递时(例如-Argument1 "Hello"),该字符串将作为“Hello”而不是NULL/空字符串传递。
谁能告诉我为什么这些没有正确传递以及如何解决?
客户端的powershell版本是5.1.17134.112。远程机器使用5.1.14393.2248。这些版本是通过运行$PSVersionTable.PSVersion 获得的。
客户端正在使用Windows 10 Pro 10.0.17134。服务器正在使用Windows 2016 Datacenter 10.0.14393,并在 Azure 上作为 VM 运行。
我曾尝试使用Script.ps1 -Argument1 $ClientArgument1 -Argument2 $ClientArgument2 ... 传递变量并使用ArgumentList 将逗号分隔的值传递给脚本,但是这两种尝试都导致无法打印。
我注意到当我使用-Argument1 "Hello" -Argument2 $ClientArgument2 -Argument3 $ClientArgument3 -Argument4 $ClientArgument4 时,Hello 确实会被打印出来。
代码
连接到远程机器的客户端
$ErrorActionPreference = "Stop"
#Create credentials to log in
$URL = 'https://url.to.server:5986'
$Username = "username"
$pass = ConvertTo-SecureString -AsPlainText 'password' -Force
$SecureString = $pass
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString
$ClientArgument1 = "Argument 1"
$ClientArgument2 = "Argument 2"
$ClientArgument3 = "Argument 3"
$ClientArgument4 = "Argument 4"
#Create the remote PS session
$sessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ConnectionUri $URL -Credential $MySecureCreds -SessionOption $sessionOption
#Call the remote script and pass variables
Invoke-Command -Session $session -Command {C:\Path\To\Script\On\Remote\Machine\Script.ps1 -Argument1 $ClientArgument1 -Argument2 $ClientArgument2 -Argument3 $ClientArgument3 -Argument4 $ClientArgument4}
#Note: Command is used because Command allows me to execute a script that is located on disk of the remote machine
远程机器的调用脚本
param(
[String]$Argument1,
[String]$Argument2,
[String]$Argument3,
[String]$Argument4
)
Write-Host 'Results of the 4 parameters passed into this script:'
Write-Host $Argument1
Write-Host $Argument2
Write-Host $Argument3
Write-Host $Argument4
Write-Host "The results have been printed"
预期和实际结果
预期结果:
Results of the 4 parameters passed into this script:
Argument 1
Argument 2
Argument 3
Argument 4
The results have been printed
实际结果
Results of the 4 parameters passed into this script:
The results have been printed
非常感谢您的宝贵时间!
【问题讨论】:
-
我建议的第一件事是删除参数上的
[string]。我不知道这是问题所在,但这不是必需的,而且我过去曾看到强制输入会做一些奇怪的事情。 -
您没有确定参数的范围。将
$using:范围用于远程命令。
标签: windows powershell azure remote-access