Skip to content

Update win-dumpconfigurator.ps1#120

Open
anmocanu wants to merge 9 commits into
Azure:mainfrom
anmocanu:patch-4
Open

Update win-dumpconfigurator.ps1#120
anmocanu wants to merge 9 commits into
Azure:mainfrom
anmocanu:patch-4

Conversation

@anmocanu

Copy link
Copy Markdown
Contributor

.VERSION
    v1.2: [May 2026] - Updated script (current)
                       - Filtered non-actionable kdbgctrl noise from user-facing output.
                       - Added explicit before/after human-readable dump configuration logging.
                       - Added strict post-apply verification and status failure on validation mismatch.
    v1.1: [May 2026] - Updated script
                       - Added intelligent dump placement for Azure temporary storage scenarios.
                       - Added optional pagefile relocation from D: to C: for dump reliability.
                       - Added WMI-based live pagefile auditing and no-reboot workflow.
    v1.0: Initial commit. First working version of the script.
@anmocanu

Copy link
Copy Markdown
Contributor Author

This PR also addresses #121 apart from the Tooling WI.

anmocanu added 3 commits May 27, 2026 11:31
Comment out DumpType and MovePagefile variables for testing.
    v1.2: [May 2026] - Updated script (current)
                       - Added Michael.Smith@microsoft.com as co-author (v1.0 creator)
                       - Changed log file location to $env:PUBLIC\Desktop for uniformity with other scripts
                       - Made automatic reboot configuration optional via -ConfigureAutomaticReboot parameter
                       - Filtered non-actionable kdbgctrl noise from user-facing output.
                       - Added explicit before/after human-readable dump configuration logging.
                       - Added strict post-apply verification and status failure on validation mismatch.
    v1.1: [May 2026] - Updated script
                       - Added intelligent dump placement for Azure temporary storage scenarios.
                       - Added optional pagefile relocation from D: to C: for dump reliability.
                       - Added WMI-based live pagefile auditing and no-reboot workflow.
    v1.0: Initial commit. First working version of the script.
Script now fails if dump type is invalid. DDF location is now changed correctly.
@EdwinBernal1 EdwinBernal1 self-requested a review June 16, 2026 13:22

@EdwinBernal1 EdwinBernal1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issues Found

🔴 Bug: [switch]$OneDump in Param block conflicts with string comparison

Param(
    [switch]$OneDump,
    ...
)

Later:

if ($OneDump -eq 'true') { ... }

A [switch] parameter is a [bool] — its values are $true/$false, not the string 'true'. When passed via az vm repair run --run-on-repair --parameters OneDump=true, the parameter binding may or may not work correctly depending on how Custom Script Extension passes parameters. The PR comment mentions this was changed for CLI compatibility, but the Param block still declares it as [switch].

Fix: Change [switch]$OneDump to [string]$OneDump = 'false' to match the string comparison pattern. Or use [bool] with proper PowerShell $true/$false handling.

🟡 Concern: Get-WmiObject deprecated in PowerShell 7+

$PagefileSettings = Get-WmiObject -Class Win32_PageFileSetting
$PagefileUsages = Get-WmiObject -Class Win32_PageFileUsage

Get-WmiObject was removed in PowerShell 7.x. While Azure repair VMs currently run Windows PowerShell 5.1, future Azure images may ship with PowerShell 7. Use Get-CimInstance as a drop-in replacement:

$PagefileSettings = Get-CimInstance -ClassName Win32_PageFileSetting

🟡 Concern: Hardcoded D: as temp drive

if (Test-Path "D:\") {
    $TempDriveExists = $true
    $DumpFile = "D:\DedicatedDump.sys"
}

Azure temp drive is usually D: but not always. On some SKUs or configurations (especially VMs with data disks), the temp drive may be E: or another letter. The script should detect the Azure temp drive dynamically, e.g., by checking for the INTELPOD volume label or reading the ResourceDisk.MountPoint from waagent.conf. However, this is a pre-existing limitation and common in the repo's scripts, so it's not a blocker.

