Blogroll

Search

Passing true dotnet nulls for strings to APIs from powershell

May 7th, 2010 by Karl

There 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 »

2 Responses

  1. zespri Says:

    Awesome! Prime example of ingenuity beating a design flow!

  2. Bob M Says:

    No need to do all that, just use [NullString]::Value nad powershell will pass an actual null value in the .NET API call.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.