Powershell 嵌套 for 循环以重新启动服务

问题描述

我的目标是循环遍历所有设备,停止所有这些设备的特定服务(在本例中为 IntenAudioService),然后终止与该服务相关的特定任务(让我们说任务 IntelX 和任务 IntelY,如果它们存在)

然后再次循环并重新启动这些服务。这可以在 1 个 for 循环中完成吗?语法正确吗?

    $devices= <<user can populate devices in this object. DeviceName or deviceid??>>
    
    >Foreach ($device in $devices){
        Invoke-Command -ComputerName $device {
        net-stop IntelAudioService

         taskkill /IM IntelX.exe /F
         net start IntelAudioService
    }
}

如果我还想为每台设备设置一个服务怎么办?像这样吗?

   foreach ($device in $devices){
Invoke-Command -ComputerName $device {
        Set-Service -Name BITS -StartupType Automatic
    }
    }

解决方法

试试这个,注意你可以同时 Invoke-Command 到多个主机名。您还可以同时使用多台计算机创建 New-PSession

$ErrorActionPreference = 'Stop'
$devices = 'Hostname1','Hostname2'

$serviceName = 'IntelAudioService' # This can be an array
$processName = 'IntelX' # This can be an array

# Note: Looping through the devices an attempting to establish a
# PSSession like below is good if you're not sure if the remote host
# is up or if the device name is the right one,etc. Using a Try {} Catch {}
# statement in this case will let you know if you couldn't connect with a
# specific remote host and which one.

# You can also simply do: $session = New-PSSession $devices without
# any loop which will be a lot faster of course,however,# if you fail to connect to one of the remote hosts
# you will get an error and the the PSSession cmdlet will stop.

$session = foreach($device in $devices)
{
    try
    {
        New-PSSession $device
    }
    catch
    {
        Write-Warning $_
    }
}

Invoke-Command -Session $session -ScriptBlock {
    Get-Service $using:serviceName | Stop-Service -Force -Verbose
    Get-Process $using:processName | Stop-Process -Force -Verbose
    Start-Service $using:serviceName -Verbose
    # Set-Service -Name $using:serviceName -StartupType Automatic
}

Remove-PSSession $session