PowerShell在检查IIS8日志自定义字段中是否存在值时避免嵌套循环(提高代码效率)

问题描述 投票:0回答:1

我的PS脚本使用服务器列表和自定义日志字段名称列表。服务器列表和自定义日志字段列表已分配了变量。该脚本检查每个服务器中是否存在大约5个自定义字段名称。我使用嵌套的ForEach和if语句来完成此操作。我知道使用嵌套的ForEach和if语句不是最有效的代码。注意:每个服务器可以有1到任意数量的自定义日志字段,我只想检查是否存在必需的自定义日志字段。我有一个保存这些值的外部CSV文件。因此,如果我不必遍历服务器上的所有自定义日志字段,那会更好。

$IISServers = Import-Csv C:\srv.csv

$STIG_CustomFields = Import-Csv C:\log_stig.csv

ForEach($IISServer in $IISServers){
  $IISServerName = $($IISServer.Host)

  try{
    invoke-command -ComputerName $IISServerName -ScriptBlock{

      $SiteLogFileCustomFields = Get-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -filter "system.applicationHost/sites/site/logFile/customFields" -Name 'Collection'

      ForEach ($STIG_CustomField in $using:STIG_CustomFields){

          ForEach($SiteLogFileCustomField in $SiteLogFileCustomFields){

              if($SiteLogFileCustomField.logFieldName -contains $STIG_CustomField.LogFieldName){
                  write-output "Yes"
              }
              else{
                  write-output "No"
              }
          }
      }
    }
  }
  catch{
      "Invoke failed"
  }
}

问题是,我不知道$ SiteLogFileCustomFields变量是什么类型。我认为这是一个集合,因为我可以使用$ SiteLogFileCustomFields [0] .LogFieldName访问其中的元素,但是我认为我可以做类似if($ SiteLogFileCustomFields -contains“ SomeName”)的操作,但是那没有工作。

任何见解将不胜感激。

powershell iis
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.