Azure-Samples / Azure-Samples/TestDeviceRegConnectivity

Modernization

Abierto
#12 0 comentarios 0 reacciones 0 asignados Ver en GitHub
Lenguaje dominante
PowerShell
Estrellas
35
Forks
14
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

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

Guía de contribución

Abrir la guía de contribución

Línea de trabajo

Abre Test-DeviceRegConnectivity.ps1 e inspecciona RunPScript alrededor de las líneas 23–32 y la resolución de identidad alrededor de la línea 277. Ejecuta el script en el entorno Entra-joined para reproducir los fallos y, después, verifica que la ejecución de la tarea programada, la resolución de identidad y la limpieza se completen sin errores.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
powershell
Área
tooling
Tipo de issue
Error
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.