Skip to content

Instantly share code, notes, and snippets.

@anderssonjohan
Last active December 12, 2015 07:48
Show Gist options
  • Save anderssonjohan/4738733 to your computer and use it in GitHub Desktop.
Save anderssonjohan/4738733 to your computer and use it in GitHub Desktop.
Upgraded to PowerShell 3.0 and found a piece in one of our scripts that wasn't compatible. Here is a sample with the corrected code which works in both 2.0 and 3.0. Conclusion: Do not use $MyInvocation.BoundParameters. However, $PSBoundParameters will work on both v2 and v3.
param(
[string] $foo,
[int] $bar
)
$arguments = ""
# Change to $PSBoundParameters..
$MyInvocation.BoundParameters.Keys | %{
Write-Host "key $_"
# $MyInvocation.BoundParameters.Item( string key ) fails in PowerShell 3.0:
# $paramValue = $MyInvocation.BoundParameters.Item( $_ )
#
# Exception getting "Item": "The given key was not present in the dictionary."
# At C:\temp\testargs.ps1:8 char:2
# + $paramValue = $MyInvocation.BoundParameters.Item( $_ )
# + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# + CategoryInfo : NotSpecified: (:) [], GetValueInvocationException
# + FullyQualifiedErrorId : ExceptionWhenGetting
# This works in both PowerShell 2.0 and 3.0
# Conclusion: Do not use $MyInvocation.BoundParameters - it will have the keys but not the values?
# $PSBoundParameters has both keys and values on v2 and v3.
$paramValue = $PSBoundParameters.Item( $_ )
if( $paramValue -match "\s" ) {
$paramValue = """$paramValue"""
}
$arguments += " -$_ $paramValue"
}
Write-Host $arguments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment