我是 PowerShell 的新手,我什至不知道如何正確使用 Google。
這就是我想要做的:在多臺計算機上運行一些命令。
我可以讓他們在計算機 A 上運行 command1,然后在計算機 A 上運行 command2,然后在計算機 A 上運行 command3……然后在計算機 B 上運行 command1 command2 在計算機 B 上……等等
但我想在所有計算機上運行 command1 然后在所有計算機上運行 command2 然后在 command3 ...等
所以這就是現在的情況:1A 2A 3A 1B 2B 3B 1C 2C 3C...
是否可以在 if $state -eq 'Start' 陳述句中執行此操作?
1A 1B 1C 2A 2B 2C 3A 3B 3C...而不創建另一個函式?
我不想扭轉一切,只是我需要遵循該模式的“開始”宣告。
這基本上是我現在擁有的:
$Computers = "ComputerA","ComputerB","ComputerC"
function Set-CService {
param(
[Parameter(Mandatory)]
[ValidateSet('Start','Stop','Restart','Install')]
[string]$State,
[Parameter(Mandatory, ValueFromPipeline)]
[array]$Computers
)
process {
$ErrorActionPreference = "SilentlyContinue"
If ($state -eq 'Start') {
foreach ($Computer in $Computers) {Write-Host "statement1 on $Computer"}
foreach ($Computer in $Computers) {Write-Host "statement2 on $Computer"}
foreach ($Computer in $Computers) {Write-Host "statement3 on $Computer"}
}
foreach ($Computer in $Computers){
If ($State -eq 'Stop') {Write-Host "It is stopping on $Computer"}
If ($state -eq 'Restart') {
Write-Host "Restart statement1 on $Computer"
write-host "Restart statement2 on $Computer"
Write-Host "Restart statement3 on $Computer"}
If ($State -eq 'Install') {
Write-Host "Install statement1 on $Computer"
write-host "Install statement2 on $Computer"
Write-Host "Install statement3 on $Computer"}
}
}
}
$Computers | Set-CService -State Start
uj5u.com熱心網友回復:
使用Invoke-Command -AsJob呼叫遠程作業負載,因為后臺作業:
If ($state -eq 'Start') {
# Kick off remoting jobs on each computer in $Computers
$jobs = Invoke-Command -ComputerName $Computers -Scriptblock {
Write-Host "statement1 on $env:ComputerName"
Write-Host "statement2 on $env:ComputerName"
Write-Host "statement3 on $env:ComputerName"
} -AsJob
# Wait for jobs to succeed, then receive the output
$jobs |Receive-Job -Wait
}
uj5u.com熱心網友回復:
我想這就是你的意思。每個陳述句在所有 3 臺計算機上并行運行,但在繼續執行下一個陳述句之前會等待。
$computers = echo a001 a002 a003
$statements = {Write-Host "statement1 on $env:Computername"},
{Write-Host "statement2 on $env:computername"},
{Write-Host "statement3 on $env:Computername"}
foreach ($statement in $statements) {
invoke-command $computers $statement
}
statement1 on A001
statement1 on A002
statement1 on A003
statement2 on A001
statement2 on A002
statement2 on A003
statement3 on A003
statement3 on A002
statement3 on A001
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364520.html
