azure-powershell icon indicating copy to clipboard operation
azure-powershell copied to clipboard

New-AzADGroup does not handle $DebugPreference

Open jikuja opened this issue 1 year ago • 4 comments

Description

$DebugPreference cmdlet does not handle $DebugPreference at all.

Issue script & Debug output

$DebugPreference = "Continue"
New-AzADGroup -DisplayName "foobar" -MailNickname "foobar1"

DisplayName Id                                   MailNickname Description
----------- --                                   ------------ -----------
foobar      480a615f-0fa8-41d5-a1fb-5bdf5c777eab foobar1     

Compare with Update-AzADGroup

Update-AzADGroup -ObjectId 480a615f-0fa8-41d5-a1fb-5bdf5c777eab -DisplayName "foobar" -MailNickname "foobar1" -Description "test"
DEBUG: [CmdletBeginProcessing]: Starting command
DEBUG: CmdletBeginProcessing: 
DEBUG: CmdletProcessRecordStart: 

Confirm
Are you sure you want to perform this action?
Performing the operation "Update-AzADGroup_UpdateExpanded" on target "Call remote 'GroupsGroupUpdateGroup' operation".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): 
DEBUG: CmdletGetPipeline: 
DEBUG: CmdletBeforeAPICall: 
DEBUG: URLCreated: /groups/480a615f-0fa8-41d5-a1fb-5bdf5c777eab
DEBUG: RequestCreated: /v1.0/groups/480a615f-0fa8-41d5-a1fb-5bdf5c777eab
DEBUG: HeaderParametersAdded: 
DEBUG: BodyContentSet: 
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
PATCH

Absolute Uri:
https://graph.microsoft.com/v1.0/groups/480a615f-0fa8-41d5-a1fb-5bdf5c777eab

Headers:
x-ms-client-request-id        : 3e02f1b2-986c-46c7-85a0-c376a6a4b9dd
CommandName                   : Update-AzADGroup
FullCommandName               : Update-AzADGroup_UpdateExpanded
ParameterSetName              : __AllParameterSets
User-Agent                    : AzurePowershell/v10.4.1,PSVersion/v7.4.4,Az.MSGraph/6.11.1

Body:
{
  "displayName": "foobar",
  "description": "test",
  "mailNickname": "foobar1"
}


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

Status Code:
NoContent

Headers:
Cache-Control                 : no-cache
Strict-Transport-Security     : max-age=31536000
request-id                    : 849cadf2-4a33-4942-95af-7d9eb5c9f27c
client-request-id             : 849cadf2-4a33-4942-95af-7d9eb5c9f27c
x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"Sweden Central","Slice":"E","Ring":"3","ScaleUnit":"002","RoleInstance":"GV3PEPF00006567"}}
x-ms-resource-unit            : 1
Date                          : Mon, 23 Sep 2024 07:50:15 GMT

Body:



DEBUG: ResponseCreated: 
DEBUG: BeforeResponseDispatch: 
DEBUG: Finally: 
DEBUG: CmdletAfterAPICall: 
DEBUG: [CmdletProcessRecordAsyncEnd]: Finish HTTP process
DEBUG: CmdletProcessRecordAsyncEnd: 
DEBUG: CmdletProcessRecordEnd: 

Otoh New-AzAdGroup -Debug works but I would like to avoin passing -Verbose and -Debug conditionally:

New-AzADGroup -DisplayName "foobar2" -MailNickname "foobar1" -Debug
DEBUG: [CmdletBeginProcessing]: Starting command
DEBUG: CmdletBeginProcessing: 
DEBUG: CmdletProcessRecordStart: 

Confirm
Are you sure you want to perform this action?
Performing the operation "New-AzADGroup_CreateExpanded" on target "Call remote 'GroupsGroupCreateGroup' operation".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): 
DEBUG: CmdletGetPipeline: 
DEBUG: CmdletBeforeAPICall: 
DEBUG: URLCreated: /groups
DEBUG: RequestCreated: /v1.0/groups
DEBUG: HeaderParametersAdded: 
DEBUG: BodyContentSet: 
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
POST

Absolute Uri:
https://graph.microsoft.com/v1.0/groups

Headers:
x-ms-client-request-id        : 9bdf0462-bbbb-4da9-8288-fa81378b8dff
CommandName                   : Az.MSGraph.internal\New-AzADGroup
FullCommandName               : New-AzADGroup_CreateExpanded
ParameterSetName              : __AllParameterSets
User-Agent                    : AzurePowershell/v10.4.1,PSVersion/v7.4.4,Az.MSGraph/6.11.1

Body:
{
  "displayName": "foobar2",
  "mailEnabled": false,
  "mailNickname": "foobar1",
  "securityEnabled": true
}


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

