【问题标题】:Providing example in named PowerShell parameter在命名的 PowerShell 参数中提供示例
【发布时间】:2021-03-25 15:38:57
【问题描述】:

使用如下代码:

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

我希望最终用户知道如何获取所有必需的命名参数,例如在执行这个脚本时,我预计会发生这样的事情

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

等等

我知道有一个 HelpMessage 参数,例如

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

但我希望在最终用户指定值时显示此消息。

【问题讨论】:

标签: powershell named-parameters


【解决方案1】:

你能澄清一下你在追求什么吗? “但我希望在最终用户指定值时显示此消息。”您希望它在运行时显示为问题/答案吗?如果是这样,您不想将其设置为强制参数,您需要 Read-Host 变量。

例如:

      $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
      }

然后您将对所有变量执行此操作,并在提供它们后采取措施。

编辑: 使用 zjg.robin 指定的答案,在运行强制参数时,用户可以输入!?获取强制参数的帮助信息。如果您希望它们被提示,那么您将需要使用与带有所需参数的 cmdlet 相对的问题/答案方法。或者,您可以为它提供两个世界,并使其成为函数内的真正 cmdlet。然后,当您调用脚本时,如果未指定参数,则提示它们输入这些参数并将其传递给函数。真的取决于你的具体要求是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-14
    • 2017-01-10
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2016-01-31
    相关资源
    最近更新 更多