【问题标题】:Creating a CSV file to use for starting services on multiple servers创建用于在多个服务器上启动服务的 CSV 文件
【发布时间】:2021-11-05 00:00:25
【问题描述】:

我创建了一个 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

【问题讨论】:

    标签: arrays powershell csv server automation


    【解决方案1】:

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

    要解决这个问题,您可以使用 Get-ServiceSet-Service 通过管道隐式使用 -InputObject 参数。

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

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

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

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

    【讨论】:

    • 嗯,这很有趣,我不知道您可以通过管道发送到Start-Service 以获取远程机器。也不知道 Tab 分隔文件。非常好!
    【解决方案2】:

    我确信有更简单的方法可以解决这个问题,但是,这就是我得到的:

    # import csv and save to variable.
    $CSV = Import-Csv -Path 'C:\ServerServerList.tsv' 
        
    # Use a foreach loop to iterate throw csv 
    # one row at a time - assigning the current iteration to $Row.
        foreach ($Row in $CSV) {
    
            # Split services into an array
            $Services = ($Row.Services -split ',').Trim()
            
            # Invoke the start-service call due to it not 
            # having it's own -ComputerName parameter to work with.+
            Invoke-Command -ScriptBlock {
    
                # Start the service using the newly created array of $Services.
                # Note: we must use a *Remote Variable* to pass over our local variable
                # by specifying the $using: keyword.
                Start-Service -Name $using:Services -PassThru -WhatIf
    
            } -ComputerName $Row.Hostname
    
        }
    

    - 这是未经测试的 -

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 2022-11-15
      • 1970-01-01
      • 2018-04-26
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      相关资源
      最近更新 更多