🟡 Concern: Pagefile relocation is destructive and not reversible

if ($MovePagefile -eq 'true') {
    $pagefile = Get-WmiObject Win32_PageFileSetting -Filter "Name LIKE '%D:%'"
    if ($pagefile) {
        $pagefile.Delete()
        # Creates new pagefile on C:
    }
}

Moving the pagefile from D: to C: is potentially destructive:

  1. If C: runs out of space, the VM may crash
  2. Restoring pagefile to D: requires another script run or manual intervention
  3. No validation of C: free space before relocating

The -MovePagefile parameter is opt-in (good), but should log a warning about C: space requirements and reversibility.

🟡 Concern: Step numbering jumps from 8 to 10

The output steps jump from Step 8 to Step 10, skipping Step 9. This is cosmetic but will confuse support engineers referencing log output.

🟡 Concern: Debug variables left in source

# $TargetDumpType = 1
# $OneDump = 'true'
# $MovePagefile = 'true'
# $ConfigureAutomaticReboot = 'true'

Commented-out debug variables should be removed before merge. They add noise and risk being accidentally uncommitted.

🟡 Concern: Typo in output

Procceding with pagefile relocation

Should be "Proceeding with pagefile relocation".

🟡 Concern: $DumpFile may be unset

If Test-Path "D:\" returns false and no temp drive is found, $DumpFile is set to "" (empty string). Later:

kdbgctrl -sd $TargetDumpType -df $DumpFile

Passing an empty -df value to kdbgctrl may produce unexpected results. Add a guard:

if ([string]::IsNullOrEmpty($DumpFile)) {
    Log-Warning "No valid dump file path could be determined"
    $DumpFile = "$env:SystemRoot\MEMORY.DMP"  # Windows default
}

🟢 Minor: Scope creep — win-ignoreAllFailures.ps1

The PR modifies win-ignoreAllFailures.ps1 (version bump to v1.2). This is unrelated to dump configuration. While harmless, it makes the PR harder to review and should ideally be in a separate commit or PR.


