Passing true dotnet nulls for strings to APIs from powershell
May 7th, 2010 by KarlThere is an issue that can basically prevent you from calling certain dotnet apis.
Basically the trick is just to make a class that’s .tostring() returns a null, and then when you pass that to an api through powershell that takes a string powershell will convert the class to a string() thus calling your code that returns a null..
namespace testnullD
{
public class nulltest
{
public nulltest(){}
public override string ToString() {return null;}
}
}
Here is a complete example you can use.
$a = @"
using System;
namespace ClassLibrary1
{
#proof of concept
public static class Class1
{
public static string Foo(string value)
{
if (value == null)
return "Special processing of null.";
else
return "'" + value + "' has been processed.";
}
}
}
"@
$b = @"
using System;
namespace testnullD
{
public class nulltest
{
public nulltest(){}
public override string ToString() {return null;}
}
}
"@
add-type $a
add-type $b
$psnull = new-object testnullD.nulltest
add-type $a
[ClassLibrary1.Class1]::Foo($null)
[ClassLibrary1.Class1]::Foo($psnull)
Posted in Gotchas Etc, Powershell | 2 Comments »

July 1st, 2010 at 1:11 am
Awesome! Prime example of ingenuity beating a design flow!
March 5th, 2013 at 9:27 pm
No need to do all that, just use [NullString]::Value nad powershell will pass an actual null value in the .NET API call.