Best way to implement PSCredential in CmdLet

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Stig Sörnsen Stig Sörnsen 9 months, 1 week ago.

  • Author
    Posts
  • #36036
    Profile photo of Stig Sörnsen
    Stig Sörnsen
    Participant

    Hi,

    I am creating a Powershell module with many CmdLet functions that is going to interact with a Web API. By default, if no PSCredential is added it should just use the -UseDefaultCredentials parameter in the Invoke-RestMethod.

    Is this really the best way to implement it?


    function Test-Function ()
    {
    [cmdletbinding()]
    Param (
    [Parameter()]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential
    )

    $url = "secret :)"

    if ($Credential)
    {
    (Invoke-RestMethod $url -Method Get -ContentType "application/json" -Credential $Credential)
    }
    else
    {
    (Invoke-RestMethod $url -Method Get -ContentType "application/json" -UseDefaultCredentials)
    }
    }

    Just wondering if I could trim it some more? Eg. not having two Invoke-RestMethod's

    Best regards

  • #36037
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    I like to use splatting for this sort of thing:

    if ($Credential)
    {
        $splat = @{ Credential = $Credential }    
    }
    else
    {
        $splat = @{ UseDefaultCredentials = $true }
    }
    
    Invoke-RestMethod $url -Method Get -ContentType "application/json" @splat
    

    You still have the same "if" statement, but only one call to the actual cmdlet (so if you want to change one of the other parameters, you only have to do it in one place.)

  • #36059
    Profile photo of Stig Sörnsen
    Stig Sörnsen
    Participant

    Awesome Dave! Exactly what I was looking for. Did not know about splatting.

    Thank you.

  • #36063
    Profile photo of Stig Sörnsen
    Stig Sörnsen
    Participant

    I ended up with this:

    function CredentialSet ($creds)
    {
    if ($creds) { $splat = @{ Credential = $creds } } else { $splat = @{ UseDefaultCredentials = $true } }
    return $splat
    }

    function Test-Function()
    {
    [cmdletbinding()]
    Param (
    [Parameter()]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential
    )

    $credentialset = CredentialSet($Credential)
    Invoke-RestMethod $url -Method Get -ContentType "application/json" @credentialset
    }

    Couldn't figure out how to 'splat' without putting function return in variable first and then splat the variable.

    But It works.

    Thanks

You must be logged in to reply to this topic.