anmocanu added 4 commits July 7, 2026 15:59
Updated version to 1.3 with critical fixes and enhancements, including PowerShell 7 compatibility and improved parameter validation.
based on received feedback: "ID	Category	Blocking condition / what to check	Why it matters	Failure example	Expected fix guidance
SYN-01	Synopsis / documentation	FAIL if script lacks comment-based help with .SYNOPSIS, .DESCRIPTION, .PARAMETER for each parameter, and at least one .EXAMPLE when parameters exist. Static check.	PowerShell comment-based help is the standard way for Get-Help to expose script/function help; .SYNOPSIS, .DESCRIPTION, .PARAMETER, and .EXAMPLE are recognized help keywords.9 Gabriela Limoli noted .SYNOPSIS and metadata improvements as a strength in win-ignoreAllFailures.ps1.10
No help block, or only # .DESCRIPTION.	Add a concise comment-based help block; document every parameter and include at least one safe example.
CQ-01	Code quality best practices	FAIL if new code uses aliases such as %, ?, select, or where, or uses Write-Host / raw Write-Output outside approved logger functions. Static check.	PSScriptAnalyzer flags aliases, Write-Host, deprecated WMI cmdlets, empty catch blocks, and related issues; internal guidance says replace Write-Host / Write-Output with logger functions.111
% { ... }, write-output "done", Write-Host "starting".	Replace aliases with full cmdlet names and route user-visible messages through Log-Output, Log-Info, Log-Warning, Log-Error, or Log-Debug.
CQ-02	PowerShell compatibility	FAIL if new or touched code uses Get-WmiObject / WMI cmdlets when an equivalent CIM cmdlet can be used, unless the script explicitly justifies legacy compatibility. Static check.	Microsoft states WMI cmdlets are deprecated and unavailable in PowerShell 6+, and recommends CIM cmdlets for new development; PSScriptAnalyzer also has a rule to avoid deprecated WMI cmdlets.611
Get-WmiObject Win32_DiskDrive.	Suggest Get-CimInstance -ClassName Win32_DiskDrive or documented CIM-session fallback where needed.
CQ-03	Minimal-change discipline	FAIL if the PR rewrites unrelated script logic or replaces shared helpers instead of using them. Static/diff check.	Internal guidance says not to replace init.ps1 / Get-Disk-Partitions.ps1, to keep shared logic centralized, and “The end script should NOT have drastic changes in the logic.”1
Reimplementing helper logic inline across the script.	Suggest the smallest localized diff and continue importing shared helpers.
DEP-01	Dependencies	FAIL if the script dot-sources helper files without validating their path or if referenced helper names do not exist in the repo context supplied to the bot. Static check.	win-ignoreAllFailures.ps1 review explicitly recommended verifying Get-Disk-Partitions-v2.ps1 exists and adding Test-Path before dot-sourcing helpers.10
. .\src\windows\common\helpers\Foo.ps1 with no Test-Path.	Add a dependency guard that logs a clear error and returns $STATUS_ERROR if missing.
DEP-02	Dependencies	FAIL if Hyper-V / nested-VM logic calls Get-VM or Hyper-V cmdlets without first checking module availability and degrading safely. Static/dynamic pattern.	win-LKGC.ps1, GA_offlinefixer.ps1, sac-enabler.ps1, and win-ignoreAllFailures.ps1 reviews all highlight Hyper-V module guards or graceful degradation as production strengths.451210
Get-VM called unconditionally.	Add Get-Module -ListAvailable -Name Hyper-V guard and log skip/degraded behavior when unavailable.
ERR-01	Error handling	FAIL if the script lacks both success and error returns, or returns inside try / catch before finally cleanup can run. Static check.	Internal guidance requires at least one $STATUS_SUCCESS and $STATUS_ERROR, and says missing status returns break telemetry; win-chkdsk-fs-corruption.ps1 improved by moving return outside try/catch/finally so cleanup happens before exit.113
try { ...; return $STATUS_SUCCESS } finally { reg unload ... }.	Track $scriptStatus, perform cleanup in finally, then return status after cleanup.
ERR-02	Error handling	FAIL if catch blocks are empty, swallow errors, or do not log actionable context. Static check.	PSScriptAnalyzer flags empty catch blocks; internal guidance requires try/catch/finally and logging failures with $STATUS_ERROR.111
catch { }.	Log exception message, affected disk/partition/path, and set failure status.
ERR-03	Error handling / for-each	FAIL if a per-disk or per-partition loop throws on the first item failure when the script could safely continue to other attached disks. Static/dynamic pattern.	win-update-registry.ps1 was blocked partly because per-partition failure stopped all processing, so a customer with multiple disks could get zero repaired if the first failed.2
foreach ($partition in $partitions) { try {...} catch { throw } }.	Log the item failure, mark that item failed, continue to next item, and fail overall only after summary if required.
SAFE-01	Security / safety	FAIL if offline repair logic can process the rescue VM’s own OS drive. Static/dynamic pattern.	win-update-registry.ps1 was blocked for no rescue OS drive exclusion; GA_offlinefixer.ps1 and sac-enabler.ps1 were praised for rescue VM drive protection / OS drive protection.2512
Iterating all volumes and modifying every \Windows\System32\Config\SYSTEM.	Exclude the rescue OS drive using a clear comparison and log which disks were skipped.
SAFE-02	Security / safety	FAIL if registry-changing scripts do not create a backup before modification and do not describe rollback/restore behavior for failure paths. Static/dynamic pattern.	win-update-registry.ps1 was blocked for destructive registry changes with no backup/rollback, while GA_offlinefixer.ps1 was praised for full registry backup and guest-agent folder backup.25
reg add ... /f without backup.	Add registry export/copy backup before writes and restore or preserve backup path on failure.
SAFE-03	Registry safety	FAIL if hive load/unload paths do not validate exit codes, use finally, release handles, and retry unload when needed. Static/dynamic pattern.	win-LKGC.ps1 was praised for hive load exit-code validation, safe reads, typed writes, sleep after load, GC before unload, unload retries, and try/finally cleanup.4
reg load ...; reg add ...; reg unload ... with no validation.	Validate load/unload exit code, use try/finally, [gc]::Collect(), and retry unload with logging.
SAFE-04	BCD validation	FAIL if scripts changing BCD do not validate the BCD path and capture before/after configuration when practical. Static/dynamic pattern.	win-ignoreAllFailure had a high failure-ratio concern around “Unable to find the BCD path,” while Ryan McCallum explicitly liked shell output showing BCD configuration before and after changes.148
bcdedit /store $bcdPath ... with no Test-Path and no before/after capture.	Validate BCD store path, log before/after bcdedit /enum all or equivalent, and fail clearly if path cannot be found.
SAFE-05	Parameter validation	FAIL if user-supplied parameters are silently ignored, normalized to unsafe defaults, or not validated with ValidateSet / explicit validation. Static/dynamic pattern.	win-dumpconfigurator feedback said not to ignore DedicatedDumpFile / DumpFile, to fail invalid DumpType, and to log modified values; invalid fulll should fail instead of defaulting to full.3
Invalid DumpType defaults to full.	Add ValidateSet('active','automatic','full','kernel','mini') or equivalent; fail fast and log accepted parameter values.
DOC-01	Documentation completeness / logging	FAIL if output logs omit changed values, status, or user-actionable context. Static/dynamic pattern.	Internal guidance says logger output is shown to users through vm repair run; dump configurator feedback required modified DDF/DumpFile values in output logs.13
“Success” with no values changed.	Log before/after values, target disk/path, and final CHANGES_APPLIED or equivalent.
FE-01	For-each loop patterns	FAIL if loop body mutates the iterated collection, depends on $_. outside its pipeline scope, or reuses global loop variables across nested loops. Static check.	The legacy sample in AZ REPAIR SCRIPTS shows fragile nested enumeration and $_.-driven disk discovery, and internal guidance favors shared helpers and limited logic changes.11
$disknumber = $_ before a loop; nested ForEach-Object reuses $disk.	Use explicit loop variables, snapshot collections before iteration, and avoid implicit $_. outside the active script block.
FE-02	For-each loop patterns	FAIL if loop processing lacks per-item logging and final summary counts for processed/skipped/failed items. Static/dynamic pattern.	win-LKGC.ps1 was praised for per-disk and overall flags plus final CHANGES_APPLIED=TRUE/FALSE, giving an audit trail.4
Loop completes with only “done.”	Add per-item log entries and a final summary of processed/skipped/failed/changed.
"

