ValidateNotNullOrEmpty

[ValidateNotNullOrEmpty()] is a PowerShell parameter-validation attribute.

It rejects values that are:

  • $null
  • An empty string: ""
  • An empty collection

Example:

function Show-ComputerName {
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$ComputerName
    )

    Write-Output "Computer name: $ComputerName"
}

Valid call:

Show-ComputerName -ComputerName "PC01"

Output:

Computer name: PC01

Invalid empty value:

Show-ComputerName -ComputerName ""

Invalid null value:

$name = $null
Show-ComputerName -ComputerName $name

Why combine it with Mandatory?

[Parameter(Mandatory)]

requires the parameter to be supplied.

[ValidateNotNullOrEmpty()]

requires the supplied value to contain something.

They are commonly used together:

param(
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$Path
)

Array example

function Test-Servers {
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]]$ComputerName
    )

    foreach ($computer in $ComputerName) {
        Write-Output "Testing $computer"
    }
}

Call:

Test-Servers -ComputerName "PC01", "PC02"

Important limitation

A string containing only spaces is not technically empty:

Show-ComputerName -ComputerName "   "

To reject whitespace too, use:

[ValidateScript({
    -not [string]::IsNullOrWhiteSpace($_)
})]
[string]$ComputerName

A simple definition:

[ValidateNotNullOrEmpty()] ensures that a parameter value is not null, blank, or an empty collection.

Leave a Reply