Casting ScriptBlock as Action[T] for Generic.List[T] ForEach method
I am having problems using the ForEach() method on Generic.List[T] in PowerShell. I have tested some of the other methods with these anonymous delegates (C# lambda expressions) on the Generic.List[T] and they work. Following is my code assuming the list[T] has values:
$list = New-Object System.Collections.Generic.List[uint32]
$rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$sysArray1 = @()
for ( $i = 0; $i -lt 10; $i++ )
{
$byte = New-Object byte[] 4
$rng.GetBytes($byte)
$list.Add( [bitconverter]::ToUInt32( $byte,0 ) )
$sysArray1 += [bitconverter]::ToUInt32( $byte,0 )
}
With the $sysArray1
I am able to use the ForEach() method; however, with $list
I am not.
PS C:Windowssystem32> $sysArray1.ForEach({($_.ToString() + " Hello, World!")})
230848998 Hello, World!
1472227127 Hello, World!
2436917759 Hello, World!
797599365 Hello, World!
3872804216 Hello, World!
453721367 Hello, World!
46463291 Hello, World!
2921221794 Hello, World!
627551225 Hello, World!
1839786036 Hello, World!
PS C:Windowssystem32> $list.ForEach({$_.ToString() + " Hello, World!"})
You cannot call a method on a null-valued expression.
At line:1 char:16
+ $list.ForEach({$_.ToString() + " Hello, World!"})
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The above error occurs as many times as the size of the List[T]. Also I cannot cast the ScriptBlocks in either approach as [Action[T]]
.
Any help would be greatly appreciated.
链接地址: http://www.djcxy.com/p/30384.html