1

I am writing cmdlets in C# and I have nullable ints (int?) which I took care of with [System.Nullable[System.Int32]] in my powershell script.

Now, however, I have some parameters that are not required that are strings and I need them to pass null if they are not supplied when calling the script and not an empty string. Is there something similar to [System.Nullable[System.Int32]] I can use?

(C#)

[Cmdlet("Update","Name")]
public class UpdateName : Cmdlet
{
    public UpdateName()
    {
    }
    [Parameter(HelpMessage = "The Name")]
    public string Name { get; set; }

    [Parameter(HelpMessage = "The Number")]
    public int? Number { get; set; }

    proctected override void ProcessRecord()
    {
        // do stuff here
    }
}

(Powershell)

[CmdletBinding()]
param
( [string]$Name,
[System.Nullable[System.Int32]]$Number
)

Update-Name -Name $Name -Number $Number

And then I am calling my script testscript.ps1 and running it with no parameters passed from my powershell prompt.

5
  • Why are you looking to allow null exactly? What does that give you? There might be other option better geared to the strengths of PowerShell here you could be doing. Commented Mar 21, 2017 at 18:58
  • function n{param([AllowNull()][System.Nullable[int32]] $number=$null)$number -eq $null} Commented Mar 21, 2017 at 19:05
  • [CmdletBinding()] param([String]$Name, [Nullable[Int]]$Number) Update-Name @PSBoundParameters Commented Mar 21, 2017 at 19:16
  • @Matt, its possible I really don't need a null, I think I will be fine doing a minor tweak and checking for empty strings. It just feels a bit like a sin, since I'm normally in C# and an empty string has always been something different to me than null. Commented Mar 21, 2017 at 19:21
  • I misunderstood the question anyway. [string]::isnullorempty($var) might help though. Commented Mar 21, 2017 at 19:22

1 Answer 1

0

I'll go ahead and post what I found. I was hoping there was just a quick answer, but my googling skills have not yet found one.

Looks like this is just the way powershell works with strings.

Why does passing $null to a parameter with AllowNull() result in an error?

So I am making changes to my Cmdlet to watch for empty strings as well as nulls.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.