Status Code:
Created

Headers:
Cache-Control                 : no-cache
Transfer-Encoding             : chunked
Location                      : https://graph.microsoft.com/v2/0a8edbb9-667f-4120-88fd-2cd241f8236f/directoryObjects/2e614f21-a0d5-41bb-b8f5-cc486cf59652/Microsoft.DirectoryServices.Group
Strict-Transport-Security     : max-age=31536000
request-id                    : 0e978305-a3d7-4b75-9c23-05822dc8a063
client-request-id             : 0e978305-a3d7-4b75-9c23-05822dc8a063
x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"Sweden Central","Slice":"E","Ring":"3","ScaleUnit":"000","RoleInstance":"GVX0EPF00004C05"}}
x-ms-resource-unit            : 1
OData-Version                 : 4.0
Date                          : Mon, 23 Sep 2024 07:57:18 GMT

Body:
{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#groups/$entity",
  "id": "2e614f21-a0d5-41bb-b8f5-cc486cf59652",
  "deletedDateTime": null,
  "classification": null,
  "createdDateTime": "2024-09-23T07:57:18Z",
  "creationOptions": [],
  "description": null,
  "displayName": "foobar2",
  "expirationDateTime": null,
  "groupTypes": [],
  "isAssignableToRole": null,
  "mail": null,
  "mailEnabled": false,
  "mailNickname": "foobar1",
  "membershipRule": null,
  "membershipRuleProcessingState": null,
  "onPremisesDomainName": null,
  "onPremisesLastSyncDateTime": null,
  "onPremisesNetBiosName": null,
  "onPremisesSamAccountName": null,
  "onPremisesSecurityIdentifier": null,
  "onPremisesSyncEnabled": null,
  "preferredDataLocation": null,
  "preferredLanguage": null,
  "proxyAddresses": [],
  "renewedDateTime": "2024-09-23T07:57:18Z",
  "resourceBehaviorOptions": [],
  "resourceProvisioningOptions": [],
  "securityEnabled": true,
  "securityIdentifier": "S-1-12-1-778129185-1102815445-1221391800-1385624940",
  "theme": null,
  "uniqueName": null,
  "visibility": null,
  "onPremisesProvisioningErrors": [],
  "serviceProvisioningErrors": []
}


DEBUG: ResponseCreated: 
DEBUG: BeforeResponseDispatch: 

DEBUG: Finally: 
DEBUG: CmdletAfterAPICall: 
DEBUG: [CmdletProcessRecordAsyncEnd]: Finish HTTP process
DEBUG: CmdletProcessRecordAsyncEnd: 
DEBUG: CmdletProcessRecordEnd: 
DEBUG: AzureQoSEvent:  Module: Az.MSGraph:0.0.-1; CommandName: New-AzADGroup; PSVersion: 7.4.4; IsSuccess: True; Duration: 00:00:01.7579590; SanitizeDuration: 00:00:00
DisplayName Id                                   MailNickname Description
----------- --                                   ------------ -----------
foobar2     2e614f21-a0d5-41bb-b8f5-cc486cf59652 foobar1      



### Environment data

