Suppress the error when get-credential prompt is cancelled

Hi Guys,

Apologies if this is a silly question. I have the below sample code which will prompt for the credentials. When I run this, if I cancel the get-credential prompt, why is it throwing an error and how to suppress that?

Param(
    [Parameter(Mandatory = $false,Position=1)]
        [string[]]$ComputerName = $env:COMPUTERNAME,
    [Parameter(Mandatory = $false)]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty
)
  

if ( 'a' -eq 'a' )
{
    $Credential = Get-Credential -Message "Please provide the credentials" -ErrorAction SilentlyContinue
}

Error info - when I cancel the get-credential prompt.

PS C:\> .\draft.ps1
userName
At C:\draft.ps1:11 char:5
+     $Credential = Get-Credential -Message "Please provide the credentials" -Erro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : Argument
 

You declared the credential parameter as a specific data type; $null isn’t acceptable but that’s what it gets if you cancel the prompt.

You shouldn’t actually be prompting in your script. If someone wants to provide a credential they’ll specify your parameter.

Thanks Don, that explains.

Thanks Don, Actually in my original script I prompt for the credential if the currently logged on user is not a domain user and also if the user hasn’t selected the credential parameter. .

if ( $ComputerName -ne $env:COMPUTERNAME -and $env:USERDOMAIN -ne $domain -and $Credential.UserName -eq $null )
{
    $Credential = Get-Credential -Message "Please provide the credentials to be used to be used for remote connection" -ErrorAction SilentlyContinue
}