【问题标题】:PowerShell will not run batch file on another machinePowerShell 不会在另一台机器上运行批处理文件
【发布时间】:2018-07-27 07:24:04
【问题描述】:

我有一个位于 VM 上的 PowerShell 脚本。该脚本创建一个 PSSession 并用于运行位于物理机上的批处理文件。但是,当我运行脚本时什么都没有发生。

PowerShell:

$Username = "Domain\User"
$Password = ConvertTo-SecureString "Password*" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($Username, $password)
$session = New-PSSession -ComputerName "K2" -Credential $cred

Enter-PSSession -Session $session

Invoke-Command -ComputerName "K2" -ScriptBlock {
    Invoke-Expression -Command: "C:\Windows\system32\cmd.exe c/ 'cd C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner'"
    Invoke-Expression -Command: "C:\Windows\system32\cmd.exe c/ 'START "" /wait PS_TR.bat'"

    #Invoke-Expression -Command: "C:\Windows\system32\cmd.exe Call c/ C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner\PS_TR.bat"
}

Exit-PSSession
Get-PSSession | Remove-PSSession

PS 输出:

PS C:\> C:\Users\User\Desktop\PS_TR.ps1 Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。版权所有。 C:\用户\用户\文档> Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。版权所有。 C:\用户\用户\文档>

当我在Invoke-Command 中运行以下行时,它成功地在物理机桌面上创建了一个文件夹:

mkdir "C:\Users\administrator.HYPERSPHERIC\Desktop\NewFolder"

所以我不明白为什么脚本没有运行批处理文件。

我已经尝试使用上面和下面代码中的行:

  • Invoke-Expresson
  • Invoke-Item
  • Start-Process
  • Start-Job

从上面可以看出,我没有得到任何像样的输出,因此我发现很难调试。

直接从物理机运行批处理文件也可以按预期工作。

【问题讨论】:

    标签: powershell batch-file


    【解决方案1】:

    不要使用Invoke-Expression。无论您需要做什么工作,都是almost always the wrong tool。此外,如果您执行cmd /c cd ... 会更改仅针对该一个 CMD 进程的工作目录。它不会影响您正在启动的下一个 CMD 进程。

    改变这个:

    Invoke-Command -ComputerName "K2" -ScriptBlock {
        Invoke-Expression -Command: "C:\Windows\system32\cmd.exe c/ 'cd C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner'"
        Invoke-Expression -Command: "C:\Windows\system32\cmd.exe c/ 'START "" /wait PS_TR.bat'"
    }
    

    进入这个:

    Invoke-Command -ComputerName "K2" -ScriptBlock {
        Set-Location 'C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner'
        & '.\PS_TR.bat'
    }
    

    问题就会消失。

    【讨论】:

    • 这样我得到以下错误The term 'PSTR.bat' is not recognized as the name of a cmdlet, function, script file, or operable program.
    • @Ross 我的错。 PowerShell 不包含 PATH 中的当前工作目录,因此它必须是 & '.\PS_TR.bat'。更正了我的答案。
    • 谢谢,这似乎奏效了。但导致我进入另一个我将调查的问题。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2018-07-08
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多