您不需要使用Select-Object。 Get-Service 直接接受服务名称的管道输入
$Services = Get-Content .\services.txt | Get-Service
ForEach( $Service in $Services )
{
If( $Service.StartType -eq 'Manual' -and $Service.Status -eq 'Running' )
{
Set-Service -InputObject $service -StartupType 'Automatic'
}
# Add more logic as needed here!
}
但是,您的问题尚不清楚您将如何做出有关服务的决定。当然,有些服务应该是手动的、自动的等……您是否希望根据文本文件指示所需的状态?
如果是这样,一个简单的解决方案可能是将配置存储在 CSV 文件中。格式为<ServiceName>, <DesiredStartType>。然后我们可以重新配置代码以应用所需的更改并更好地反馈给控制台。
根据评论更新
既然您确定了 csv 文件,并在 @Theo's helpful answer 上进一步构建。这是使用 CSV 输入文件的另一种方法。在这种情况下,我在提取服务后将输入转换为哈希表。这样可以轻松引用所需的配置。
假设与 Theo 的回答相同的 CSV 布局:
Service,StartType,Status
Service A,Manual,Running
Service B,Automatic,Running
Service C,Manual,Stopped
$DesiredConfig = Import-Csv c:\Temp\Services.csv
$Services = $DesiredConfig.Service | Get-Service
# Flip config data to a dictionary
$DesiredConfig = $DesiredConfig | Group-Object -Property Service -AsHashTable -AsString
ForEach( $Service in $Services )
{
$DesiredStart = $DesiredConfig[$Service.Name].StartType
$DesiredStatus = $DesiredConfig[$Service.Name].Status
If( $Service.StartType -ne $DesiredStart -or $Service.Status -ne $DesiredStatus )
{
Write-Host "Changing $($Service.Name) StartType/Status : $($Service.StartType) / $($Service.Status) > $DesiredStart / $DesiredStatus) ..."
$Service = $Service | Set-Service -StartupType $($DesiredConfig[$Service.Name].StartType) -Status $DesiredStatus -PassThru
# You don't need to reassign or use -PassThru, however if you are going to post-report this spares you the need to
# re-get-services. You are going to run the set command anyhow!
}
}
# Not needed, but just to check...
$Services | Format-Table Name,Displayname,STartType,Status -AutoSize
我没有对此进行测试,但方法应该是可靠的。
让我知道这是否有帮助。谢谢。