首页 > 解决方案 > 创建用于在多个服务器上启动服务的 CSV 文件

问题描述

我创建了一个 tsv 文件来列出服务器和服务,如下所示: TSV 文件如下:

Hostname    Services
=========================
             
Server01    SP4AdminV4,SPTraceV4,SPWriterV4,WAS,W3SVC
Server02    SP4AdminV4,SPTraceV4,SPWriterV4,WAS,W3SVC,SPSearchHostController, OSearch16

PowerShell 命令

Import-csv C:\ServerServerList.tsv  
$Services = $_.Services -Split ',' 
Start-Service -Computer 'Server01' -Name $Services 

然后我收到以下错误:

Start-Service: Cannot Bind Argument to parameter 'Name' because it is an empty string.
At Line:3 char:43
+ Start-Service -Computer $_.Hostname -Name **$Services**
                                           
+
         +categoryinfo: InvalidData (:) [Start-Service], ParameterBindingValidationException
         +FullyQualifiedErrorId: ParameterArgumentValidationErrorEmptyStringNotAllowed, 
          Microsoft.Powershell.Commands.StartServiceCommand

标签: arrayspowershellcsvserverautomation

解决方案


我一眼就能发现几个问题。首先,您似乎没有$Services正确分配。第二你Start-Service没有-ComputerName参数。

为了解决这个问题,您可以将 useGet-Service与通过管道Set-Service隐式使用参数结合使用。-InputObject

Import-csv C:\ServerServerList.tsv -Delimiter "`t" |
ForEach-Object{
    $Services = $_.Services -Split ','
    Get-Service -Computer $_.HostName -Name $Services
} |
Start-Service

如您所述,我假设这是一个制表符分隔的文件。还假设服务以使拆分正确的方式列出。

循环将[System.ServiceProcess.ServiceController]对象发送到管道中。这些都绑定到-InputObject参数。在内部,Start-Service 使用该.MachineName属性在远程系统上进行更改。

警告: Get/Set-Service在这种情况下并不总是正确报告错误。在操作员帐户无权访问远程系统的情况下,我遇到的主要障碍是误导性错误和/或静默故障。


推荐阅读