我有一个 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
有没有一种方法可以允许“删除”操作?
GetAllIdentityProvidersFromDatabase
返回的不是HashSet
,而是string
。如果有多个字符串,则会打包成数组。而数组是固定大小的。 - user4003407string
对象数组,那将会很有帮助。考虑到该函数似乎计算出$AllIdPIdentifiers
的值,并引用了一个HashSet<T>
对象,我天真地认为该函数本身将返回HashSet<T>
对象。如果不能使用 OP 显示的代码,有没有一种方法使 PowerShell 函数返回实际的HashSet<T>
对象呢? - Peter DunihoContains
和Remove
操作的工作量。 - vdenotaris