What changed against your checklist:

Added help examples for SYN-01
Added two .EXAMPLE entries in the comment-based help at win-dumpconfigurator.ps1:50 and win-dumpconfigurator.ps1:54.
Added dependency guards for DEP-01
Added a validated init dependency path before dot-sourcing at win-dumpconfigurator.ps1:113.
Added a validated tool dependency path before running kdbgctrl at win-dumpconfigurator.ps1:450.
Removed legacy WMI class usage for CQ-02
Replaced the [WMIClass] create flow with New-CimInstance at win-dumpconfigurator.ps1:410.
Tightened parameter intake and normalization for SAFE-05
Changed boolean-like parameter defaults to empty strings so lowercase injected params are not ignored at win-dumpconfigurator.ps1:100.
Added explicit normalization for boolean-like inputs at win-dumpconfigurator.ps1:141.
Added backup/rollback guidance for SAFE-02
Added CrashControl registry backup before writes at win-dumpconfigurator.ps1:284.
Added rollback-path logging in failure flow at win-dumpconfigurator.ps1:532.
Added per-item plus summary loop logging for FE-02
Added pagefile scan summary at win-dumpconfigurator.ps1:331.
Added delete-loop processed/skipped/failed summary at win-dumpconfigurator.ps1:404.
Small quality cleanup
Renamed helper to approved verb style: Get-KdbgctrlOutputSummary at win-dumpconfigurator.ps1:205.
Updated call site accordingly at win-dumpconfigurator.ps1:456.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants