Skip to content

Instantly share code, notes, and snippets.

@adamdriscoll
Created March 23, 2017 15:13
Show Gist options
  • Save adamdriscoll/b03fcfca789eea8199a57c8c57335f6d to your computer and use it in GitHub Desktop.
Save adamdriscoll/b03fcfca789eea8199a57c8c57335f6d to your computer and use it in GitHub Desktop.
How do you set a null to a string in PowerShell?
Add-Type "
public class MyClass {
public string MyString {get;set;}
public object GetNull { get { return null; } }
public void SetNull() { MyString = null; }
}"
$myObject = New-Object -TypeName MyClass
$myObject.MyString = "Hey!"
$myObject.MyString = $null
$myObject.Mystring -eq [String]::Empty
$myObject.MyString -eq $null
$myObject.MyString = $myObject.GetNull
$myObject.Mystring -eq [String]::Empty
$myObject.MyString -eq $null
$myObject.SetNull()
$myObject.Mystring -eq [String]::Empty
$myObject.MyString -eq $null
<# Results in
True
False
True
False
False
True
#>
@KirkMunro
Copy link

$myObject.MyString = [NullString]::Value
$myObject.MyString -eq $null # returns true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment