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.

spacebread
  • 503
  • 7
  • 19
  • 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. – Matt Mar 21 '17 at 18:58
  • `function n{param([AllowNull()][System.Nullable[int32]] $number=$null)$number -eq $null}` – Matt Mar 21 '17 at 19:05
  • `[CmdletBinding()] param([String]$Name, [Nullable[Int]]$Number) Update-Name @PSBoundParameters` – user4003407 Mar 21 '17 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. – spacebread Mar 21 '17 at 19:21
  • I misunderstood the question anyway. `[string]::isnullorempty($var)` might help though. – Matt Mar 21 '17 at 19:22

1 Answers1

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.

Community
  • 1
  • 1
spacebread
  • 503
  • 7
  • 19