运行 多个服务器上的 .bat 文件

Running a .bat file on several servers

我目前正尝试在大约 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 一旦它到达服务器,目前它似乎只是在复制。

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

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

microsoft:

-PassThru

Returns a process object for each process that the cmdlet started. By default, this cmdlet does not generate any output.

-Wait Indicates that this cmdlet waits for the specified process and its descendants to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the processes finish.

-PassThru return你是进程对象,可以查看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,它将 return 您作为控制台的标准输出。

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

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