Reputation: 1059
I'm currently checking parameters passed into my script using:
$CommandName = $PSCmdlet.MyInvocation.InvocationName
$ParameterList = (Get-Command -Name $CommandName).Parameters
$Values = Get-Variable -Name $ParameterList.Values.Name -EA SilentlyContinue
This works fine. Now I want to remove specific elements, so I create a collection:
[System.Collections.ArrayList]$Array = $Values
And call the remove method:
$Array = $Array.Remove('TestParameter')
Outputting $Array
now returns nothing.
What am I missing?
Upvotes: 0
Views: 88
Reputation: 32170
$Array.Remove('TestParameter')
doesn't return the array. It just removes the first item that matches.
Try:
[System.Collections.ArrayList]$Array = $Values
$Array.Remove('TestParameter')
Example:
PS C:\> [System.Collections.ArrayList]$Array = @(1,1,2,3,5,8)
PS C:\> $Array.Remove(1)
PS C:\> $Array
1
2
3
5
8
Note that only the first matching value is removed by the Remove()
function, so be aware of how it works with duplicates.
However, as presented, your code is not going to work because Parameters is a HashTable, not an Array. HashTables sometimes aren't treated as IEnumerable, so sometimes a HashTable will not always be treated as a collection but as a single object. It's a quirk of HashTables. This means that Get-Variable
isn't seeing that it's getting a whole array of names, and instead thinks it's just getting one name that has carriage returns in it.
Try this:
$ParameterList = @((Get-Command -Name $CommandName).Parameters.Keys)
$Values = Get-Variable -Name $ParameterList -ErrorAction SilentlyContinue;
[System.Collections.ArrayList]$Array = $Values
$Array.Remove('TestParameter')
$Array
You can check the documentation, or you can view the function definitions with PowerShell directly:
PS C:\> ,$x | Get-Member | Where-Object Name -eq 'Remove'
TypeName: System.Collections.ArrayList
Name MemberType Definition
---- ---------- ----------
Remove Method void Remove(System.Object obj), void IList.Remove(System.Object value)
See how both definitions start with void
? That means the method has no return value. Note the comma in ,$x
is there to get the arraylist object itself instead of the underlying items in the arraylist.
Upvotes: 1
Reputation: 1999
Try this to get only parameters not matching 'TestParameter'
:
$Array = $Array | Where-Object { $_.Name -ne 'TestParameter' }
You cannot remove an item from a fixed width collection, you have to create a selection of the items you need and overwrite the old collection ($Array
in your example).
Upvotes: 1