Azure-Samples / Azure-Samples/TestDeviceRegConnectivity

Modernization

Aperta
#12 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub
Lingua principale
PowerShell
Stelle
35
Fork
14
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

Had to spar with AI to make two changes to even get the script to run without errors:

**1. The Problem: Legacy Identity Logic**
The script crashes at line 277 because [System.DirectoryServices.AccountManagement.UserPrincipal]::Current is designed for Active Directory Domain Services (AD DS). In an Entra-joined environment, the identity object returned often doesn't fit the expected schema of that specific .NET class, leading to the Unable to cast...GroupPrincipal error.

The Solution: Modernized Test-DeviceRegConnectivity.ps1
Apply these three surgical fixes to the script you provided:

1. Fix Identity Resolution (Line 277)
Replace the block starting at line 277 with logic that gracefully handles Entra ID identities:

```
# Add-Type is kept for compatibility, but we avoid strict casting
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

try {
$CurrentPrincipal = [System.DirectoryServices.AccountManagement.Principal]::Current
$UserUPN = "Unknown"

if ($CurrentPrincipal -and $CurrentPrincipal.StructuralObjectClass -eq "user") {
$UserUPN = whoami /upn
}
} catch {
Write-Log -Message "AccountManagement failed to resolve identity. Falling back to whoami." -Level WARN
$UserUPN = whoami /upn
}

$msg = "User Account: " + (whoami) + ", UPN: " + $UserUPN
Write-Log -Message $msg
```

**2. Robust Task Execution (Line 23)**
The RunPScript function fails because it uses Register-ScheduledJob, which creates a complex overhead. Since you confirmed Register-ScheduledTask works, replace the RunPScript function (Lines 23–32) with this simplified version:

```
Function RunPScript([String] $PSScript){
$GUID = [guid]::NewGuid().Guid
$B64Payload = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($PSScript))
$Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -WindowStyle Hidden -EncodedCommand $B64Payload"
$Principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest

# Register and Start
$Task = Register-ScheduledTask -TaskName $GUID -Action $Action -Principal $Principal -ErrorAction Stop
Start-ScheduledTask -TaskName $GUID -ErrorAction Stop

# Wait for completion
while ((Get-ScheduledTask -TaskName $GUID).State -ne 'Ready') { Start-Sleep -Milliseconds 200 }

# Clean up
Unregister-ScheduledTask -TaskName $GUID -Confirm:$false
return "Task Executed" # Note: This script architecture makes capturing STDOUT difficult without a temp file.
}
```

With the changes, the test ran as it should

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.