Home > Software design >  How to check parameter is null in where clause in powershell
How to check parameter is null in where clause in powershell

Time:08-24

I'm trying to write a PowerShell command but stucked on where clause. What i want to achieve is if parameters are not defined, where clause needs to ignore them. I tried this code but couldn't success.

I have parameters;

Param(
    [parameter(position=0)]
    [String]
        $JobName,
    [parameter(position=1)]
    [String]
        $JobID
)
 

And where clause which i tried and failed,

$Timerjob = Get-SPTimerJob | where { ($_.Id -eq $JobID) -or ($_.Title -eq $JobName) }

If $JobName or $JobID is null (or both of them), where clause should ignore them

how can i achieve this without writing multiple if clause?

CodePudding user response:

Continuing from my comment:

To retrieve all Timer Jobs if both $JobName and $JobID are empty, you will need to add that condition to the Where-Object cmdlet:

$Timerjob = Get-SPTimerJob |Where-Object {
    (!$JobName -and !$JobID) -or ($_.Id -eq $JobID) -or ($_.Title -eq $JobName)
}

This means if both $JobName and $JobID are empty, the condition (!$JobName -and !$JobID) is $True. Any condition with the -or comparison operator won't be able to change that (to $false) causing the whole condition to be true in that matter and all Timer Jobs returned.

In case you would like to make a difference between an empty string filter and a parameter that isn't supplied, you would probably want to do something like this:

$Timerjob = Get-SPTimerJob |Where-Object {
    ($PSBoundParameters.ContainsKey('JobName') -and $PSBoundParameters.ContainsKey('JobID')) -or
    ($_.Id -eq $JobID) -or ($_.Title -eq $JobName)
}

In this case you would e.g. still be able to retrieve Time Jobs with an empty title (-JobName ''), if even possible.

  • Related