首页 > 解决方案 > 从批处理文件调用 PowerShell 脚本以连接远程计算机不起作用

问题描述

当我正常运行 PowerShell 脚本时,它工作正常,从批处理文件调用相同的脚本时会出现问题。

Unt1.ps1脚本:

$linux_app_user="ORXXXX\"+$args[0]
$pass_win=$args[1]
$path=$args[2]
$pass = ConvertTo-SecureString -AsPlainText $pass_win -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 
$linux_app_user, $pass
$Invoke-Command -ComputerName XXXXXXXX.XXXX.XXX.XXXX -Credential $cred -ErrorAction 
Stop -ScriptBlock {
      param($path)
      Invoke-Expression $path
} -Arg $path

cal.bat脚本:

@echo off

SET Server=slXXXXXXXX.XXX.XXXX.com
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%
powershell.exe -ExecutionPolicy  RemoteSigned -File 
  C:\Users\chaj\Documents\String\Unt1.ps1 'XXXX' 'XXXX@321' 'C:\cal.bat'

错误:

[xxxxxx.xx.xxxxx.xxx] 连接远程服务器 xxxxxx.xx.xxxxx.xxx 失败
带有以下错误消息:用户名或密码不正确。
有关详细信息,请参阅 about_Remote_Troubleshooting 帮助主题。
在 C:\Users\chafg\Documents\String\Unt1.ps1:7 char:1
+ $Result=Invoke-Command -ComputerName xxxxxx.xx.xxxxx.xxx -Credenti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : OpenError: (xxxxxx.xx.xxxxx.xxx) [], PSRemotingTransportException
    + FullyQualifiedErrorId:登录失败,PSSessionStateBroken

标签: powershellbatch-fileparameter-passingquoting

解决方案


PowerShell CLI -File参数一起使用时,所有参数都将逐字使用- 除非用"..."(双引号)括起来:与使用时不同-Command'...'(单引号)不会被识别为字符串分隔符

因此,您的命令(此处简化):

powershell.exe -File C:\path\to\Unt1.ps1 'XXXX' 'XXXX@321' 'C:\cal.bat'

导致Unt1.ps1脚本看到带有封闭'的参数,这不是您的意图;例如,它没有按预期$args[0]接收,而是逐字接收。XXXX'XXXX'

解决方法是使用"..."双引号)

powershell.exe -File C:\path\to\Unt1.ps1 "XXXX" "XXXX@321" "C:\cal.bat"

或者,鉴于您的特定示例参数不需要引用(尽管真实的可能):

powershell.exe -File C:\path\to\Unt1.ps1 XXXX XXXX@321 C:\cal.bat

推荐阅读