Last active
December 12, 2015 07:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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