将空值传递给cmdlet参数

Cur*_*One 1 powershell cmdlets null parameter-passing

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

Get-EventLog -LogName Application -Source sourcename -Newest uservalue `
      -After $null -Before $null
Run Code Online (Sandbox Code Playgroud)

问题是cmdlet无法识别和参数$null的可接受输入.如何在不抛出错误的情况下将空值传递给cmdlet的参数?-After-Before

bri*_*ist 5

使用Splatting.

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

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

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

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

Get-EventLog @params
Run Code Online (Sandbox Code Playgroud)