How to determine if user cancels prompt for credentials

Hopefully just a quick question. I have a script where I have a function/optional parameter as follows that allows a user to enter partial, or complete credentials. If they just enter nothing, when calling the function, or they enter the user’s UPN, they get prompted for the missing part of the credentials. Is there a way to detect if the user cancels this credential prompt?

Function Blah
{
  Param
  (
    [PSCredential] $Credential = $Null
  )
}

Let me clarify further what I’m trying to catch. When I run the function, I’m running it as:

Blah -Credential user@domain.com

I’m trying to detect that the user ran it that way, but then chose to cancel the prompt.

You could do something like this

Function Blah
{
  Param
  (
    [string]$Credential
  )
  If ($Credential) {
    $psCred = Get-Credential -UserName $Credential -Message "Enter Credentials"
    If ($psCred) {
        Write-Verbose -Message "Credential Captured"
    } Else {
        Write-Verbose -Message "Credential Prompt Canceled"
    }
  } Else {
    Write-Verbose -Message "No Credential supplied"
  }
}
$VerbosePreference = "Continue"
Blah -Credential user@domain.com

Hi Kevyn,

You can use the ValidateNotNullOrEmpty Validation Attribute. That will make the function throw an error, if the credential prompt is cancelled.

function Blah {
    Param(
        [ValidateNotNullOrEmpty()]
        [PSCredential]
        $Credential = $null
    )
    
    $Credential
}

Blah -Credential user@domain.com

Thanks guys. I’ll probably end up going with the [ValidateNotNullOrEmpty()] option. To clarify, here is what I have.

Function Connect-O365ExchangeOnline
{
  [CmdletBinding()]
  Param
  (
    [PSCredential] $Credential = $Null,
  )

  [String] $FunctionName = 'Connect-O365ExchangeOnline'

  If(!$Credential)
  {
    Try
    {
      Write-Verbose "Prompting user for Office 365 credentials."
      $Credential = Get-Credential -ErrorAction Stop
    } #End 'Try' block
    Catch
    {
      Write-Warning "User cancelled the request for credentials.  Exiting the $FunctionName function."
    } #End Catch block
  } #End 'If' block

When I run the following, I get prompted for credentials and if I hit the Cancel button I immediately get the warning from my above code.

Connect-O365ExchangeOnline

When I run the following, I get prompted for credentials, click Cancel, get prompted again, click Cancel, and finally get my warning message.

Connect-O365ExchangeOnline -Credential user@domain.com

I understand why I’m getting the second prompt and was looking for a way to stop things after just the first cancellation, and with the hopes of displaying my warning message before the error…but the error message from the [ValidateNotNullOrEmpty()] option may be the way I’ll have to go. It certainly did stop the script when I cancelled on the first prompt for credentials. Just was hoping to display the warning before it. I appreciate the ideas. :slight_smile: