繁体   English   中英

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

[英]How to check null on passed PowerShell argument

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

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

我能够实现我的第一个两个场景,但无法实现最后一个。 下面是我的 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 Cmndlet(令牌文件路径包含继续令牌。根据上述场景可以为空,我需要在 C# 中处理)

param (
  $TokenFilePath = 'C:\Users\Desktop\ContinuationToken.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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM