Advertisement
Guest User

PowerShell Function IsNullOrEmpty

a guest
Apr 2nd, 2015
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function IsNullOrEmpty {
  2. <#
  3. .SYNOPSIS
  4.     Determine if an object is $null or empty.
  5. .DESCRIPTION
  6.     Determine if an object is $null or empty.
  7. .INPUT
  8.     Accepts pipeline input of any object type.
  9. .OUTPUTS
  10.     system.boolean
  11. .PARAMETER InputObject
  12.     Input object to examine for $null or empty value.
  13. .EXAMPLE
  14.     IsNullOrEmpty($null)
  15. .EXAMPLE
  16.     An example showing use with the pipeline:
  17.     @(1,'',2,'String',$null,@(),@(3,4,5)) | Where-Object { -not (IsNullOrEmpty($_)) } | Write-Host
  18.     Only writes array elements to the console if they are not $null or empty.
  19. .NOTES
  20.     Please note that strongly typed variables cannot be set to $null in PowerShell.
  21.    
  22.     If you set  [int32]$a  = $null    ==> PowerShell will set $a = 0
  23.     If you set  [switch]$b = $null    ==> PowerShell will set $b = $false
  24.     If you set  [string]$c = $null    ==> PowerShell will set $c = ''
  25.    
  26.     After people complained about not being able to set variables of [string] type to $null,
  27.      PowerShell 3 gained the ability to set a [string] type to $null like this:
  28.      [string]$d = [System.Management.Automation.Language.NullString]::Value
  29. .LINK
  30. #>
  31.     [CmdletBinding()]
  32.     Param (
  33.         [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
  34.         [AllowNull()]
  35.         [AllowEmptyString()]
  36.         [AllowEmptyCollection()]
  37.         $InputObject
  38.     )
  39.     Process {
  40.         ## Switching the comparison order of this 'If' statement can give inaccurate
  41.         ## results when arrays are involved, so don't touch.
  42.         If ($null -eq $InputObject) {
  43.             Write-Output $true
  44.         }
  45.         ElseIf (($InputObject -is [array]) -and (-not $InputObject.Count)) {
  46.             Write-Output $true
  47.         }
  48.         ElseIf (($InputObject -is [string]) -and (-not $InputObject)) {
  49.             Write-Output $true
  50.         }
  51.         ## To handle null values from SQL databases.
  52.         ElseIf ($InputObject -is [DBNull]) {
  53.             Write-Output $true
  54.         }
  55.         Else {
  56.             Write-Output $false
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement