关于多个集合的Powershell foreach

时间:2018-11-01 16:20:32

标签: powershell foreach powershell-v5.0

因此,我有一个Powershell脚本正在与我一起向社区寻求帮助。我必须先言一点,在交流我想做的事情时,我并非总是最好的,部分原因是我没有编程经验,所以请多多包涵,并提出问题/纠正我,如果我使用错误的词来解释我的意思。

话虽如此,这就是我想要做的:

同时增加服务和启动类型:

  • 在服务器X($ rebootingServer)上停止服务A($ services)

  • 在服务器X($ rebootingServer)上禁用服务A($ services)

      

    鉴于:我们知道在脚本运行之前在服务器Y 上禁用了服务A

  • 在服务器Y上基于文本文件列表$ startuptypes启用服务A

  • 在服务器Y上启动服务A
  • 漂洗并重复直到$ services和$ startuptypes在每个列表的末尾

因此,假设$ services具有:
bits appmgmt

和$ startuptypes具有:

Automatic Manual

我希望分别应用它们(位>自动appmgmt>手动)

这里是我到目前为止的内容:

$services = Get-Content "C:\TEMP\services.txt"
$Startuptypes = Get-Content "C:\TEMP\StartupTypes.txt"
$RebootingServer = Read-Host 'Name of the server that you are bringing down'
$FailoverServer = Read-Host 'Name of the server it is failing over to'


#foreach ($service in $services && $Startuptype in $Startuptypes) {

Invoke-Command -ComputerName $RebootingServer -ArgumentList $service - ScriptBlock {param($service) Stop-Service $service}
Start-Sleep -s 3
Invoke-Command -ComputerName $RebootingServer -ArgumentList $service - ScriptBlock {param($service) set-service $service -StartupType Disabled}
Start-Sleep -s 10
Invoke-Command -ComputerName $FailoverServer -ArgumentList $service $StartupType -ScriptBlock {param($service,$startuptype) Set-Service $service -StartupType $startuptype}
Start-Sleep -s 3
Invoke-Command -ComputerName $FailoverServer -ArgumentList $service - ScriptBlock {param($service) Start-Service $service}
Start-sleep -s 10
}

“ for each”语句是我想要它执行的操作的伪代码,但不确定是否存在或如何相应地编写它。我什至不知道该怎么称呼。有多个条件?除此之外,我该如何正确地写出我要完成的工作?感谢您对高级的任何帮助。

1 个答案:

答案 0 :(得分:1)

听起来您想枚举对应对 中的两个集合的元素:在迭代1中,处理集合A的元素1和集合B的元素1 ,...

# Sample collections.
# Note that their counts must match.
$services     = 'serviceA', 'serviceB', 'serviceC'
$startupTypes = 'automatic', 'manual', 'disabled '

$i = 0 # helper index var.
foreach ($service in $services) { # enumerate $services directly

   # Using the index variable, find the corresponding element from 
   # the 2nd collection, $startupTypes, then increment the index.
   $startupType = $startupTypes[$i++]

   # Now process $service and $startupType as needed.
}