如何在传递的PowerShell参数上检查null



下面是我创建这个powershell cmdlt的C#代码,它有两个参数MaxAge和ContinuationToken。我想要

  1. 如果未提供Continuation令牌,则MaxAge是强制性的
  2. ContinuationToken(如果提供(是强制性的,MaxAge是可选
  3. ContinuationToken在没有MaxAge的情况下提供时不能为null,并且应该提示用户提供该值

我能够实现前两个场景,但无法实现最后一个。下面是我的pwshell cmdlet和C#代码。请注意:

[Cmdlet(VerbsCommon.Get, "ChangedRecordings", DefaultParameterSetName = GetChangedRecordingsCmd.ParamSetCloud)]
public class GetChangedRecordingsCmd : PwshCmd
{
protected const string ParamSetCloud = "Cloud";
protected const string ParamSetFile = "File";
[Parameter(Mandatory = true,
Position = 0, ParameterSetName = ParamSetCloud,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true, HelpMessage = "Provide the maximum age of recordings from the change feed")]
[Parameter(Mandatory = false, ParameterSetName = ParamSetFile)]
public TimeSpan MaxAge { get; set; }
[Parameter(Position = 1,Mandatory = true,
ValueFromPipeline = true, ParameterSetName = ParamSetFile,
ValueFromPipelineByPropertyName = true, HelpMessage = "Provide a continuation token for the change feed")]
public string ContinuationToken { get; set; }
protected override void BeginProcessing()
{
if (ParameterSetName.Equals(ParamSetFile) && string.IsNullOrWhiteSpace(ContinuationToken))
{
WriteWarning("Continuation Token can't be null. Please pass a valid Continuation Token");
}
}
protected override void ProcessRecord()
{
//My opeartions
WriteObject(new { ContinuationToken = result, Recordings = recs });
}

对应的Powershell Cmdlet(令牌文件路径包含Continuation令牌。根据上面的场景,它可以是空的,我需要在C#中处理它(

param (
$TokenFilePath = 'C:UsersDesktopContinuationToken.txt',
$MaxAge = '2'
)
$existingToken = Get-Content -Path $TokenFilePath
$recordings = Get-ChangedRecordings -ContinuationToken $existingToken -MaxResults 10
Write-Host $recordings.Recordings.Count
$recordings.ContinuationToken|Set-Content -Path $TokenFilePath
$recs = $recordings.Recordings

为此,您可能需要使用ValidateNotNull属性:

[ValidateNotNull()]
[Parameter(Position = 1,Mandatory = true,
ValueFromPipeline = true, ParameterSetName = ParamSetFile,
ValueFromPipelineByPropertyName = true, HelpMessage = "Provide a continuation token for the change feed")]
public string ContinuationToken { get; set; }

最新更新