In Powershell, How to print only the command synax when no parameters are provided? Example:
PS> .\sign.ps1
sign.ps1 [-Trace] [-New] [-All] [[-File] <string[]>] [<CommonParameters>]
Instead I get the complete Help page for the command... Here's what I'm doing.
# sign.ps1
<#
.SYNOPSIS
Script for Signing Powershell Scripts
.PARAMETER New
Create a new code signing certificate for signing powershell scripts.
(requires Powershell to be run in admin mode in order to make the certificate)
.PARAMETER File
List of Powershell scripts to sign
.PARAMETER All
Sign all ps1 files in the current directory
.EXAMPLE
# Creates a new certificate stored in current direcctory as sign.pfx
PS> sign -New
# Sign all ps1 files in current directory
PS> sign -File *.ps1
#>
param(
[switch]$Trace,
[switch]$New,
[switch]$All,
[string[]]$File
)
if ($PSBoundParameters.Count -eq 0) {
Get-Help $MyInvocation.MyCommand.Path
exit 1
}
CodePudding user response:
To offer an alternative to Jeff Zeitlin's effective solution:
Get-Command
-Syntax
is designed to report a command's syntax diagram, and it derives it directly from the target command's definition, not from its help. Therefore, it works whether or not the target command has (comment-based) help defined for it.
It is also useful in interactive use (e.g., Get-Command -Syntax Get-ChildItem
, or, using aliases and elastic syntax, gcm -sy gci
).
if ($PSBoundParameters.Count -eq 0) {
Get-Command -Syntax $PSCommandPath
exit 1
}
Note the use of the automatic $PSCommandPath
variable as a simpler way to refer to the running script's full path.
You can apply the technique to a function too:
if ($PSBoundParameters.Count -eq 0) {
$MyInvocation.MyCommand | Get-Command -Syntax
return
}
However, this isn't fully robust, because - unfortunately - $MyInvocation.MyCommand
, which is an unambiguous System.Management.Automation.FunctionInfo
instance, is stringified in the process, which means that Get-Command
sees the only the function name, and not also its module context, so at least hypothetically Get-Command
could act on a different function with the same name, from a different module / from the non-module scope domain.
This problematic Get-Command
behavior - the inability to recognize System.Management.Automation.CommandInfo
instances (as well as of derived classes such as FunctionInfo
) as such in its pipeline input - is the subject of GitHub issue #11017.
If this were to get fixed, $MyInvocation.MyCommand | Get-Command -Syntax
would work robustly in both scripts and functions.
CodePudding user response:
The output of the Get-Help
command is an object which has several member properties. One of those properties is "syntax". Thus...
if ($PSBoundParameters.Count -eq 0) {
(Get-Help $MyInvocation.MyCommand.Path).syntax
exit 1
}
...should do the trick.
(a little experimentation shows that this probably won't work for "built-in" commands, only for script cmdlets/advanced functions)