Best way to implement PSCredential in CmdLet

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

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.)

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

Thank you.

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