Checking if a variable has been submitted to a function

$PSBoundParameters.ContainsKey('Username')

The line above will return true if the ‘Username’ has been provided to the function

https://stackoverflow.com/questions/48643250/how-to-check-if-a-powershell-optional-argument-was-set-by-caller

Function get-TPNUserState() {
    <#
    .Description
    Supplies some sommonly needed values for a user:
    PasswordLastSet, DisplayName, Description, LastLogonDate, Manager, DistinguishedName, whencreated

    .Example
    get-TPNUserState tp-nickel

    .Parameter Username
    The username that you want to look into. If you don't enter one then it will prompt you.

    #>

    [Cmdletbinding()]
    param(
        [Parameter(Position=0)]
        [string]$Username
        )
    process{
         
        if(!$PSBoundParameters.ContainsKey('Username')){ $Username = read-host -Prompt UserName } #if Username is not set then prompt for it.
        Get-ADuser $Username -properties PasswordLastSet, DisplayName, Description, LastLogonDate, Manager, DistinguishedName, whencreated | select SAMAccountName, DisplayName, Description, Enabled, PasswordLastSet, LastLogonDate, whencreated, Manager, DistinguishedName | fl
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

2 × 2 =