Author Posts

March 4, 2016 at 4:22 am

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

March 4, 2016 at 4:58 am

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

March 4, 2016 at 6:51 am

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

Thank you.

March 4, 2016 at 7:10 am

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