【问题标题】:Running bat file via powershell on multiple servers在多台服务器上通过 powershell 运行 bat 文件
【发布时间】:2015-11-04 11:42:36
【问题描述】:

我正在使用 powershell 尝试在多台服务器上远程运行安装脚本,但有点卡住了。

以下是我目前所拥有的。 Computers.txt 包含我要运行安装的所有服务器的列表。这些都位于同一个域上。然后我映射一个驱动器浏览到脚本所在的共享,然后运行安装脚本。

$computers = Get-Content -Path c:\temp\Computers.txt

New-PSDrive –Name “S” –PSProvider FileSystem –Root “\\dc1-app01\apps” –Persist

Start-Process -FilePath S:\createfile.bat

我希望我缺少很多东西才能使它起作用? bat 文件本身非常复杂,所以目前我不想将其更改为 powershell。

我正在运行的 PC 也是这些服务器上的受信任主机。

感谢您的意见,我是 powershell 新手

谢谢

【问题讨论】:

  • 真正的问题是什么?

标签: powershell powershell-3.0


【解决方案1】:

我认为您错过了遍历服务器列表(数组)的循环:

$VerbosePreference = 'Continue'

$Computers = Get-Content -Path c:\temp\Computers.txt

Foreach ($C in $Computers) {

    Write-Verbose "Start batch file as a job on $C"

    Invoke-Command -ComputerName $C -ScriptBlock {
        New-PSDrive –Name 'S' –PSProvider FileSystem –Root '\\dc1-app01\apps' –Persist
        Start-Process -FilePath S:\createfile.bat -Wait
    } -AsJob
}

Write-Verbose 'Waiting for all jobs to finish'
Wait-Job
Write-Verbose 'Showing job results:'
Get-Job | Receive-Job

我也把它做成了一份工作,所以你可以同时在多台服务器上运行它。

为了更简单,您不必映射驱动器,只需在 Invoke-CommandScriptBlock 中尝试此操作即可:

& '\\dc1-app01\apps\createfile.bat'

【讨论】:

  • 感谢您的回复。我尝试运行您推荐的命令,但系统提示我输入 ID 参数?似乎开始很好地运行远程作业。我当前运行的批处理文件是一个简单的创建文件。有什么想法吗?