```PowerShell
$PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.4.4
PSEdition                      Core
GitCommitId                    7.4.4
OS                             Darwin 22.6.0 Darwin Kernel Version 22.6.0: Mon Jun 24 01:21:41 PDT 2024; root:xnu-8796.141.3.706.2~1/RELEASE_ARM64_T6020
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Module versions

Get-Module Az*

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     3.0.3                 Az.Accounts                         {Add-AzEnvironment, Clear-AzConfig, Clear-AzContext, Clear-AzDefault…}
Script     0.0                   Az.MSGraph.custom                   {Add-AzADAppPermission, Add-AzADGroupMember, Get-AzADAppCredential, Get-AzADAppFederatedCredential…}
Binary     6.11.1.0              Az.MSGraph.private                  {Export-CmdletSurface, Export-ExampleStub, Export-FormatPs1xml, Export-HelpMarkdown…}
Script     6.11.1                Az.Resources                        {Export-AzResourceGroup, Export-AzTemplateSpec, Get-AzDenyAssignment, Get-AzDeployment…}
Script     1.1.2                 Az.Tools.Predictor                  {Disable-AzPredictor, Enable-AzPredictor, Open-AzPredictorSurvey, Send-AzPredictorRating}

Error output

No response

jikuja avatar Sep 23 '24 07:09 jikuja

@VeryEarly can you try to reproduce? THanks

isra-fel avatar Sep 26 '24 06:09 isra-fel

Related: did not test fully yet: Looks like at least of not all MS Graph API related CMdlets ignore also ConfirmPreference and only -Confirm works.

jikuja avatar Oct 04 '24 09:10 jikuja

Hi @jikuja ,

Tried Az.Resource 6.11.1, and the debug message was able to be displayed. I noticed the Module versions section, it not only had version for Az.Resources, but also some internal dll and psm1. Can you try open a new powershell session and start cleanly:

$DebugPreference='Continue'
Import-Module Az.Resources
New-AzADGroup -DisplayName "foobar" -MailNickname "foobar1"

VeryEarly avatar Oct 10 '24 07:10 VeryEarly

Seemss to be working now. This is really weird. Any tips how to find what is causing the issue?

jikuja avatar Oct 10 '24 11:10 jikuja

More details:

PS /home/janne> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.4.5
PSEdition                      Core
GitCommitId                    7.4.5
OS                             CBL-Mariner/Linux
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
PS /home/janne> Get-Module Az*

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     3.0.4                 Az.Accounts                         {Add-AzEnvironment, Clear-AzConfig, Clear-AzContext, Clear-AzDefault…}
Script     8.4.0                 Az.Compute                          {Add-AzImageDataDisk, Add-AzVhd, Add-AzVMAdditionalUnattendContent, Add-AzVMDataDisk…}
Script     7.9.0                 Az.Network                          {Add-AzApplicationGatewayAuthenticationCertificate, Add-AzApplicationGatewayBackendAddressPool, Add-AzApplicationG…
Script     7.5.0                 Az.Resources                        {Export-AzResourceGroup, Export-AzTemplateSpec, Get-AzDenyAssignment, Get-AzDeployment…}
Script     7.4.0                 Az.Storage                          {Add-AzRmStorageContainerLegalHold, Add-AzStorageAccountManagementPolicyAction, Add-AzStorageAccountNetworkRule, C…
Script     1.1.3                 Az.Tools.Predictor                  {Disable-AzPredictor, Enable-AzPredictor, Open-AzPredictorSurvey, Send-AzPredictorRating}
Script     0.0.0.10              AzureAD.Standard.Preview            {Add-AzureADApplicationOwner, Add-AzureADDeviceRegisteredOwner, Add-AzureADDeviceRegisteredUser, Add-AzureADDirect…
Script     0.9.3                 AzurePSDrive      

test.ps1

[CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")]
param (
    [string]
    $objectId,
    [string]
    $description,
    [switch]
    $Force,
    [switch]
    $PassThru
)

if ($Force -and -not $PSBoundParameters.ContainsKey('Confirm')) {
    Write-Verbose "Changing `$ConfirmPreference to None"
    $ConfirmPreference = 'None'
}

Write-Warning $ConfirmPreference
Write-Warning $DebugPreference

Update-AzADGroup -ObjectId $objectId -Description $description -PassThru:$PassThru

Script execution:

PS /home/janne> ./test.ps1 -objectId f686f775-adf2-4c11-902f-7f62449bdaf9 -description "aaaa" -PassThru -Confirm -Debug
WARNING: Low
WARNING: Continue
True
PS /home/janne> ./test.ps1 -objectId f686f775-adf2-4c11-902f-7f62449bdaf9 -description "aaaa" -PassThru -WhatIf        
WARNING: High
WARNING: SilentlyContinue
True

For me it looks like it is pure luck if logging preferences, what or confirm works with MS Graph API -related CmdLets

jikuja avatar Nov 14 '24 13:11 jikuja

I might have found to root cause for this issue: https://stackoverflow.com/a/21292783/776884

The issue here is that variables in a caller's scope do not get picked up by code in a script module. When you call ".\scaffold.ps1 -verbose", $VerbosePreference is set to 'Continue' in scaffold.ps1's script scope. If you call a compiled Cmdlet from that script, it honors that $VerbosePreference value, but when you call Advanced Functions from a script module, they do not.

This was something I did not even think about. Not sure if this is also true for -Confirm flag.


@isra-fel @VeryEarly Looks like reproduciable but the issue is in the PowerShell itself

Probably worth of closing especially if there is documentation about preference variable scoping limitations on MSFT side.


Documentation finding

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.4#long-description has:

Changes to preference variables apply only in the scope they are made and any child scopes thereof. For example, you can limit the effects of changing a preference variable to a single function or script. For more information, see about_Scopes.

and the linked article

Functions from a module don't run in a child scope of the calling scope. Modules have their own session state that's linked to the scope in which the module was imported. All module code runs in a module-specific hierarchy of scopes that has its own root scope. For more information, see the Modules section of this article.

That partially contradicts the original finding but is clearly to root cause of the issue.

jikuja avatar Dec 15 '24 11:12 jikuja

Thanks for the investigation! I'm closing the issue.

isra-fel avatar Dec 17 '24 06:12 isra-fel