Possible to pass null from Powershell to a .Net AP

2020-02-10 03:59发布

API:

namespace ClassLibrary1
{
    public class Class1
    {
        public static string Test(string input)
        {
            if (input == null)
                return "It's null";
            if (input == string.Empty)
                return "It's empty";
            else
                return "Non-empty string of length " + input.Length;
        }
    }
}

Script:

add-type -path C:\temp\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll
[classlibrary1.class1]::Test($null)
[classlibrary1.class1]::Test([object]$null)
[classlibrary1.class1]::Test([psobject]$null)
[classlibrary1.class1]::Test($dummyVar)
[classlibrary1.class1]::Test($profile.dummyProperty)

Output:

It's empty
It's empty
It's empty
It's empty
It's empty

What am I missing?

3条回答
\"骚年 ilove
2楼-- · 2020-02-10 04:09

In order to pass a null value to an API call, use [NullString]::Value.

查看更多
欢心
3楼-- · 2020-02-10 04:18

According to this MS connect issue, this is a known problem. There are a couple workarounds posted there, too, like using reflection to pass the paramaters (which is clever, but kinda silly that it's required). Cheers!

查看更多
成全新的幸福
4楼-- · 2020-02-10 04:31

this is just how PowerShell behaves - it will always try to convert an object as long as it is convertible to the target type (in this case string). PowerShell will always convert null (the absence of a value) to String.Empty when casting into a string object.

Take a look at Bruce Payette's book "Windows PowerShell in Action", around page 142. Bruce is one of the architects behind PowerShell.

It's kinda one of those documented little gotchas of the scripting language, and we should definitely be aware of it.

查看更多
登录 后发表回答