首页 > 解决方案 > powershell System.Collections.Generic.List[System.String] 和 foreach

问题描述

我发现我有以下通用列表,我可以看到它里面有项目,但是当我尝试运行代码时,它并没有在 foreach 中命中。这是我的代码:

function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile)
{

   $sqlConnection = New-Object System.Data.SqlClient.SqlConnection

   $sqlConnection.ConnectionString = "Server=blah;Database=blah;User ID=blah;Password=blah"  #production #I have an error in this so it doesn't connect
      $sqlConnection.Open()
   if($sqlConnection.State -ne 'Open'){
      $global:ErrorStrings.Add("Exception: $("Couldn't connect to DB with connection string given");;  ") #this gets hit
   }

###

$global:ErrorStrings = New-Object System.Collections.Generic.List[System.String] #System.Object]
$query = "Select blah"
$dir = "C:\blah"

SQLQueryWriteToFile $query $dir

$errorCodeAsString = ""

foreach ($item in $global:ErrorStrings.Members){
   $errorCodeAsString += $item  #this isn't hit
}

知道为什么它没有在我的 foreach 循环列表中找到错误字符串,当我看到它在那里查看 $global:ErrorStrings 时?基于这个foreach list,我做对了。我很难找到像我正在做的例子。谢谢!

标签: listpowershellforeach

解决方案


尝试这个:

function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile)
{
  [System.Data.SqlClient.SqlConnection] $sqlConnection=$null
  [System.Data.SqlClient.SqlCommand] $command=$null 
  try
  {
      $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
      $sqlConnection.ConnectionString = "Server=blah;Database=blah;User ID=blah;Password=blah"
      $command = New-Object System.Data.SqlClient.SqlCommand
      $command.Connection=$sqlConnection
      $command.CommandText=$SQLquery

      $sqlConnection.Open()
      $command.ExecuteNonQuery()

  }
  catch
  {
      $global:ErrorStrings.Add($_.Exception.Message)
  }
  finally
  {
      if ($sqlConnection -ne $null) 
      {
        $sqlConnection.Close()
        $sqlConnection.Dispose()
      }

      if ($command -ne $null) 
      {
        $command.Dispose()
      }
  }

}


$global:ErrorStrings = New-Object System.Collections.Generic.List[System.String]
$query = "Select blah"
$dir = "C:\blah"

$global:ErrorStrings.Clear()
SQLQueryWriteToFile $query $dir

$errorCodeAsString=""

for ($i = 0; $i -lt $global:ErrorStrings.Count; $i++)
{ 
    $errorCodeAsString +=$global:ErrorStrings.Item($i)
}

$errorCodeAsString

推荐阅读