list - 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,我做对了。我很难找到像我正在做的例子。谢谢!
解决方案
尝试这个:
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
推荐阅读
- python - 在哪里可以找到 python 中类的方法定义?
- node.js - spawn babel-node ENOENT
- java - 在 Windows 上运行 Java makefile
- javascript - 如何告诉 MathJax 只处理一个节点?
- android - 如何确保 FCM 通知?
- python - Python 代码不断选择相同的随机字符
- javascript - 在 Vega-Lite 的概览+细节显示上应用选择
- python - 如何找到一个单词在一个字符串中重复了多少次?
- javascript - 如何使用 jQuery 创建带有 JSON 输入的 ul-li 结构?
- mysql - 在 AWS 中使用 liquibase 更新 MySQL 5.6.40 DD