3

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.

1 Answer 1

8

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>]
Sign up to request clarification or add additional context in comments.

3 Comments

Hi @briantist. If I use: if ($xyz -is [String]){} if ($xyz -is [bool]){} if ($xyz -is [int]){} It works. If I use: if ($xyz -is [SecureString]){} It will not work. It gets pickedup as a PSOBject or PSCustomObject. How do I get around that?
@CostaZachariou well I don't know because I can't see the part of your code that assigns $xyz. What is the output of $xyz.GetType().FullName?
Thank you for your help earlier. I think it was because it was returning a null and was changing to the default object of PSCustomObject. That seems to be working now. Creating another question for returning SecureString.

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.