Say I have a Powershell script TestParameters.ps1 like this, with two mandatory, named parameters and two optional parameters:
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True)]
[string] $AFile = "C:\A\Path",
[Parameter(Mandatory=$True)]
[ValidateSet("A","B","C", "D")]
[string] $ALetter = "A",
[Parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]
[string] $Optional1 = "Foo",
[Parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]
[string] $Optional2 = "Bar"
)
echo "Hello World!"
$psboundparameters.keys | ForEach {
Write-Output "($_)=($($PSBoundParameters.$_))"
}
Say I call the script like this:
.\TestParameters.ps1 `
-AFile "C:\Another\Path" `
-ALetter "B"
which produces output:
Hello World!
(AFile)=(C:\Another\Path)
(ALetter)=(B)
Powershell set the variables $Optional1 and $Optional2 ... but how do I easily display them to the screen, like the way I use $PSBoundParameters?
I do not want to simply write the following every time I have a script:
Write-Host $AFile
Write-Host $ALetter
Write-Host $Optional1
Write-Host $Optional2
Notes:
- $args only seems to include unbound parameters, not default parameters
$MyInvocation seems to only include commands passed on the command lineEDIT: MyInvocation has member variable MyCommand.Parameters, which seems to have all the parameters, not just those passed on the command line...see the accepted answer, below.- Get-Variable seems to include the optional variables in the result list, but I do not know how to differentiate them from the other variables