Ok, I tried to look around and figure out how to do this, but wasn't able to figure it out. Here's what I want to do.
# Run script normally
.\myscript.ps1 "blah" "yo"
These should do the same thing
Get-Help .\myscript.ps1
.\myscript.ps1
I want to be able to use the Get-Help syntax, but don't want to have to repeat it somewhere with a parameter switch statement. If this has been answered somewhere else, feel free to point me there.
You can add the following code to the top of your script:
if($args.Count -eq 0) {
Get-Help $MyInvocation.MyCommand.Definition
return
}
$PSBoundParameters.Values.Count will give you the count of parameters passed when you use param() in your script. You can then use $args to find anything else entered that is outside these parameters. So if you test for both when using param you can get help response.
Example parametertest.ps1
param([string]$val1,$val2,[switch]$val3)
if ( $PSBoundParameters.Values.Count -eq 0 -and $args.count -eq 0 ) {
Get-Help $MyInvocation.MyCommand.Definition
return
}
if ( $PSBoundParameters.Values.Count -eq 0 ){
Write-Output ("No parameters passed")
return
}
else { write-output("val1=$val1 val2=$val2 val3=$val3") }
if ( $args -and $args.count -gt 0 ) {
Write-Output ("Found Args $args") }
if ( $PSBoundParameters.Values.Count -eq 0 -and $args -and $args.count -eq 0
Example output
powershell -File parametertest.ps1
parametertest.ps1 [[-val1] < string>] [[-val2] < Object>] [-val3]
powershell -File parametertest.ps1 sometest 123
val1=sometest val2=123 val3=False
powershell -File parametertest.ps1 -val1 stuff -val2 123 -val3
val1=stuff val2=123 val3=True
powershell -File parametertest.ps1 -unknown parameter
No parameters passed
Found Args -unknown parameter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With