PowerShell将不会在另一台计算机上运行批处理文件

时间:2018-07-27 07:24:04

标签: powershell batch-file

我有一个位于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 [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\User\Documents>
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\User\Documents>

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

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

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

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

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

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

还可以直接从物理机运行批处理文件,如预期的那样。

1 个答案:

答案 0 :(得分:4)

请勿使用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'
}

问题将消失。

相关问题