Skip to content

Update-AzPolicyAssignment has different behavior when run in Powershell vs Windows Powershell #27649

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
everest146 opened this issue Apr 25, 2025 · 2 comments
Labels
bug This issue requires a change to an existing behavior in the product in order to be resolved. customer-reported needs-team-attention This issue needs attention from Azure service team or SDK team Policy Azure Resource Policy Service Attention This issue is responsible by Azure service team.

Comments

@everest146
Copy link

Description

I have a script that uses Update-AzPolicyAssignment to sync policies I have in Azure with my policy jsons I have in AuzreDevOps. But when I run the script in an Azure Powershell job environment I get the following error:
Test-Path : Illegal characters in path.

I also get this error locally if I try to run it in Windows Powershell. However if I use Powershell, Update-AzPolicyAssignment works as expected. All policies assignments that are fed to this function when run on Windows Powershell yield the same result. Some of the output I added below is shortened to remove lots of repeats.

If you need any more information let me know. Thank you in advance.

Issue script & Debug output

DEBUG: [CmdletBeginProcessing]: Starting command
DEBUG: CmdletBeginProcessing:
DEBUG: CmdletProcessRecordStart:
DEBUG: CmdletGetPipeline:
DEBUG: CmdletBeforeAPICall:
DEBUG: URLCreated:
//providers/Microsoft.Management/managementGroups/***/providers/Microsoft.Authorization/policyAssignments/***
-protection?api-version=2023-04-01
DEBUG: RequestCreated:
//providers/Microsoft.Management/managementGroups/***/providers/Microsoft.Authorization/policyAssignments/***
-protection?api-version=2023-04-01
DEBUG: HeaderParametersAdded:
DEBUG: ============================ HTTP REQUEST
============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com//providers/Microsoft.Management/managementGrou
ps/***/providers/Microsoft.Authorization/p
olicyAssignments/***?api-version=2023-04-01

Headers:
x-ms-unique-id                : 9
x-ms-client-request-id        : e83f3e09-1664-4e44-a4b3-47292ce37e4b
CommandName                   : &
FullCommandName               : Get-AzPolicyAssignment_Get1
ParameterSetName              : __AllParameterSets
User-Agent                    :
AzurePowershell/v0.0.0,PSVersion/v5.1.22621.4391,Az.Policy/7.8.1

Body:


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

Status Code:
OK

Headers:
Pragma                        : no-cache
Strict-Transport-Security     : max-age=31536000; includeSubDomains
x-ms-operation-identifier     :
x-ms-ratelimit-remaining-tenant-reads: 249
x-ms-request-id               : da429540-0285-47c1-b54d-454821bdae50
x-ms-correlation-request-id   : da429540-0285-47c1-b54d-454821bdae50
x-ms-routing-request-id       :
***:***
X-Content-Type-Options        : nosniff
X-Cache                       : CONFIG_NOCACHE
X-MSEdge-Ref                  : Ref A: DD502CD53EA7461EBF9EBC968861A5CB Ref
 B: MNZ221060619039 Ref C: 2025-04-25T21:56:29Z
Cache-Control                 : no-cache

Body:
{
  "identity": {
    "principalId": "***",
    "tenantId": "***",
    "type": "SystemAssigned"
  },
  "properties": {
    "displayName": "",
    "policyDefinitionId":
"/providers/Microsoft.Management/managementGroups/***/providers/Microsoft.Authorization/policySetDefinitions/***",
    "definitionVersion": "1.*.*",
    "scope":
"/providers/Microsoft.Management/managementGroups***",
    "notScopes": [

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***",

"/subscriptions/***/resourceGroups/***"
    ],
    "description": "",
    "metadata": {
      "createdOn": "***",
      "updatedOn": "***",
      "createdBy": "***",
      "updatedBy": "***"
    },
    "enforcementMode": "Default"
  },
  "id":
"/providers/Microsoft.Management/managementGroups/***/providers/Microsoft.Authorization/policyAssignments/***
-protection",
  "type": "Microsoft.Authorization/policyAssignments",
  "name": "***",
  "location": "***",
  "systemData": {
    "createdBy": "***",
    "createdByType": "Application",
    "createdAt": "***",
    "lastModifiedBy": "***",
    "lastModifiedByType": "***",
    "lastModifiedAt": "***"
  }
}

DEBUG: ResponseCreated:
DEBUG: BeforeResponseDispatch:
DEBUG: Finally:
DEBUG: CmdletAfterAPICall:
DEBUG: [CmdletProcessRecordAsyncEnd]: Finish HTTP process
DEBUG: CmdletProcessRecordAsyncEnd:
DEBUG: CmdletProcessRecordEnd:
Test-Path : Illegal characters in path.
At C:\***\Documents\WindowsPowerShell\Modul
es\Az.Resources\7.10.0\Policy.Autorest\custom\Helpers.ps1:423 char:9
+     if (Test-Path $parameterValue) {
+         ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (C:\***\scripts
   \{
}:String) [Test-Path], ArgumentException
    + FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell
   .Commands.TestPathCommand

Environment data

$PSVersionTable is empty in both local and virtual environments

Module versions

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     4.1.0      Az.Accounts                         {Add-AzEnvironment, Clear-AzConfig, Clear-AzContext, Clear-AzDefault...}
Script     7.10.0     Az.Resources                        {Export-AzResourceGroup, Export-AzTemplateSpec, Get-AzDenyAssignment, Get-AzDeployment...}

Error output

DEBUG: Got version 0 of Az
DEBUG: Got version 0 of Az.Accounts
DEBUG: 6:14:14 PM - [ConfigManager] Got nothing from [DisplaySecretsWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 6:14:14 PM - ResolveError begin processing with ParameterSet 'AnyErrorParameterSet'.
DEBUG: 6:14:14 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [Az.Accounts], Cmdlet = [Resolve-AzError]. Returning default
value [True].
DEBUG: 6:14:14 PM - [ConfigManager] Got nothing from [DisplaySecretsWarning], Module = [], Cmdlet = []. Returning default value [True].


   HistoryId: 12


Message        : Illegal characters in path.
StackTrace     :    at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
                    at System.IO.Path.GetFileName(String path)
                    at System.Management.Automation.Utils.IsReservedDeviceName(String destinationPath)
                    at System.Management.Automation.Utils.NativeItemExists(String path, Boolean& isDirectory, Exception& exception)
                    at Microsoft.PowerShell.Commands.FileSystemProvider.ItemExists(String path, ErrorRecord& error)
Exception      : System.ArgumentException
InvocationInfo : {Test-Path}
Line           :     if (Test-Path $parameterValue) {

Position       : At C:\***\Documents\WindowsPowerShell\Modules\Az.Resources\7.10.0\Policy.Autorest\custom\Helpers.ps1:423
                 char:9
                 +     if (Test-Path $parameterValue) {
                 +         ~~~~~~~~~~~~~~~~~~~~~~~~~

   HistoryId: 7


Message        : The 'Get-AzPolicyAssignment' command was found in the module 'Az.Resources', but the module could not be loaded. For more information,
                 run 'Import-Module Az.Resources'.
StackTrace     :    at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                    at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                    at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                    at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
Exception      : System.Management.Automation.CommandNotFoundException
InvocationInfo : {}
Line           :                                $PolicyAssignment = Get-AzPolicyAssignment -Name $AssignmentName -Scope $Assignment.AssignmentScope -ErrorAction Stop

Position       : At C:\***\scripts\New-AzurePolicyInitiativeAssignment.ps1:30 char:25
                 +                 $PolicyAssignment = Get-AzPolicyAssignment -Name $Ass ...
                 +                                     ~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 7



DEBUG: 6:14:14 PM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 6:14:14 PM - [ConfigManager] Got nothing from [CheckForUpgrade], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: AzureQoSEvent:  Module: Az.Accounts:4.1.0; CommandName: Resolve-AzError; PSVersion: 5.1.22621.4391; IsSuccess: True; Duration: 00:00:00.2806546;
SanitizeDuration: 00:00:00.0011187
DEBUG: 6:14:14 PM - [ConfigManager] Got nothing from [EnableDataCollection], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 6:14:14 PM - ResolveError end processing.
@everest146 everest146 added bug This issue requires a change to an existing behavior in the product in order to be resolved. needs-triage This is a new issue that needs to be triaged to the appropriate team. labels Apr 25, 2025
@microsoft-github-policy-service microsoft-github-policy-service bot added customer-reported needs-triage This is a new issue that needs to be triaged to the appropriate team. and removed needs-triage This is a new issue that needs to be triaged to the appropriate team. labels Apr 25, 2025
@isra-fel
Copy link
Member

isra-fel commented May 5, 2025

Hi @everest146 I found this about Test-Path

When a whitespace string is provided for the Path parameter, it returns $false. This is a change from Windows PowerShell 5.1. When an empty string is provided, Test-Path returns an error.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/test-path?view=powershell-7.5#example-8-test-a-path-with-whitespace-as-the-value

Do you happen to know which path is the command testing? Does it contain whitespaces?

@isra-fel isra-fel added Policy Azure Resource Policy Service Attention This issue is responsible by Azure service team. needs-author-feedback More information is needed from author to address the issue. and removed needs-triage This is a new issue that needs to be triaged to the appropriate team. labels May 5, 2025
@microsoft-github-policy-service microsoft-github-policy-service bot added the no-recent-activity There has been no recent activity on this issue. label May 12, 2025
@everest146
Copy link
Author

Hi @isra-fel I'm passing in the Update-AzPolicyAssignment function two parameters: a policy assignment Id in the Id parameter and an array of resource group paths in the NotScope parameter. I've double checked and neither the Id or the NotScope have whitespace in them. Sorry for my delayed response.

@microsoft-github-policy-service microsoft-github-policy-service bot added needs-team-attention This issue needs attention from Azure service team or SDK team and removed needs-author-feedback More information is needed from author to address the issue. no-recent-activity There has been no recent activity on this issue. labels May 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug This issue requires a change to an existing behavior in the product in order to be resolved. customer-reported needs-team-attention This issue needs attention from Azure service team or SDK team Policy Azure Resource Policy Service Attention This issue is responsible by Azure service team.
Projects
None yet
Development

No branches or pull requests

2 participants