在多台服务器上运行.bat文件

时间:2019-05-13 12:19:27

标签: powershell batch-file server rdp

我目前正在尝试在约150台服务器上运行.bat文件。我可以像没有问题一样运行脚本-将.bat复制到服务器,但是它似乎根本没有执行。

主要在Windows 2012服务器上运行。

#Variables
$servers = "D:\Apps\Davetest\servers.txt"
$computername = Get-Content $servers
$sourcefile = "D:\Apps\Davetest\test.bat"
#This section will install the software 
foreach ($computer in $computername) 
{
    $destinationFolder = "\\$computer\C$\Temp"
    <#
       It will copy $sourcefile to the $destinationfolder. If the Folder does 
       not exist it will create it.
    #>

    if (!(Test-Path -path $destinationFolder))
    {
          New-Item $destinationFolder -Type Directory
    }
    Copy-Item -Path $sourcefile -Destination $destinationFolder
    Invoke-Command -ComputerName $computer -ScriptBlock {Start-Process 'c:\Temp\test.bat'}

}

我正在寻找它来运行.bat,一旦它击中服务器,并且目前看来它只是在复制。

1 个答案:

答案 0 :(得分:1)

那是因为Start-Process立即返回。使用-Wait参数。

Start-Process -FilePath 'c:\Temp\test.bat' -NoNewWindow -Wait -PassThru

microsoft

  

-PassThru

     

为cmdlet启动的每个进程返回一个进程对象。默认情况下,此cmdlet不会生成任何输出。

     

-等待   指示此cmdlet在接受更多输入之前等待指定的过程及其后代完成。此参数隐藏命令提示符或保留窗口,直到进程完成。

-PassThru返回一个过程对象,您可以在其中检查ExitCode参数:

$p = Start-Process -FilePath your_command -ArgumentList "arg1", "arg" -NoNewWindow  -Wait -PassThru
if ($p.ExitCode -ne 0) {
   throw "Failed to clone $buildItemName from $buildItemUrl to $($tmpDirectory.FullName)"
}

作为Start-Process的替代方法,您还可以使用Invoke-Expression,它将返回控制台的标准输出。

要检查Invoke-Expression是否成功,可以使用:

 $output = Invoke-Expression $command
 if ((-not $?) -or ($LASTEXITCODE -ne 0)) {
        throw "invoke-expression failed for command $command. Command output: $output"
 }
相关问题