Repository navigation
Run with Az PowerShell only: drop the Azure CLI - #66
Draft
pmorgenrood wants to merge 139 commits into
Draft
pmorgenrood wants to merge 139 commits into
pmorgenrood wants to merge 139 commits into
Conversation
added 9 commits
October 28, 2026 23:44
Offline Pester tests, no live Azure: - LoginSessionReuse: the three direct-run sign-in rules (service principal always wins; a usable cached Az PowerShell sign-in is reused; otherwise one sign-in, a token check, and exit 1), managed identity, process-only service principal and managed identity sign-ins, and the reconnect before metrics and consumption. - WrapperSignIn: the Run-AllSubscriptions.ps1 sign-in gate. - TenantSubscriptions: Get-AzSubscription -TenantId, delegated and duplicate subscriptions. - AzGraphQueryPaging / AzGraphQueryRetry: Resource Graph through Invoke-AzRestMethod with canned pages (0, 1, 1000+ rows), skip tokens, subscription batches, the empty-key sentinel, status-code retries and a retry cap that holds under SilentlyContinue. - SetupStop: a missing or unloadable Az module, low disk and an unwritable output folder stop a direct run with exit 1 before any Azure call. - NoAzCli: a guard that no script calls az or Search-AzGraph.
Invoke-AzGraphQuerySafe now posts the query to the Resource Graph REST API with Invoke-AzRestMethod (Az.Accounts) instead of running `az graph query`, so neither the Azure CLI nor Az.ResourceGraph is needed. The raw response text is kept, so a resource with an empty-string property key is still returned (the empty key is renamed to a sentinel before parsing), and -Lowercase lowercases culture-invariantly. Every page is read with the skip token, in subscription batches of at most 1000, and the inventory and AVD queries name the run's subscriptions explicitly. Errors are classified by status code (400/401/403/408/429/5xx, Retry-After); retries are capped with an explicit break, so the cap holds under the production SilentlyContinue preference, and a failure throws instead of returning a partial page.
A direct run of ResourceInventory.ps1 signs in by three rules: 1. -Appid, -Secret and -TenantID always sign in as the service principal, even when a user is already signed in. 2. Otherwise an Az PowerShell sign-in on the target tenant that can get a token without a prompt is reused, with no prompt. 3. Otherwise it signs in once (-DeviceLogin for device code, the new -UseManagedIdentity for the machine's identity), checks the token and stops with exit 1 if there is still none, instead of prompting again or collecting an empty inventory. A usable sign-in is never signed out; a tenant switch, and service principal and managed identity sign-ins, apply to this process only (-Scope Process), so a later run without -Appid or -UseManagedIdentity does not reuse that identity. The reconnect before metrics and consumption keeps the same identity. Run-AllSubscriptions.ps1 uses the same checks (Connect-RdaWrapperSession): reuse a usable sign-in on -TenantID, else sign in once and stop with exit 1 when no token follows. Subscriptions are listed with Get-AzSubscription -TenantId, so subscriptions delegated to the tenant are kept and duplicates are dropped, instead of `az account list`.
ResourceInventory.ps1 no longer checks for az or installs its resource-graph extension, and Run-AllSubscriptions.ps1 no longer detects or installs the Azure CLI. The Az module check and the disk-space and write pre-flight checks of a direct run used throw, which the production SilentlyContinue preference suppresses: with Az.Compute or Az.Monitor missing the run went on to sign in and collect, and the VM and VMSS collectors failed later. They now log the reason and exit 1 before any Azure call, as the sign-in stop does.
The Azure CLI and its resource-graph extension are no longer prerequisites. Describe the three sign-in rules, -UseManagedIdentity, process-only service principal and managed identity sign-ins, and the exit 1 when a required Az module is missing.
A row that already holds a key named _rda_emptykey (in any case) gets a numbered sentinel instead, so no value is dropped. A parse error quotes at most 500 characters of the page and of the parser message, and none of the page under -Obfuscate.
…thod The consumption phase and the wrapper's consumption probe switch the subscription with Set-AzContext -Scope Process, so a run no longer rewrites the user's saved default subscription. The zero-resources hint prints an Invoke-AzRestMethod one-liner instead of Search-AzGraph, whose module the tool does not install. Both are guarded in Tests/NoAzCli.Tests.ps1.
- A service principal or managed identity sign-in that throws, or leaves the context on another account, stops the run with exit 1 instead of collecting as a cached user. - Azure Cloud Shell signs in through LoginSession like any other environment: its own sign-in is a cached sign-in (probed, tenant checked), and -Appid, -UseManagedIdentity, -DeviceLogin and -TenantID are honoured. - The run goes on only when the context is on the target tenant. A cached account that reaches -TenantID silently is switched to it for this process instead of prompting; a domain -TenantID is compared by id. - The tenant picker lists the tenants subscriptions are accessed through (TenantId, so Azure Lighthouse managing tenants appear) plus the context's tenant. An answer out of range is asked again once, then the run stops. - A direct run whose tenant lists no subscriptions stops with exit 1. A session with no console stops instead of opening a browser (-DeviceLogin still signs in). - The reconnect before metrics and consumption happens at most once per run, signs a user in on the run's tenant (or switches back to it silently), and skips the phase rather than prompting a second time. - Tests/SignInRules.Tests.ps1 runs each case end to end in a child pwsh under the production preference.
Cloud Shell follows the same rules; a failed service principal or managed identity sign-in stops the run; a cached account is switched to -TenantID without a prompt; a run with no console, no chosen tenant or no subscriptions stops; the reconnect is once per run and never a second prompt. Drop the 'more than one authentication request' notes, and give -Secret as the SecureString it is.
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Oct 29, 2026
…ep state on a zip failure, no browser without a console Review council findings on the merged candidate (gpt-5.6-sol, claude-opus-5.5): - MAJOR, loop trap (awslabs#48 x awslabs#52 x awslabs#68): a subscription whose run wrote no report zip was taken off the completed list but never put on the retry list, so every -Resume collected it again, ended with exit 2 and kept the state; the retry limit never counted it. The sequential loop, the one-subscription path and the stream worker now record it as a failed run ("the run wrote no report zip"), so -ResumeFailedOnly retries it and the retry limit ends a cause that does not go away. awslabs#48's tests that asserted the old behaviour now expect the retry entry. - MAJOR, pre-existing: Get-WrapperExitCode ignored $FailedSubscriptions, so a run with failed subscriptions exited 0 ("clean run"). It now returns 2 (a report is missing from the bundle) and the README says so. - MAJOR/MINOR (awslabs#63 x awslabs#48): the resume state was cleared even when the consolidated zip could not be built, so the next -Resume collected every subscription again. The state is now kept while $BundleBuildError is set. - MAJOR (awslabs#66): the wrapper sign-in opened a browser with no console (scheduled task, CI). It now stops with exit 1 and advice, as a direct run does; -DeviceLogin and a reusable sign-in still work. Each change has a test that failed before it (RetryLimit, WrapperSignIn, RunAllSubscriptionsReconciliation).
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Oct 30, 2026
# Conflicts: # Functions/Common.Functions.ps1 # Functions/RunAllSubscriptions.Functions.ps1 # README.md # ResourceInventory.ps1
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Oct 30, 2026
…wslabs#59/awslabs#61/awslabs#64/awslabs#53/awslabs#56): run the offline harnesses on the Az PowerShell path The child-process harnesses of these PRs answered sign-in, the subscription list and Resource Graph through an 'az' stand-in. awslabs#66 drops the Azure CLI, so that stand-in is never called. Tests/Helpers/AzPsStandIns.ps1 now gives every harness Get-AzSubscription, Get-AzAccessToken -TenantId, a signed-in context and Resource Graph paging through Invoke-AzRestMethod with skip tokens, and answers each page from the harness's own graph stand-in (renamed Invoke-StandInGraph). Discovery queries go through Invoke-DiscoveryGraphQuery (awslabs#59), so the -HideRawOutput check reads those calls. awslabs#59's unparsable page is now a cut-off page (an empty property name is kept since awslabs#66), and awslabs#52's setup stop is shown with a missing Az module instead of a missing Azure CLI.
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Oct 30, 2026
… the pending list into the fallback tests, drop the az stand-ins The one-subscription fallback now takes the pending list the wrapper builds before it, so awslabs#48's and awslabs#49's tests that lift that block set it from their subscriptions. The end-of-run merge no longer deletes the per-stream files itself (the wrapper deletes them with the resume state), so awslabs#49's merge test expects them still there. The az command the -Resume harnesses put on PATH is removed: the tool signs in with Az PowerShell only, and nothing called it.
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Oct 30, 2026
…ep state on a zip failure, no browser without a console Review council findings on the merged candidate (gpt-5.6-sol, claude-opus-5.5): - MAJOR, loop trap (awslabs#48 x awslabs#52 x awslabs#68): a subscription whose run wrote no report zip was taken off the completed list but never put on the retry list, so every -Resume collected it again, ended with exit 2 and kept the state; the retry limit never counted it. The sequential loop, the one-subscription path and the stream worker now record it as a failed run ("the run wrote no report zip"), so -ResumeFailedOnly retries it and the retry limit ends a cause that does not go away. awslabs#48's tests that asserted the old behaviour now expect the retry entry. - MAJOR, pre-existing: Get-WrapperExitCode ignored $FailedSubscriptions, so a run with failed subscriptions exited 0 ("clean run"). It now returns 2 (a report is missing from the bundle) and the README says so. - MAJOR/MINOR (awslabs#63 x awslabs#48): the resume state was cleared even when the consolidated zip could not be built, so the next -Resume collected every subscription again. The state is now kept while $BundleBuildError is set. - MAJOR (awslabs#66): the wrapper sign-in opened a browser with no console (scheduled task, CI). It now stops with exit 1 and advice, as a direct run does; -DeviceLogin and a reusable sign-in still work. Each change has a test that failed before it (RetryLimit, WrapperSignIn, RunAllSubscriptionsReconciliation).
pmorgenrood
force-pushed
the
upstream-pr/powershell-only
branch
from
October 30, 2026 20:26
ac0da18 to
e85c10a
Compare
added 6 commits
October 31, 2026 13:48
…o console The wrapper sign-in opened a browser with no console to sign in from (a scheduled task, CI, pwsh -NonInteractive). It now stops with exit 1 and advice, as a direct run does; -DeviceLogin and a reusable sign-in still work. Test: WrapperSignIn 'stops without opening a browser when there is no console and no -DeviceLogin'.
ResourceInventory.ps1 ends without exit when it succeeds, which leaves
$LASTEXITCODE as it was. With no native command in the run to reset it,
one subscription's exit 1 marked every later subscription of the same
loop or stream as failed ("Script exited with code 1") although its
report was written, and put it on the retry list. A native command that
failed in the session before the wrapper started failed every
subscription. The sequential loop, the one-subscription path and the
stream worker now set it to 0 before each call.
Test: ExitCodeCarryOver runs the wrapper with the real inventory script.
The wrapper ended with an exit only when its code was not 0. A clean run started inside a PowerShell session (Cloud Shell, a calling script) then left $LASTEXITCODE as it was before the run: 1 after a failed command or an earlier run that stopped with exit 1. With two or more streams no inventory runs in the session, so nothing else sets it. The clean path now ends with exit 0, after the transcript has stopped. Test: ExitCodeCarryOver runs the wrapper in a pwsh -Command session.
…more count_ was cast with [long]. Under the inventory's SilentlyContinue, a present value that is not a number failed the cast and read as 0, which skipped that query's rows; a fraction became a whole number and a negative number was added as it was. It is now parsed with [long]::TryParse in the invariant culture, and a value that is not a whole number of 0 or more throws a clear error. The function sets ErrorActionPreference to Stop, as Invoke-AzGraphQuerySafe does, so the error ends it there as a Resource Graph failure does.
…n ids The test ran the real ResourceInventory.ps1 without the flag that skips its online version check, so every run downloaded Version.json from GitHub. The stand-in Az.Accounts, which the wrapper and every stream load first, now sets that flag and the platform, as Tests/SetupStop.Tests.ps1 does in its harness. Each child also gets POWERSHELL_TELEMETRY_OPTOUT=1. The stand-in subscription ids are built at run time, since ResourceInventory.ps1 takes only a GUID.
This was referenced Nov 4, 2026
added 7 commits
November 9, 2026 10:10
With no saved sign-in and no -TenantID the script signs in itself. It turned debug output off for the sign-in, then set $DebugPreference to 'Continue' instead of back to what it was, so the Az cmdlets the sign-in step ran afterwards (the subscription list, the tenant choice) printed DEBUG lines in a run without -Debug. The earlier value is now saved and put back, also when the sign-in stops the run; under -Debug that is still 'Continue'. The new test runs the real script against offline stand-ins whose subscription list writes one debug line: signing in itself without and with -Debug, and reusing a saved sign-in, under en-US and tr-TR. The run harness gains -DebugOutput (pass -Debug), -NoResources (subscriptions with no resources) and one-at-a-time up-front checks for a run over several subscriptions, which the later tests use. Tests/Helpers/AzPsStandIns.ps1 comes with it: the offline Az PowerShell stand-ins (sign-in, subscription list, Resource Graph paging) that the run harness and the later discovery tests load.
Resource discovery reads Resource Graph 1,000 rows per request, so the pages of one query are read seconds apart. The query sorted by id, and Resource Graph sorts text by its exact characters, upper case before lower case. The same resource can come back with its resource group in upper case on one read and in lower case on the next: a virtual machine that is starting or stopping switches several times within a few seconds. Its row then moves between the first and the last page while the pages are read, so the inventory listed the VM twice (once with its old power state) or left it out, and one other resource at a page edge was lost or listed twice with it. The total row count stayed the same, so nothing reported it. The three resource discovery queries (-ResourceGroup, -SubscriptionID and every subscription) now sort by tolower(id), which keeps each row in one place whatever the case of its id. The rows and columns returned are the same; only their order changes, for resources whose id holds upper-case letters. The AVD query pages the same way and is not changed. Tests/DiscoveryPageOrder.Tests.ps1 runs the real ResourceInventory.ps1 on each discovery path with a stand-in Resource Graph that sorts as Resource Graph does and changes one resource's group case after the first page, in both directions. Before this change the resource was listed twice or not at all; now every resource is listed once.
The AVD discovery query (desktopvirtualizationresources) reads Resource Graph 1,000 rows per request and sorted by id, which Resource Graph compares by exact characters, upper case first. When the resource group in a row's id changes case between two page reads, the row moves between the first and the last page: it is listed twice or not at all, and the row at the page edge is lost or listed twice with it. The resource discovery queries already sort by tolower(id); the AVD query now does the same. The page order tests now also run the AVD path with 1,501 session hosts, one of which changes case after the first page.
Host pools come from the resources table, which a -SubscriptionID run reads for that subscription only. The session host query (desktopvirtualizationresources) named every subscription the identity can see, also under -SubscriptionID. The wrapper runs one -SubscriptionID run per subscription, so each of them read the other subscriptions' session hosts. Those never match the run's host pools, but their real ids went into every run's obfuscation dictionary, each run gave the same session host its own tokens, and an empty subscription counted them as its own resources. The session host query now names -SubscriptionID when it is given, as the resources query does. A run over every subscription still names all of them. No output field, column or id shape changes. Test: Tests/AvdSubscriptionScope.Tests.ps1 runs the real script offline with two subscriptions and checks the subscriptions each AVD query names and the real ids the dictionary holds. (cherry picked from commit bde0c1d537c5f0ccdb53ae7318832602f53b168e)
The Quick Start and the local set-up steps now say that PowerShell 7 and the four Az submodules are all the tool needs, that the Azure CLI is not used, and how to sign in.
Az.Accounts 5.5.4 is the version this tool was tested with live, so both entry points now check for it before they sign in. - Functions/AzModules.Functions.ps1 holds the minimum version in one place and checks the highest installed Az.Accounts and any copy already loaded in the session. - Missing or older: the run prints the version it found, the version it needs and the Install-Module command (-MinimumVersion 5.5.4 -Scope CurrentUser), then stops with exit 1. Running that command is the way out; the next run passes the check. - An older Az.Accounts already loaded in the session cannot be replaced, so the run stops and asks for a new PowerShell session. - Run-AllSubscriptions.ps1 counts an old Az.Accounts as missing; its install offer installs 5.5.4 or newer, checks once more and stops with the command if that did not work. No retry loop. - README prerequisites name Az.Accounts 5.5.4 or newer. Tests: Tests/AzAccountsVersion.Tests.ps1 (21 tests: older, equal, newer, missing, several installed, older already loaded, both entry points, interactive install once).
The version check reads the highest Az.Accounts on disk, but a plain Import-Module takes the first copy in PSModulePath order. With an older copy in an earlier folder, the check passed and the older one loaded. The direct run, the wrapper and each stream now import Az.Accounts with -MinimumVersion (Get-RdaAzAccountsMinimumVersion), and the direct run and the wrapper check the loaded copy once more after the import. A copy that is still too old stops the run with exit 1 and the same advice (a new session, or the install command) before any Azure call. Nothing retries. Tests: AzAccountsVersion covers both entry points with an older copy first on the path (import names the minimum; a stand-in that loads the older copy anyway stops with exit 1) and an AST check that every Az.Accounts import in the three entry scripts names -MinimumVersion. SetupStop's Import-Module stand-in now takes -MinimumVersion.
added 15 commits
November 10, 2026 15:33
…ionID az account list listed only Enabled subscriptions by default, so a direct run over the tenant left Disabled and Warned ones out. Get-AzSubscription lists every state, and the run collected them too. A direct run without -SubscriptionID now keeps the Enabled ones; -SubscriptionID still collects the one it names, and the wrapper's -IncludeDisabled path is unchanged.
…tion A run given -SubscriptionID that finds nothing no longer suggests passing it. The state filter now compares without case, as the wrapper does. The comment on Get-RdaTenantSubscriptions says callers filter, and the tests check the advice text.
…rceGroup alone A tenant that lists no subscription at all now says so, without the -SubscriptionID hint. A -SubscriptionID the sign-in does not list stops the run instead of writing an empty report. -ResourceGroup without -SubscriptionID now exits 1. Comments say plainly which caller filters.
Another open change moves the refusal ahead of the metrics preflight. The test now runs the check wherever it sits, so it holds with either change merged.
…t 1 on a wrong -OutputDirectory The argument check now runs before LoginSession, so nobody is asked to sign in for a run that cannot go on. A wrong -OutputDirectory exited 0; it now exits 1. The tests run each check in a child process and check its message and exit code.
…n is Enabled The PowerShell 7 stop exited 0; it now exits 1. When the tenant lists subscriptions but none is Enabled, the advice no longer suggests checking Reader access. The -OutputDirectory test now uses a folder that cannot be made, the only case the check sees.
The version check ran only on Windows, so PowerShell 6 on Linux or macOS went on. It now runs for every platform, with a test of the whole check on Unix and Windows. Two comments say more plainly which run does what.
The -ResourceGroup, -OutputDirectory and PowerShell 7 stops now name the parameters as typed and say what to do. The test header says the Enabled filter applies to the listed subscriptions.
The version check ran after the module checks, so on PowerShell 6 a module stop could come first with other advice. It is now the script's first statement, with a test of its place and its stop. Two test comments are plainer.
On a Turkish host ToLower() turned RG-INFRA into rg-ınfra, so the Resource Graph query matched no resource group and the report was empty. The test runs the inventory loop under en-US and tr-TR.
… not stand in The branch that skips network resources adds helpers to the loop, so the test stopped before its query. Unknown commands are now no-ops in the test's child run.
This was referenced Nov 12, 2026
added 4 commits
November 12, 2026 17:03
…ll-only The wrapper and the stream worker read each subscription's resource count from $Global:ResourceCount, as awslabs#41 does (it frees $Global:Resources before the report), and keep this branch's report zip path and narration guard on top.
Since awslabs#41 the wrapper reads each subscription's count from $Global:ResourceCount, because ResourceInventory.ps1 releases $Global:Resources before the report. The stand-in for that script now sets the count too, so a stream still prints its 'done' line.
The tests where a console line cannot be written after a subscription worked passed also when the run counted 0 resources, because that run prints a warning instead of the refused line. The stand-in now records each refused line, and the tests check it is the line of a subscription that worked.
The two stream workers are separate processes that both appended to one file, so a write that collided could drop a line. Each process now writes its own file and the test reads them all.
pmorgenrood
force-pushed
the
upstream-pr/powershell-only
branch
from
November 17, 2026 23:54
072caef to
1e1bf73
Compare
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 17, 2026
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 17, 2026
… failure, no browser without a console Changes on the merged candidate: - loop trap (awslabs#48 x awslabs#52 x awslabs#68): a subscription whose run wrote no report zip was taken off the completed list but never put on the retry list, so every -Resume collected it again, ended with exit 2 and kept the state; the retry limit never counted it. The sequential loop, the one-subscription path and the stream worker now record it as a failed run ("the run wrote no report zip"), so -ResumeFailedOnly retries it and the retry limit ends a cause that does not go away. awslabs#48's tests that asserted the old behaviour now expect the retry entry. - pre-existing: Get-WrapperExitCode ignored $FailedSubscriptions, so a run with failed subscriptions exited 0 ("clean run"). It now returns 2 (a report is missing from the bundle) and the README says so. - (awslabs#63 x awslabs#48): the resume state was cleared even when the consolidated zip could not be built, so the next -Resume collected every subscription again. The state is now kept while $BundleBuildError is set. - (awslabs#66): the wrapper sign-in opened a browser with no console (scheduled task, CI). It now stops with exit 1 and advice, as a direct run does; -DeviceLogin and a reusable sign-in still work. Each change has a test that failed before it (RetryLimit, WrapperSignIn, RunAllSubscriptionsReconciliation).
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 18, 2026
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The tool no longer needs the Azure CLI. It signs in, lists subscriptions and queries Resource Graph with the Az PowerShell
modules it already loads (
Az.Accounts,Az.Compute,Az.Monitor,Az.Billing). The Azure CLI and itsresource-graphextension are no longer prerequisites, and
Az.ResourceGraphis not needed either.Problem
On
mainthe tool needs two sign-ins and two toolchains: the Azure CLI for sign-in, subscriptions and Resource Graph(
az login,az account list,az graph query), and Az PowerShell for metrics and consumption. That causes several problems:az loginand again withConnect-AzAccount. When there is no Azure CLIsign-in on the requested tenant it first runs
az account clear, which signs the user out of the Azure CLI. Nothing checksafterwards that either sign-in can still get a token. When MFA or Conditional Access blocks the token, the run carries on
and collects an empty inventory with no error.
-Appid -Secret -TenantID, a cached Azure CLI user on that tenant takes theearly return, so the run collects as that user instead of the service principal. In Azure Cloud Shell the sign-in step is
skipped altogether:
-Appidand-DeviceLoginare ignored, the cached token is neverchecked, and the tenant is never compared with
-TenantID.tenant number outside the picker's list, or a tenant with no subscriptions, ends in an empty report with exit
0. Thereconnect before metrics and consumption signs a user in with no tenant (it can land on the home tenant) and can prompt a
second time in a run.
templates) hold a property named
"". PowerShell 7'sConvertFrom-Jsonrefuses such a key, so the wholeaz graph queryanswer cannot be parsed. Under the script's
SilentlyContinuepreference that error is suppressed: reproduced offline, apage of two resources, one with an empty key, adds 0 resources to the inventory and the run carries on.
$ErrorActionPreference = 'SilentlyContinue'(unless-Debug),and under it a bare
throwis ignored. The Az module check, the low-disk check and the write check all stop withthrow. Sowith
Az.ComputeorAz.Monitornot installed the run goes on to sign in and collect, and the VirtualMachines and VMSScollectors fail later. With an output folder that cannot be written to, it prints
Pre-flight checks passed.queried, and paging uses
--skip/--firstinstead of the skip token.Change
Sign-in (direct run of
ResourceInventory.ps1, local PowerShell and Azure Cloud Shell alike). Three rules, in this order:-Appid,-Secretand-TenantIDalways sign in as the service principal (the secret stays a SecureString), even when auser is already signed in.
-Appidwithout the other two stops with exit1. If the service principal sign-in throws, orthe context afterwards is not a
ServicePrincipalaccount with that app id, the run stops with exit1; it nevercontinues as the cached user. New
-UseManagedIdentityworks the same way (the context must be aManagedServiceaccount).
when it is on that tenant, or switched to
-TenantIDfor this process (Set-AzContext -Tenant -Scope Process) when it ison another one. In Cloud Shell, Cloud Shell's own sign-in is such a sign-in.
Connect-AzAccount;-DeviceLoginfor device code), then checks the token. If thesign-in fails or there is still no token, the run stops with exit
1and says which command to run yourself. It does notprompt again. In a session with no console it stops with exit
1instead of opening a browser (-DeviceLoginstill signsin).
Whatever the rule, the run goes on only when the context is on the target tenant (a domain
-TenantIDis compared by itsid) and the tenant lists at least one subscription; otherwise it stops with exit
1instead of writing an empty orwrong-tenant report. After a fresh sign-in without
-TenantID, the tenant picker lists the tenants subscriptions areaccessed through (
TenantId, so an Azure Lighthouse managing tenant is offered) plus the context's tenant; a number outsidethe list is asked for once more, then the run stops.
A usable sign-in is never signed out. Every
Set-AzContext(tenant switch, and the consumption phase's subscription switch)applies to the script's own process only (
-Scope Process), so the user's saved default subscription is left alone. Serviceprincipal and managed identity sign-ins are also process-only (
Connect-AzAccount -Scope Process), so a later run without-Appidor-UseManagedIdentitydoes not quietly reuse that identity.The reconnect before metrics and consumption happens at most once per run. It keeps the identity: the service principal, the
managed identity (never a user sign-in), or for a user a silent switch back to the run's tenant, else one sign-in on the run's
tenant (
-Tenant) if the run has not prompted yet. When a user reconnect would be a second prompt, or there is no console,the phase is skipped with an error and the rest of the inventory continues.
Sign-in (
Run-AllSubscriptions.ps1). The same check: a usable Az PowerShell sign-in on-TenantIDis reused, otherwisethe wrapper signs in once and stops with exit
1when no token follows. The Azure CLI detection and install step is removed.Subscriptions. Listed with
Get-AzSubscription -TenantId, so subscriptions delegated to the tenant (Azure Lighthouse) arekept and a subscription returned twice is listed once.
Resource Graph.
Invoke-AzGraphQuerySafeposts the query to the Resource Graph REST API withInvoke-AzRestMethod(fromAz.Accounts):_rda_emptykeybefore parsing, so those resources are kept;when the answer already holds that name (in any case) a numbered name is used, so no value is dropped. With
-Lowercasethetext is lowercased culture-invariantly.
Retry-Afterwhen Azure gives it; 400, 401, 403and 404 fail at once. The retry cap is an explicit loop limit, so it holds under
SilentlyContinue. A failure, or an answerthat cannot be parsed, throws with the status, the error code and the query. A run never continues with a partial page. A
parse error quotes at most 500 characters of the answer, and none of it under
-Obfuscate.Setup stops. A missing Az module, an Az module that is on disk but does not load, under 100 MB free, and an output folder
that cannot be written to now print the reason and stop a direct run with exit
1, before any Azure call.Wrapper hint. When a subscription returns 0 resources, the wrapper prints an
Invoke-AzRestMethodone-liner to check itinstead of
Search-AzGraph, whose module the tool does not install.README. The Azure CLI and the
resource-graphextension are gone from the prerequisites. The sign-in rules and-UseManagedIdentityare documented, the "more than one authentication request" notes are removed, and-Secretis shown asthe SecureString it is.
What users see
Connect-AzAccount, or Cloud Shell): no prompt; the sign-in is reused, also foranother tenant it can reach silently.
Connect-AzAccountprompt (browser,or a device code with
-DeviceLogin), then continues. Later runs reuse that sign-in with no prompt. Their Azure CLI sign-inis left alone (the script no longer runs
az account clear).exit
1instead of collecting as whoever was signed in.1with advice instead of waiting on a browser.Testing
Offline Pester 5.7.1 on PowerShell 7, with stand-ins for every Azure cmdlet; no live Azure. New test files:
Tests/LoginSessionReuse.Tests.ps1: the three sign-in rules, device code, managed identity, the tenant picker, the exit1stops (run in a child
pwshunderSilentlyContinue), process-only service principal and managed identity sign-ins (thenext run without
-Appid/-UseManagedIdentitydoes not reuse them), and the reconnect before metrics and consumption:once per run, on the run's tenant, a silent switch back when possible, no second prompt, no prompt without a console.
Tests/SignInRules.Tests.ps1: each case end to end in a childpwshunderSilentlyContinue, for local runs and forCloud Shell (through
CheckPowerShell): service principal or managed identity sign-in that throws, or leaves the cacheduser in the context, while a user is cached -> exit
1, nothing listed; Cloud Shell cached, stale, stale with-DeviceLogin, tenant mismatch, service principal, managed identity; silent switch to-TenantID; context left on anothertenant -> exit
1; domain-TenantID; Lighthouse tenant in the picker (TenantIddiffers fromHomeTenantId); pickerout of range or not a number twice -> exit
1; empty subscription list -> exit1; no console -> exit1without abrowser,
-DeviceLoginallowed.Tests/WrapperSignIn.Tests.ps1: the wrapper's sign-in check.Tests/TenantSubscriptions.Tests.ps1:Get-AzSubscription -TenantId, delegated and duplicate subscriptions.Tests/AzGraphQueryPaging.Tests.ps1: canned REST pages with 0, 1 and over 1000 rows, skip tokens, batches of 1000subscriptions, the empty-key sentinel and its collision with a real
_rda_emptykeykey (also after lowercasing),invariant lowercasing.
Tests/SetupStop.Tests.ps1: the real script in a childpwsh: missing module, module that does not load, low disk andunwritable output folder each exit
1with no Azure call; a control run with everything present reaches the sign-in.Tests/NoAzCli.Tests.ps1: a guard over the syntax tree of every script the tool runs: noazcall, noSearch-AzGraph(as a call or in printed advice), and every
Set-AzContextkeeps-Scope Process.Tests/AzGraphQueryRetry.Tests.ps1is rewritten for the REST path: status-code classification,Retry-After, retryexhaustion under
SilentlyContinue, and a parse error that quotes at most 500 characters (none under-Obfuscate).Full suite:
main269 passed, 162 failed, 22 skipped; this branch 673 passed, 162 failed, 22 skipped. The same 162 fail onboth: the 7 files that need a
ResourcesReport_*.zipfixture. PSScriptAnalyzer with the repository settings reports nofindings on the changed files.
Not tested against Azure: real token acquisition,
-Scope Processbehaviour across runspaces, Resource Graph's livepaging and throttling, the
Account.Typevalues a live context reports after a service principal (ServicePrincipal) ormanaged identity (
ManagedService) sign-in, and resolving a domain-TenantIDthrough theTenantIdofGet-AzAccessToken. The tests use canned answers.Open PRs affected
Functions/Common.Functions.ps1,README.md); Carry earlier reports into the -Resume bundle #48, Retry metrics or consumption a run left incomplete #61 and Keep the resume state while -ResumeFailedOnly leaves a subscription not collected #62(
Functions/RunAllSubscriptions.Functions.ps1, where the Azure CLI helpers are removed); Exit 2 from a direct run that wrote no report #52 and Stop a direct run when Resource Graph discovery fails #59(
ResourceInventory.ps1).azneed those fakes converted to Az PowerShell orInvoke-AzRestMethodstand-ins once this lands.Tests/NoAzCli.Tests.ps1fails any open PR that adds anazcall.Update
This update adds fixes found while testing the Az PowerShell path end to end. No inventory, consumption or metrics field,
column, type or file name changes, and masked ids keep their shape.
browser that no one can see. A clean wrapper run ends with exit 0, and the exit code is cleared before each
subscription.
instead of the first one on the module path, and names any Az submodule that pins an older Az.Accounts, with the update
to run first. The parallel stream worker asks for the same minimum.
id changes case between reads (a VM that is starting or stopping) is not read twice or skipped. AVD session hosts are
read from the run's own subscription and resource group only.
lists each failed subscription by name and id. With -ParallelStreams, each stream summary is read by one strict reader:
it must belong to this run and hold exactly one row for each subscription the stream ran. A missing or unreadable
summary is reported as "not confirmed", never as success, and every successful subscription must have its own report
zip on disk. MainSummary.html shows such a stream too.
(so a folder name with [ or ] works). When it cannot be written, the per-stream state and the summary-only rows are
kept in files the next run reads at its start, and the console says which files were kept and why.
ResourceInventory.ps1without-SubscriptionIDcollectsonly subscriptions whose state is
Enabled. When the tenant lists none, or none that is Enabled, or does not list the-SubscriptionIDgiven, the run stops with exit 1 and says what to check, instead of writing an empty report.-ResourceGroupwithout-SubscriptionIDis refused with exit 1 before sign-in, and-ResourceGroupis lower-cased withinvariant rules. An
-OutputDirectorythat cannot be found or made gives exit 1. PowerShell 7 is checked first, on everyplatform, before any module or sign-in step: an older PowerShell exits 1.
means and what it can hide.
Tested: full Pester suite (no new failure against the previous head), PSScriptAnalyzer per file (no new finding), and
live runs before and after, plain and with -Obfuscate, comparing inventory, consumption, metrics and their links. Not run
live against
main(main signs in through the Azure CLI, which the test host does not have), and not run on Windows.