C:\Scripts\UserLogonAudit_B.ps1 === Diagnostyka skryptu logowania === BŁĄD: Zmienna…
- User
C:\Scripts\UserLogonAudit_B.ps1 === Diagnostyka skryptu logowania === BŁĄD: Zmienna $logFile nie jest zdefiniowana!
- Assistant
Wygląda na to, że w Twoim skrypcie brakuje definicji zmiennej
$logFile, co powoduje błąd na samym początku. W oryginalnym kodzie, który podałeś na początku, zmienna ta jest zdefiniowana w sekcji "Konfiguracja i Inicjalizacja Zmiennych Globalnych". Prawdopodobnie w plikuC:\Scripts\UserLogonAudit_B.ps1ta część nie została uwzględniona lub jest problem z zakresem zmiennych.Analiza błędu:
- Błąd: "BŁĄD: Zmienna $logFile nie jest zdefiniowana!" wynika z linii, którą dodałem w poprawionej wersji:
if (-not $logFile) { Write-Host "BŁĄD: Zmienna `$logFile nie jest zdefiniowana!" -ForegroundColor Red exit 1 } - To jest celowe sprawdzenie, aby zapobiec dalszemu wykonywaniu skryptu, jeśli zmienna nie istnieje. Jeśli
$logFilenie jest zdefiniowana na górze skryptu, skrypt się zatrzyma.
Rozwiązanie:
-
Dodaj definicję zmiennych globalnych na początku skryptu. Upewnij się, że sekcja z początkowego kodu jest włączona. Powinna wyglądać tak:
$logFile = "C:\Logs\LoginMonitor.log" $throttleFile = "C:\Logs\LoginThrottleData.json" $allowedLogonTypes = @(2, 10, 11) -
Oto pełna, poprawiona wersja skryptu: Poniżej podaję kompletny skrypt, łączący oryginalną konfigurację z poprawkami, które wcześniej zaproponowałem. Upewnij się, że cały kod jest w jednym pliku (
C:\Scripts\UserLogonAudit_B.ps1).#region --- Konfiguracja i Inicjalizacja Zmiennych Globalnych --- $logFile = "C:\Logs\LoginMonitor.log" $throttleFile = "C:\Logs\LoginThrottleData.json" $allowedLogonTypes = @(2, 10, 11) # Inicjalizacja zmiennej do przechowywania danych throttlingu $data = @{} if (Test-Path $throttleFile) { try { $fileContent = Get-Content $throttleFile -Raw -Encoding UTF8 -ErrorAction Stop if ($fileContent -and $fileContent -ne "") { $data = $fileContent | ConvertFrom-Json -ErrorAction Stop Write-Host "✓ Wczytano dane throttlingu z: $throttleFile" -ForegroundColor Cyan } else { $data = @{} Write-Host "Plik throttlingu jest pusty. Inicjalizuję pusty słownik." -ForegroundColor Yellow } } catch { Write-Host "BŁĄD: Nie można wczytać pliku throttlingu ($throttleFile). Inicjalizuję pusty." -ForegroundColor Red Write-Host "Szczegóły błędu: $($_.Exception.Message)" -ForegroundColor Red $data = @{} } } else { Write-Host "Plik throttlingu ($throttleFile) nie istnieje. Inicjalizuję pusty." -ForegroundColor Cyan } #endregion #region --- Definicje Funkcji --- function GetLogonTypeName { param ([int]$LogonType) switch ($LogonType) { 2 { "Interactive" } 3 { "Network" } 4 { "Batch" } 5 { "Service" } 7 { "Unlock" } 8 { "NetworkCleartext" } 9 { "NewCredentials" } 10 { "RemoteInteractive" } 11 { "CachedInteractive" } default { "Unknown ($LogonType)" } } } function CanProcess { param ( [string]$key, [int]$throttleIntervalMinutes = 5 ) $currentTime = (Get-Date).ToFileTimeUtc() if (-not $script:data.ContainsKey($key)) { $script:data[$key] = $currentTime return $true } $lastProcessTime = $script:data[$key] $timeDifference = ([datetime]::FromFileTimeUtc($currentTime) - [datetime]::FromFileTimeUtc($lastProcessTime)).TotalMinutes if ($timeDifference -ge $throttleIntervalMinutes) { $script:data[$key] = $currentTime return $true } else { return $false } } #endregion # Dodaj na początku skryptu Write-Host "=== Diagnostyka skryptu logowania ===" -ForegroundColor Green # Sprawdź czy zmienne globalne są zdefiniowane if (-not $logFile) { Write-Host "BŁĄD: Zmienna `$logFile nie jest zdefiniowana!" -ForegroundColor Red exit 1 } if (-not $allowedLogonTypes) { Write-Host "BŁĄD: Zmienna `$allowedLogonTypes nie jest zdefiniowana!" -ForegroundColor Red exit 1 } # 1. Sprawdź czy katalog istnieje $logDir = Split-Path $logFile -Parent if (-not (Test-Path $logDir)) { Write-Host "BŁĄD: Katalog $logDir nie istnieje!" -ForegroundColor Red try { New-Item -Path $logDir -ItemType Directory -Force | Out-Null Write-Host "Utworzono katalog: $logDir" -ForegroundColor Yellow } catch { Write-Host "BŁĄD: Nie można utworzyć katalogu: $($_.Exception.Message)" -ForegroundColor Red exit 1 } } # 2. Test uprawnień do zapisu try { "Test" | Out-File -FilePath $logFile -Append -Encoding UTF8 Write-Host "✓ Uprawnienia do zapisu: OK" -ForegroundColor Green } catch { Write-Host "BŁĄD: Brak uprawnień do zapisu w $logFile" -ForegroundColor Red Write-Host "Błąd: $($_.Exception.Message)" -ForegroundColor Red exit 1 } # 3. Sprawdź zdarzenia PRZED filtrowaniem try { $allEvents = Get-WinEvent -FilterHashtable @{ LogName = 'Security' ID = 4624 StartTime = (Get-Date).AddMinutes(-5) } -ErrorAction Stop Write-Host "✓ Znaleziono $($allEvents.Count) zdarzeń logowania z ostatnich 5 minut" -ForegroundColor Green } catch { Write-Host "BŁĄD: Nie można pobrać zdarzeń: $($_.Exception.Message)" -ForegroundColor Red exit 1 } # 4. Inicjalizacja liczników i zmiennych $processedCount = 0 $skippedReasons = @{ 'SamePID' = 0 'WrongType' = 0 'SystemUser' = 0 'Throttled' = 0 } # Pobierz zdarzenia z wykluczeniem tych generowanych przez ten skrypt $currentPID = $PID Write-Host "Bieżący PID procesu: $currentPID" -ForegroundColor Cyan try { $logonEvents = Get-WinEvent -FilterHashtable @{ LogName = 'Security' ID = 4624 StartTime = (Get-Date).AddMinutes(-5) } -ErrorAction Stop | Where-Object { $xml = [xml]$_.ToXml() $processId = $xml.Event.System.Execution.ProcessID if ($processId -eq $currentPID) { $skippedReasons['SamePID']++ return $false } return $true } Write-Host "Po filtrowaniu PID: $($logonEvents.Count) zdarzeń" -ForegroundColor Cyan } catch { Write-Host "BŁĄD: Problem z pobieraniem/filtrowaniem zdarzeń: $($_.Exception.Message)" -ForegroundColor Red exit 1 } foreach ($event in $logonEvents) { try { $user = $event.Properties[5].Value $domain = $event.Properties[6].Value $type = [int]$event.Properties[8].Value $workstation = $event.Properties[11].Value $ipAddress = $event.Properties[18].Value Write-Host "Przetwarzam: $domain\$user, typ: $type" -ForegroundColor Gray if ($type -notin $allowedLogonTypes) { $skippedReasons['WrongType']++ continue } if (-not $user -or $user -eq "-" -or $user -match "^(SYSTEM|UMFD|LOCAL SERVICE|NETWORK SERVICE|\$$)") { $skippedReasons['SystemUser']++ continue } $timestamp = $event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss") $desc = GetLogonTypeName $type if (-not (CanProcess "$user-$type")) { $skippedReasons['Throttled']++ Write-Host " → Pominięto (throttling): $user-$type" -ForegroundColor Yellow continue } # Zapisz do pliku $logLine = "$timestamp | User: $domain\$user | Type: $desc | Workstation: $workstation | IP: $ipAddress" Write-Host " → ZAPISUJĘ: $logLine" -ForegroundColor Green Add-Content -Path $logFile -Value $logLine -Encoding UTF8 $processedCount++ } catch { Write-Host "BŁĄD: Problem z przetwarzaniem zdarzenia: $($_.Exception.Message)" -ForegroundColor Red continue } } # Podsumowanie Write-Host "`n=== PODSUMOWANIE ===" -ForegroundColor Green Write-Host "Zapisano do logu: $processedCount wpisów" -ForegroundColor Green Write-Host "Powody pominięcia:" -ForegroundColor Yellow $skippedReasons.GetEnumerator() | ForEach-Object { Write-Host " $($_.Key): $($_.Value)" -ForegroundColor Yellow } # Zapis throttlingu try { $script:data | ConvertTo-Json | Set-Content $throttleFile -Force -Encoding UTF8 Write-Host "✓ Zapisano dane throttlingu do: $throttleFile" -ForegroundColor Cyan } catch { Write-Host "BŁĄD: Nie można zapisać pliku throttlingu: $($_.Exception.Message)" -ForegroundColor Red }
Jak to naprawić:
- Kopiuj i wklej cały kod: Zapisz go do pliku
C:\Scripts\UserLogonAudit_B.ps1. - Uruchom skrypt ponownie: Otwórz PowerShell jako administrator i wykonaj:
C:\Scripts\UserLogonAudit_B.ps1. - Sprawdź środowisko: Upewnij się, że skrypt jest uruchamiany w kontekście, gdzie zmienne globalne są dostępne (np. nie w funkcji, tylko w głównym bloku skryptu).
Jeśli błąd nadal występuje, podaj więcej szczegółów, np. pełny output błędu lub jak uruchamiasz skrypt. Możemy to dalej debugować! 😊
- Błąd: "BŁĄD: Zmienna $logFile nie jest zdefiniowana!" wynika z linii, którą dodałem w poprawionej wersji:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.