string Powershell - 将 System.Data.DataRow 解析为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12944824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:39:09  来源:igfitidea点击:

Powershell - Parse System.Data.DataRow to String

stringpowershelldatarow

提问by infinity

I need your inputs on how to convert the output from a SQL query into a string in powershell. I am currently doing the following

我需要您输入有关如何将 SQL 查询的输出转换为 powershell 字符串的信息。我目前正在做以下事情

function ExecuteFromScriptRowset($connectionParams, $file)
{
     return (invoke-sqlcmd @connectionParams 
             -inputFile $file -MaxCharLength 8000000)
}

I use the above function to call a .sql file that does something like

我使用上面的函数来调用一个 .sql 文件,它执行类似的操作

SELECT Names FROM tblXXX

Here is the actual powershell code that I use to invoke the SQL stored proc

这是我用来调用 SQL 存储过程的实际 powershell 代码

$output = ExecuteFromScriptRowset $someDB (Resolve-Path '.\selectXXX.sql')

The output is an array of System.Data.DataRow which I need to convert to a string array. I am currently trying out the following which is not working as intended

输出是一个 System.Data.DataRow 数组,我需要将其转换为字符串数组。我目前正在尝试以下无法按预期工作的方法

$formatOut = @()

for ($i=0; $i -le $output.Length; $i++)
{
    $formatOut = $formatOut + [string]$output[$i]
}

Here is the output of $formatOut is after the for loop and this is not what I was looking for

这是 $formatOut 的输出在 for 循环之后,这不是我想要的

$formatOut[0] = System.Data.DataRow
$formatOut[1] = System.Data.DataRow
$formatOut[2] = System.Data.DataRow

Could you please let me know what I need to do so that I create a string array of the contents of the $output object

您能否让我知道我需要做什么,以便我创建 $output 对象内容的字符串数组

回答by Neolisk

What you are seeing is completely normal, because by default ToStringwill output object type. This is per .NET specifications.

您所看到的完全正常,因为默认情况下ToString会输出对象类型。这是根据 .NET 规范。

You can convert a DataRowto array of object using ItemArray, and then join via "," or whichever join method you prefer, like this:

您可以使用 将 a 转换DataRow为对象数组ItemArray,然后通过“,”或您喜欢的任何连接方法进行连接,如下所示:

$formatOut = $formatOut + ($output[$i].ItemArray -join ",")