Search code examples
powershellnamed-parameters

Providing example in named PowerShell parameter


With the code like this:

param
(   
    [Parameter(Mandatory = $true)] 
    [string]$TenantId,

    [Parameter(Mandatory = $true)] 
    [System.Uri]$HostUrl,
         
    [Parameter(Mandatory = $true)] 
    [string]$SiteId,
         
    [Parameter(Mandatory = $true)] 
    [guid]$WebId,
         
    [Parameter(Mandatory = $true)] 
    [guid]$ListId,
         
    [Parameter(Mandatory = $true)] 
    [guid]$UniqueId,    
         
    [Parameter(Mandatory = $true)] 
    [string]$OutFile
)

Connect-MgGraph -Scopes "Sites.FullControl.All" -TenantId $TenantId -ForceRefresh

Get-MgSiteListItemDriveItemContent -ListId $ListId -ListItemId $UniqueId -SiteId "$($HostUrl.DnsSafeHost),$SiteId,$WebId" -OutFile $OutFile

Disconnect-MgGraph

I would like the end user to know how to fetch all required named parameters, e.g. upon executing this script I anticipate something like this

cmdlet  at command pipeline position 1
Supply values for the following parameters:
TenantId (to get TenantID go to Admin Center - Settings and copy TenantID): xxx
HostUrl (to get HostUrl copy HostUrl from the log files): yyy-yyy 
SiteId (SiteId can be obtained directly in SharePoint site): zzz-zzz-zzz

etc.

I know there is a HelpMessage parameter e.g.

[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage="Site name")]

yet I want this message to be displayed when the end-user specifies the value.


Solution

  • Can you clarify what you're after? "yet I want this message to be displayed when the end-user specifies the value." Do you want it displayed as a Question/Answer while running? If so you don't want to set it as a mandatory parameter, you want to Read-Host the variables.

    For Example:

          $TenantId = Read-Host "TenantId (to get TenantID go to Admin Center - Settings and Copy TenantID)"
          
          if ($null -eq $TenantId) {
                Write-Output "Invalid TenantId supplied, unable to continue."
                return
          }
    

    And then you would do that for all of your variables and take actions once they are supplied.

    Edit: Using the answer that zjg.robin specified, while running the mandatory parameter, a user can type in !? to get the help message for the mandatory parameters. If you would rather them be prompted, then you will want to use the Question/Answer methodology as apposed to the cmdlet with required parameters. Or, you can provide both worlds to it, and make it a true cmdlet inside a function. Then when you call the script, if no parameters are specified, you prompt them for those and pass it to the function. Really depends on what you're specific requirements are.