我正在编写一个脚本,该脚本将传入两个变量和一个csv文件,以更改csv文件中列出的计算机上的服务。
该命令将采用以下格式:ex。 start SQLService
或stop PBIService
给定的csv文件:
服务器,服务
server1,SQLService
server2,PBIService
server3,PBIService
param($task, $service) #arguments from cmd line input
if($task -eq "start")
{
Set-Variable -Name "task" -Value "running"
}
elseif($task -eq "stop")
{
Set-Variable -Name "task" -Value "stopped"
}
if($service -eq "SQLService")
{
Set-Variable -Name "SQLsvc" -Value "SQLService"
}
elseif($service -eq "PBIService")
{
Set-Variable -Name "PBIsvc" -Value "PBIService"
}
Import-CSV .\csvfile.csv |
ForEach {
if($_.service -eq "SQLService")
{
$getService = Get-Service $SQLsvc -ComputerName $_.Server
$oldstatus = $getService.status
$getService |
Set-Service -Status $task -PassThru |
Select MachineName, Name, Status,
@{n='OldStatus';e={$oldStatus}}
}
elseif($_.Service -eq "PBIService")
{
$getService = Get-Service $PBIsvc -ComputerName $_.Server
$oldstatus = $getService.status
$getService |
Set-Service -Status $task -PassThru |
Select MachineName, Name, Status,
@{n='OldStatus';e={$oldStatus}}
}
} |
tee output.txt
但是,当我出于某种原因运行它时,它会影响所有服务...
MachineName Name Status OldStatus
----------- ---- ------ ---------
server1 SQLService Running Running
server2 PBIService Running Running
Set-Service : Service 'Microsoft Monitoring Agent Audit Forwarding (AdtAgent)' cannot be started due to the following
error: Cannot start service AdtAgent on computer 'server3'.
+ Set-Service -Status $task -PassThru |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], Se
rviceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.SetServiceCommand
server3 AdtAgent Stopped ...ed...}
Set-Service : Service 'AllJoyn Router Service (AJRouter)' cannot be started due to the following error: Cannot start
service AJRouter on computer 'server3'.
+ Set-Service -Status $task -PassThru |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], Se
rviceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.SetServiceCommand
server3 AJRouter Stopped ...ed...}
此外,为什么如果我命令start SQLService
,PBIService也同时启动?由于某种原因,该条件无法正常运行...
在这种情况下,唯一受影响的服务器和服务应该是server1,因为在满足条件的情况下,该服务器具有service = SQLService
答案 0 :(得分:1)
在foreach中,您无需检查作为参数传递的内容。
我建议仅处理来自csv的与通过的$Service
匹配的行
Import-CSV .\csvfile.csv | Where-Object Service -eq $Service |
if / elseif中的脚本块与{strong>两者源自传递的$ service的$SQLsvc
/ $PBIsvc
相同,因此可以合并并直接使用$服务