Skip to content

Add-MgApplicationPassword fails when run in a Powershell script; trying to cast password credentials into the wrong type #3572

@jwkenney

Description

@jwkenney

Describe the bug

Following example #1 in for adding a new app secret for a registered application, per MS Learn article:
https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.applications/add-mgapplicationpassword?view=graph-powershell-1.0#example-1-add-a-password-credential-to-an-application-with-a-six-month-expiry

When I run the Add-MgApplicationPassword command according to the example in an interactive powershell session (entering each command manually), it is successful.

However, when running the same commands in a Powershell script, it throws the below error:

Cannot convert the "Microsoft.Graph.PowerShell.Models.MicrosoftGraphPasswordCredential" value of type
"Microsoft.Graph.PowerShell.Models.MicrosoftGraphPasswordCredential" to type
"System.Management.Automation.SwitchParameter".
At C:\users\myuser\examplescript.ps1:66 char:5
  +     $newsecret = Add-MgApplicationPassword -ApplicationId ${AppObjectId} ...
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
   + FullyQualifiedErrorId : ConvertToFinalInvalidCastException

Despite this error, I still see the secret added successfully in Azure Portal under the App Registration details. However the secret is not usable, because the error message returned by the command prevents the user from printing the secret value later in the script.

I tried a number of alternative approaches, each giving the same result:

# Attempt #2, inserting credentials as a BodyParameter instead of using -PasswordCredentials. Also did not work.
$body = @{
        passwordCredential = @{
            displayName = "Foo secret"
            endDateTime = (Get-Date).AddDays(180)
        }
    }
    $newsecret = Add-MgApplicationPassword -ApplicationId $AppObjectId -BodyParameter $body

# Attempt #3, Run Invoke-MgGraphRequest directly... also did not work
    $body = @{
      passwordCredential = @{
        displayName = $SecretDescription
        endDateTime = (Get-Date).AddDays(180)
      }
    }
    $newsecret = Invoke-MgGraphRequest `
    -Method POST `
    -Uri "https://graph.microsoft.com/v1.0/applications/$($AppObjectId)/addPassword" `
    -Body $body

My running environment is below. The issue happens with PowerShell 5 and 7.

Expected behavior

The app registration secret is added under the App Registration in Azure Portal, and the PowerShell script returns the new secret's properties successfully.

What happens instead:

  • When run in a PowerShell script, the Add-MgApplicationPassword command throws an error when trying to convert the credential into a SwitchParameter, the credential is created successfully but the error blocks the output of secret value making it useless.
  • When same commands are run individually in an interactive Powershell session, we do not get the type conversion error and we are able to print the secret value afterwards.

How to reproduce

Ref. Example 1 in This microsoft learn article:

Run these commands in an interactive Powershell session, and it should work:

$TenantId = "yourtenant.onmicrosoft.com"
$AppObjectId = "yourobjectID"

Import-Module -NoClobber -Name Microsoft.Graph.Applications
Import-Module -NoClobber -Name Microsoft.Graph.Authentication

$dateStr = (Get-Date).ToString("yyyy-MM-dd")
$Description = "${dateStr} New secret created by $(whoami) from $(hostname) via Powershell"
Connect-MgGraph -NoWelcome -TenantId ${TenantId} -Scopes "Application.ReadWrite.All"
$appInfo = Get-MgApplication -ApplicationId ${AppObjectId}
$newsecret = Add-MgApplicationPassword -ApplicationId ${AppObjectId} -PasswordCredential @{DisplayName = $Description; EndDateTime = (Get-Date).AddDays(180)}
$newsecret | ConvertTo-Json

The same commands will throw an error when running in a Powershell script.

SDK Version

2.36.1

Latest version known to work for scenario above?

No response

Known Workarounds

Current workarounds are:

  • Execute the commands directly in an interactive PowerShell session
  • Run the Add-MgApplicationPassword command with -Debug -Confirm:$false, so that the HTTP response body of the Graph API call is shown. The command will still throw an error, but a user can see the new secret text in the HTTP response body.

Debug output

Click to expand log

With -Debug -Confirm:$false added to Add-MgApplicationPassword command:

DEBUG: [CmdletBeginProcessing]: - Add-MgApplicationPassword begin processing with parameterSet 'AddExpanded'.
DEBUG: [Authentication]: - AuthType: 'Delegated', TokenCredentialType: 'InteractiveBrowser', ContextScope: 'CurrentUser', AppName: 'Microsoft Graph Command Line Tools'.
DEBUG: [Authentication]: - Scopes: [Application.Read.All, Application.ReadWrite.All, openid, profile, email].
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
POST

Absolute Uri:
https://graph.microsoft.com/v1.0/applications/[redacted]/microsoft.graph.addPassword

Headers:
FeatureFlag                   : 00000003
Cache-Control                 : no-store, no-cache
User-Agent                    : Mozilla/5.0,(Windows NT 10.0; Microsoft Windows 10.0.26100; en-US),PowerShell/7.5.4
SdkVersion                    : graph-powershell/2.36.1
client-request-id             : [redacted]
Accept-Encoding               : gzip,deflate,br

Body:
{
  "passwordCredential": {
    "displayName": "2026-03-31 Created by testscript.ps1 by [redacted] on [redacted]",
    "endDateTime": "2046-03-30T19:04:56.0702256Z"
  }
}


DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Cache-Control                 : no-cache
Location                      : https://graph.microsoft.com/
Vary                          : Accept-Encoding
Strict-Transport-Security     : max-age=31536000
request-id                    : [redacted]
client-request-id             : [redacted]
x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"East US","Slice":"E","Ring":"5","ScaleUnit":"002","RoleInstance":"BL02EPF000025FA"}}
x-ms-resource-unit            : 1
odata-version                 : 4.0
Date                          : Tue, 31 Mar 2026 19:05:06 GMT

Body:
{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.passwordCredential",
  "customKeyIdentifier": null,
  "displayName": "2026-03-31 Created by testscript.ps1 by [redacted] on [redacted]",
  "endDateTime": "2046-03-30T19:04:56.0702256Z",
  "hint": "M.k",
  "keyId": "bba1a609-c544-4d19-b75c-aa626b625b88",
  "secretText": "RedactedSecretText",
  "startDateTime": "2026-03-31T19:05:04.6767267Z"
}

DEBUG: [CmdletEndProcessing]: - Add-MgApplicationPassword end processing.
InvalidArgument: C:\Users\testuser\projects\devops\testscript.ps1:87
Line |
  87 |      $newsecret = Add-MgApplicationPassword -ApplicationId $AppObjectI …
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot convert the "Microsoft.Graph.PowerShell.Models.MicrosoftGraphPasswordCredential" value of type
     | "Microsoft.Graph.PowerShell.Models.MicrosoftGraphPasswordCredential" to type "System.Management.Automation.SwitchParameter".

Configuration

PS > $PSVersionTable
Name                           Value
----                           -----
PSVersion                      7.5.4
PSEdition                      Core
GitCommitId                    7.5.4
OS                             Microsoft Windows 10.0.26100
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

PS > Get-Module Microsoft.Graph.Applications -ListAvailable

    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Script     2.36.1                Microsoft.Graph.Applications        Core,Desk {Add-MgApplicationKey, Add-MgApplicationPassword, Add-MgServicePrincipalKey, Add-MgServicePrincipalPassword…}

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    status:waiting-for-triageAn issue that is yet to be reviewed or assignedtype:bugA broken experience

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions