我有一个PowerShell功能如下:
Function GetAllIdentityProvidersFromDatabase {
param (
[string] $SQLConnectionSting
)
$AllIdPIdentifiers = New-Object 'System.Collections.Generic.HashSet[string]'
$SQLConnect = new-object system.data.sqlclient.sqlconnection $SQLConnectionSting
try {
$SQLQuery = $("SELECT [IdPIdentifier] FROM [dbo].[IdPs]")
$SQLConnect.Open()
$command = New-object system.data.sqlclient.SqlCommand
$command.connection = $SQLConnect
$command.CommandText = $SQLQuery
$Reader = $command.ExecuteReader()
while ($Reader.Read()) {
$value = $Reader.GetValue($1)
$AllIdPIdentifiers.Add($value) | Out-Null
}
$AllIdPIdentifiers
} catch {
Write-Host "SQL Select error: " $Error[0].ToString() -ForegroundColor Red
} finally {
$SQLConnect.Close()
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在另一个脚本中:
$AllIdPIdentifiers = New-Object 'System.Collections.Generic.HashSet[string]'
$AllIdPIdentifiers = GetAllIdentityProvidersFromDatabase $SQLConnectionString
$AllIdPIdentifiers.Remove("GodspeedYou") …Run Code Online (Sandbox Code Playgroud) 我一直在尝试编写一个返回初始化[System.Data.DataTable]对象数据类型的实用程序函数.
我知道恼人的PowerShell函数返回行为,它试图将所有内容"展开"为[System.Array]返回类型.以前我一直设法解决这个问题.通常使用"逗号技巧"来返回你自己的阵列@(,$result)工作 - 但这次这似乎没有什么区别,我已经用完了选项......
我通常使用的另一个技巧是$nullProcess块中的赋值(请参阅下面的代码) - 这样我愚弄了管道,没有什么可以在输出上"展开"...
我不是不可能得到答案,到目前为止根据我的经验在PowerShell中没有什么是不可能的:)
这是我的代码:
function Get-SourceDataTable
{
[OutputType([System.Data.DataTable])]
[cmdletbinding()]
param(
[parameter(Mandatory=$true, Position=0)]
[System.Data.SqlClient.SqlBulkCopy] $Destination,
[parameter(Mandatory=$true, Position=1)]
[System.Collections.Specialized.OrderedDictionary] $ColumnDefinition,
[parameter(Mandatory=$false, Position=2)]
[int]$ColumnStartIndex = 0
)
BEGIN{
$datatable = New-Object System.Data.DataTable
$colIndex = $ColumnStartIndex
}
PROCESS{
$ColumnDefinition.Keys |
foreach {
$null = $datatable.Columns.Add($_, $ColumnDefinition[$_]) # define each column name and data type
$null = $Destination.ColumnMappings.Add($_, $colIndex) # map column to destination table
$colIndex++
}
}
END{
return …Run Code Online (Sandbox Code Playgroud)