【问题标题】:Pass empty value to cmdlet parameter将空值传递给 cmdlet 参数
【发布时间】:2018-05-15 19:09:22
【问题描述】:

我正在编写 Get-EventLog cmdlet 的图形实例,以便我可以锁定用户可以输入的参数和值。在下图中,紫色框(左列)将由我设置,但棕褐色框(右列)可以接受用户输入的任何值。 在此后端,我正在编写一个函数,该函数将采用用户输入的任何值并使用这些值调用 Get-EventLog cmdlet。例如,如果用户只为最新的参数输入一个值,那么这将是它会生成的代码:

Get-EventLog -LogName Application -Source sourcename -Newest uservalue `
      -After $null -Before $null

问题在于 cmdlet 无法将 $null 识别为 -After-Before 参数的可接受输入。如何将空值传递给 cmdlet 的参数而不引发错误?

【问题讨论】:

  • -Before-After 需要 DateTime 值,因此您不能指定 $null。但是,您可以省略该参数或改用[DateTime]::MinValue[DateTime]::MaxValue
  • 是的,这适用于-After-Before,但如果用户没有输入-Newest 的值,我仍然会遇到问题,这需要一个诠释。不过,飞溅似乎可以解决这个问题。 :)

标签: powershell null parameter-passing cmdlets


【解决方案1】:

Use Splatting.

$params = @{
    LogName = 'Logname'
    Source = 'Source'
}

if ($AfterValue) {
    $params.After = $AfterValue
}

if ($BeforeValue) {
    $params.Before = $BeforeValue
}

if ($NewestValue) {
    $params.Newest = $NewestValue
}

Get-EventLog @params

【讨论】:

  • 这正是我想要的。谢谢!
猜你喜欢
  • 2014-11-09
  • 2015-05-24
  • 1970-01-01
  • 2016-09-26
  • 2015-03-09
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多