Since you're trying to assign $myCredential
with Get-Credential
in the case of it being absent, then I assume you want your parameter to be a [PSCredential]
.
In that case, strongly type your parameter, and mark it as mandatory (by the way [ref]
is not needed at all :
function Get-MyCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[PSCredential]
$Credential
)
Write-Host "Got credential with username '$($Credential.Username)'"
}
This way, you really don't have to do any checking at all. Making it Mandatory lets PowerShell enforce that for you, and making it a [PSCredential]
ensures that the object is a valid [PSCredential]
from the start.
The only other case you might want to check for, depending on what you're doing with the credential, is an empty credential.
To do that you can compare it to [PSCredential]::Empty
, and you can do it in a validation attribute so it gets done on parameter binding:
function Get-MyCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[PSCredential]
[ValidateScript( {
$_ -ne [PSCredential]::Empty
} )
$Credential
)
Write-Host "Got credential with username '$($Credential.Username)'"
}
You can do other validation in there if you want (checking for a certain username format, like if it needs to be an email address or something). If it's complex it may be better done within the function body, depends on the scenario.
But for the most part you probably don't need additional validation at all.