Here is our test script t.ps1
param( $Name="foo", $LastName="bar" ) "Name: $Name LastName: $LastName" "PSBoundParameters : " $PSBoundParameters "Removing 'Name'" $PSBoundParameters.Remove('Name') "After Removing 'Name'" "Name: $Name LastName: $LastName" "PSBoundParameters : " $PSBoundParameters "Removing 'LastName'" $PSBoundParameters.Remove('LastName') "After Removing 'LastName'" "Name: $Name LastName: $LastName" "PSBoundParameters : " $PSBoundParameters
## Let's start testing
D:\> C:\temp\t.ps1 Name: foo LastName: bar PSBoundParameters : ## <--- It's empty Removing 'Name' False ## There was no 'Name' parameter to remove After Removing 'Name' Name: foo LastName: bar PSBoundParameters : Removing 'LastName' False After Removing 'LastName' Name: foo LastName: bar PSBoundParameters : D:\>
So, what happened? Well, $PSBoundParameters did not have anything, because nothing was passed to the script.
Now let's try passing it parameters
D:\> C:\temp\t.ps1 -name Adil -LastName Hindistan Name: Adil LastName: Hindistan PSBoundParameters : ## This returns 2 key/value pairs Key Value --- ----- Name Adil LastName Hindistan Removing 'Name' ## <-- returns True, b/c it could remove the binding True After Removing 'Name' Name: Adil LastName: Hindistan PSBoundParameters : LastName Hindistan ## <- now, $PSBoundParameters only has one key/value Removing 'LastName' True After Removing 'LastName' Name: Adil LastName: Hindistan PSBoundParameters :
Note that $Name and $LastName got their values assigned and are not affected from $PSBoundParameters.Remove() operation at all. All we are doing is removing keys from a dictionary.
We can also add key/value pairs to it using this:
$PSBoundParameters.Add('Key','Value') E.g. $LastName='Doe' $PSBoundParameters.Add('NewLastName',$LastName)$PSBoundParameters are quite useful to determine whether a parameter is using its default value or was it passed a value. It is also useful for splatting:
Some-CommandLet @PSBoundParametersThis supplies the key value pairs a CMDLET or function would require
No comments:
Post a Comment