Powershell中的HashSet:Collection是固定大小的

时间:2015-03-19 15:10:38

标签: c# powershell

我有 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()
    }
}

然后,在另一个脚本中:

$AllIdPIdentifiers = New-Object 'System.Collections.Generic.HashSet[string]'
$AllIdPIdentifiers = GetAllIdentityProvidersFromDatabase $SQLConnectionString
$AllIdPIdentifiers.Remove("GodspeedYou")
Write-Host $AllIdPIdentifiers.Count

通过执行它,我有这个错误:

Exception calling "Remove" with "1" argument(s): "Collection was of a fixed size."
At C:\PowerShell\EduGain\FederationMetadataExtractor.ps1:151 char:1
+ $AllIdPIdentifiers.Remove("GodspeedYou")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException

有没有办法允许Remove操作?

1 个答案:

答案 0 :(得分:5)

当您按管道传递集合时,会枚举它并传递每个单独的元素。如果要将集合作为单个元素传递,则应将集合打包到另一个集合。一元,创建具有单个元素的数组。

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()
    }
}