Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of variable from parameter using PowerShell

Tags:

powershell

How do I get the type of the variable from a parameter using PowerShell?

Something to the effect of if TypeOf(xyz) is String or if TypeOf(xyz) is integer.

For my purpose I want to check if it is a string or a securestring. I would like to use a single function with a parameter. Not two separate functions, one for a securestring and one for a string.

like image 663
Costa Zachariou Avatar asked Sep 23 '26 12:09

Costa Zachariou


1 Answers

The direct answer to your question is to use the -is operator:

if ($xyz -is [String]){}
if ($xyz -is [SecureString]){}

if ($xyz -isnot [int]){}

However, digging deeper:

I would like to use a single function with a parameter. Not two separate functions, one for a securestring and one for a string.

You can use a single function, with parameter sets to distinguish between which version you're using:

function Do-Thing {
[CmdletBinding()]
param(
    [Parameter(
        ParameterSetName = 'Secure',
        Mandatory = $true
    )]
    [SecureString]
    $SecureString ,

    [Parameter(
        ParameterSetName = 'Plain',
        Mandatory = $true
    )]
    [String]
    $String
)

    switch ($PSCmdlet.ParameterSetName)
    {
        'Plain' {
            # do plain string stuff
        }

        'Secure' {
            # do secure stuff
        }
    }
}

Go ahead and run that sample definition, and then look at the help:

Get-Help Do-Thing

You'll see the generated parameter sets, which show the two ways you can call it. Each way has a single, mutually-exclusive parameter.

NAME
    Do-Thing

SYNTAX
    Do-Thing -SecureString <securestring>  [<CommonParameters>]

    Do-Thing -String <string>  [<CommonParameters>]
like image 52
briantist Avatar answered Sep 27 '26 01:09

briantist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!