Suppress the error when get-credential prompt is cancelled

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of GJ GJ 1 year, 11 months ago.

  • Author
    Posts
  • #21440
    Profile photo of GJ
    GJ
    Participant

    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
     
    
  • #21441
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #21442
    Profile photo of Don Jones
    Don Jones
    Keymaster

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

  • #21443
    Profile photo of GJ
    GJ
    Participant

    Thanks Don, that explains.

  • #21444
    Profile photo of GJ
    GJ
    Participant

    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
    }
    

You must be logged in to reply to this topic.