Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 806 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I check if a string is null or empty in PowerShell?

#11
An extension of the answer from Keith Hill (to account for whitespace):

$str = " "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }

This returns "Empty" for nulls, empty strings, and strings with whitespace, and "Not Empty" for everything else.
Reply

#12
You can use a conditional statement with both `IsNullOrWhitespace()` and `isNullOrEmpty()` static methods testing for white spaces or a null value. For example, before inserting into a `MySQL` database, I loop through the values I will enter and use the condition to avoid null or whitespace values.

```
// RowData is iterative, in this case a hashtable,
// $_.values targets the values of the hashtable

```PowerShell
$rowData | ForEach-Object {
if(-not [string]::IsNullOrEmpty($_.values) -and
-not [string]::IsNullOrWhiteSpace($_.values)) {
// Insert logic here to use non-null/whitespace values
}
}
```
Reply

#13
Another alternative adding 2 new [Script Methods](

[To see links please register here]

) to the [`System.String`](

[To see links please register here]

) instances using [`Update-TypeData`](

[To see links please register here]

):

```sh
Update-TypeData -MemberType ScriptMethod -MemberName IsNullOrEmpty -Value {
return [string]::IsNullOrEmpty($this)
} -TypeName System.String

Update-TypeData -MemberType ScriptMethod -MemberName IsNullOrWhiteSpace -Value {
return [string]::IsNullOrWhiteSpace($this)
} -TypeName System.String

'hello'.IsNullOrEmpty() # => False
''.IsNullOrEmpty() # => True
' '.IsNullOrEmpty() # => False
' '.IsNullOrWhiteSpace() # => True
```
Reply

#14
Addressing the tangential shortcoming with [@KeithHill's answer][1] not covering the *`IsNullOrWhitespace`* case, in PowerShell 7.1 and later we can use the [null-conditional member operator][2] to gracefully check if a string is null or whitespace without needing to first check that the string isn't `$null` ourselves, while avoiding the use of `[string]::IsNullOrWhitespace(string)`.

> **Note:** You can also do this with PowerShell 7.0 if you enable the `PSNullConditionalOperators` experimental feature:
>
> ```powershell
> Enable-ExperimentalFeature -Name PSNullConditionalOperators
> ```

To use the `$str3` example from Keith's answer (and pretending the ternary operator doesn't also exist since 7.0 for clarity):

```powershell
$str3 = ' '
if ( ${str3}?.Trim() ) {
'not empty or whitespace'
} else {
'empty or whitespace'
}
empty or whitespace
```

`.Trim()` is only invoked if `$str3` is a non-null value, otherwise `$null` is returned instead.

---

One thing to remember is that a question mark `?` is valid as part of a variable name. This is why we must *first* disambiguate the variable name by before applying the conditional-access operator like so: `${str3}`

---

Since I did mention the ternary operator earlier, *and* since this answer already centers around PowerShell 7.1 and later, you can simplify the code block above by using the ternary operator, removing the boilerplate `if/then/else` statement almost entirely:

```powershell
${str3}?.Trim() ? 'not empty or whitespace' : 'empty or whitespace'
```

The [ternary operator][3] is a simplified `if/then/else` statement for basic conditionals. I don't want to muddy the waters too much here with nuances around it, but read it as "if the left side of the *lone* question-mark `?` is true, execute what is on the right side of the `?`, or else execute what comes after the colon `:`".

You can read more about the ternary operator in the [PowerShell documentation][3].


[1]:

[To see links please register here]

[2]:

[To see links please register here]

-
[3]:

[To see links please register here]

Reply

#15
You could create a filter that converts empty strings to nulls, then you only would have to check for null.

filter nullif {@($_, $null)[$_ -eq '']}

Then you just need to pipe your value into it

('' | nullif) -eq $null
> True
('x' | nullif) -eq $null
> False

An even easier mrthod would be to use a regex

$null -match '^$'
> True
'' -match '^$'
> True
'x' -match '^$'
> False


Reply

#16
<!-- language-all: sh -->

Many good answers here; let me offer a **pragmatic summary** with **PowerShell-idiomatic solutions**:

Given a variable `$str` that may contain `$null` or a *string* (or any _scalar_):

```
# Test for $null or '' (empty string).
# Equivalent of: [string]::IsNullOrEmpty($str)
$str -like ''

# Test for $null or '' or all-whitespace.
# Equivalent of: [string]::IsNullOrWhitespace($str)
$str -notmatch '\S'
```

Note: If `$str` can be a _collection_ (array), use the type-agnostic solutions at the bottom.

* Using the string-only [`-like`](

[To see links please register here]

) operator implicitly coerces the LHS to a _string_, and since `[string] $null` yields the empty string, both `'' -like ''` and `$null -like ''` yield `$true`.

* Similarly, the [regex](

[To see links please register here]

[`-match` / `-notmatch`](

[To see links please register here]

) operators, as *string-only* operators, coerce their LHS operand to a string, and `$null` is treated like `''` in this conversion.

* `\S` is a regex escape sequence that matches any _non_-whitespace character (it is the negated form of `\s`).

* `-match` / `-notmatch` perform _substring_ matching by default (and only ever return _one_ match), so if `\S` matches, the implication is that at least one character that isn't a whitespace character is present.

---

**Caveat**:

Given PowerShell's dynamic typing, you may not know the type of the value stored in a given variable ahead of time.

While the techniques above work predictable with `$null`, `[string]` instances, and other types that are _non-enumerable_, **_enumerable_ values (other than strings) may yield surprising results**, because if the LHS of `-like` and `-notmatch` are enumerables (loosely speaking: collections), the operation is applied to _each element_, and instead of returning a single Boolean value, the _sub-array of matching elements_ is returned.

In the context of a conditional, the way an array is coerced to a Boolean is somewhat counterintuitive; if the array has just _one_ element, that element itself is coerced to a Boolean; with _two or more_ elements, the array is always coerced to `$true`, irrespective of the element values - see the bottom section of [this answer](

[To see links please register here]

). For instance:

```
# -> 'why?', because @('', '') -like '' yields @('', ''), which
# - due to being a 2-element array - is $true
$var = @('', '')
if ($var -like '') { 'why?' }
```

if you **cast a non-string enumerable LHS to `[string]`**, PowerShell stringifies it by space-concatenating its (stringified) elements.
This is also what happens _implicitly_ when you call `[string]::IsNullOrEmpty()` or `[string]::IsNullOrWhiteSpace()`, because their parameter is `[string]`-typed.

Thus, the **type-agnostic equivalents of the above** - using the stringification rules described - are:

```
# Test for $null or '' (empty string) or any stringified value being ''
# Equivalent of: [string]::IsNullOrEmpty($var)
[string] $var -eq ''

# Test for $null or '' or all-whitespace or any stringified value being ''
# Equivalent of: [string]::IsNullOrWhitespace($var)
([string] $var).Trim() -eq ''
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through