Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function IsNullOrEmpty {
- <#
- .SYNOPSIS
- Determine if an object is $null or empty.
- .DESCRIPTION
- Determine if an object is $null or empty.
- .INPUT
- Accepts pipeline input of any object type.
- .OUTPUTS
- system.boolean
- .PARAMETER InputObject
- Input object to examine for $null or empty value.
- .EXAMPLE
- IsNullOrEmpty($null)
- .EXAMPLE
- An example showing use with the pipeline:
- @(1,'',2,'String',$null,@(),@(3,4,5)) | Where-Object { -not (IsNullOrEmpty($_)) } | Write-Host
- Only writes array elements to the console if they are not $null or empty.
- .NOTES
- Please note that strongly typed variables cannot be set to $null in PowerShell.
- If you set [int32]$a = $null ==> PowerShell will set $a = 0
- If you set [switch]$b = $null ==> PowerShell will set $b = $false
- If you set [string]$c = $null ==> PowerShell will set $c = ''
- After people complained about not being able to set variables of [string] type to $null,
- PowerShell 3 gained the ability to set a [string] type to $null like this:
- [string]$d = [System.Management.Automation.Language.NullString]::Value
- .LINK
- #>
- [CmdletBinding()]
- Param (
- [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
- [AllowNull()]
- [AllowEmptyString()]
- [AllowEmptyCollection()]
- $InputObject
- )
- Process {
- ## Switching the comparison order of this 'If' statement can give inaccurate
- ## results when arrays are involved, so don't touch.
- If ($null -eq $InputObject) {
- Write-Output $true
- }
- ElseIf (($InputObject -is [array]) -and (-not $InputObject.Count)) {
- Write-Output $true
- }
- ElseIf (($InputObject -is [string]) -and (-not $InputObject)) {
- Write-Output $true
- }
- ## To handle null values from SQL databases.
- ElseIf ($InputObject -is [DBNull]) {
- Write-Output $true
- }
- Else {
- Write-Output $false
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement