Sao chép và dán tập lệnh mẫu này và sửa đổi khi cần thiết cho môi trường của bạn:
<# . TÓM TẮT Bật tác vụ đã lên lịch Cập nhật Khởi động An toàn.
.DESCRIPTION Tập lệnh này đảm bảo tác vụ đã lập lịch Cập nhật Khởi động Bảo mật của Windows (\Microsoft\Windows\PI\Secure-Boot-Update) được bật. Nếu bị vô hiệu hóa, tính năng này sẽ bật tính năng này. Nếu tác vụ đã bị xóa, nó có thể tạo lại nó.
.PARAMETER Action Hành động cần thực hiện. Giá trị hợp lệ: kiểm tra, bật, tạo - kiểm tra: Chỉ kiểm tra trạng thái nhiệm vụ - bật: (mặc định) Bật tác vụ nếu tắt. Nếu nhiệm vụ bị thiếu, hãy nhắc tạo.- tạo: Tạo tác vụ nếu tác vụ không tồn tại
.PARAMETER ComputerName Tùy chọn. Mảng tên máy tính để kiểm tra/bật tác vụ trên đó.Nếu không được chỉ định, chạy trên máy cục bộ.
.PARAMETER Credential Tùy chọn. Thông tin xác thực để truy nhập máy tính từ xa.
.PARAMETER Quiet Bỏ lời nhắc và tự động trả lời Có. Hữu ích cho tự động hóa.
.EXAMPLE .\Enable-SecureBootTask.ps1 # Bật trạng thái tác vụ trên máy cục bộ
.EXAMPLE bật .\Check-SecureBootScheduledTask.ps1 này # Bật tác vụ nếu tắt. Yêu cầu tạo nếu thiếu.
.EXAMPLE .\Check-SecureBootScheduledTask.ps1 tạo # Tạo tác vụ nếu tác vụ đã bị xóa, sau đó kiểm tra trạng thái tác vụ
.EXAMPLE .\Check-SecureBootScheduledTask.ps1 chọn -ComputerName "PC1", "PC2" # Kiểm tra tác vụ trên máy từ xa
.NOTES Yêu cầu đặc quyền của người quản trị để bật hoặc tạo tác vụ.Đường dẫn Nhiệm vụ: \Microsoft\Windows\PI\Secure-Boot-Update Tác vụ chạy taskhostw.exe mỗi 12 giờ với đặc quyền nâng cao.#>
[CmdletBinding(SupportsShouldProcess)] param( [Parameter(Position=0)] [ValidateSet('check', 'enable', 'create', '')] [string]$Action = 'enable',
[Parameter()] [string[]]$ComputerName,
[Parameter()] [PSCredential]$Credential,
[Parameter()] [Alias('Force', 'Silent')] [switch]$Quiet )
# Convert Action to switches for backward compatibility $Enable = $Action -eq 'enable' $Create = $Action -eq 'create'
# Download URL: https://aka.ms/getsecureboot -> "Deployment and Monitoring Samples" # Lưu ý: Tập lệnh này chạy trên các điểm cuối để bật tác vụ Cập nhật Khởi động An toàn.
$TaskPath = "\Microsoft\Windows\PI\" $TaskName = "Secure-Boot-Update"
function Get-SecureBootTaskStatus { [CmdletBinding()] param( [string]$Computer = $env:COMPUTERNAME )
$result = [PSCustomObject]@{ ComputerName = $Computer TaskExists = $false Thống kê Tác vụ = $null IsEnabled = $false LastRunTime = $null NextRunTime = $null Lỗi = $null }
try { if ($Computer -eq $env:COMPUTERNAME -or $Computer -eq "localhost" -or $Computer -eq ".") { # Sử dụng các schtasks.exe phát hiện nhiệm vụ đáng tin cậy hơn $schtasksOutput = schtasks.exe /Query /TN "$TaskPath$TaskName" /FO CSV 2>&1 if ($LASTEXITCODE -ne 0) { # Không tìm thấy tác vụ không phải là lỗi - chỉ có nghĩa là tác vụ không tồn tại $result. TaskExists = $false trả lại $result } # Phân tích đầu ra CSV $taskData = $schtasksOutput | ConvertFrom-Csv nếu ($taskData) { $result. TaskExists = $true $result. Trạng thái Tác vụ = $taskData.Trạng thái $result. IsEnabled = ($taskData.Status -eq 'Ready' -or $taskData.Status -eq 'Running') # Cố gắng lấy thời gian chạy tiếp theo từ dữ liệu if ($taskData.'Next Run Time' -and $taskData.'Next Run Time' -ne 'N/A') { hãy thử { $result. NextRunTime = [DateTime]::P arse($taskData.'Next Run Time') } bắt { } } } } khác { # Máy tính từ xa - sử Invoke-Command với schtasks $remoteResult = Invoke-Command -ComputerName $Computer -ScriptBlock { param($fullTaskName) $output = schtasks.exe /Query /TN $fullTaskName /FO CSV 2>&1 @{ ExitCode = $LASTEXITCODE Đầu ra = $output } } -ArgumentList "$TaskPath$TaskName" -ErrorAction Stop
if ($remoteResult.ExitCode -ne 0) { # Không tìm thấy tác vụ không phải là lỗi - chỉ có nghĩa là tác vụ không tồn tại $result. TaskExists = $false trả lại $result }
$taskData = $remoteResult.Output | ConvertFrom-Csv if ($taskData) { $result. TaskExists = $true $result. Trạng thái Nhiệm vụ = $taskData.Trạng thái $result. IsEnabled = ($taskData.Status -eq 'Ready' -or $taskData.Status -eq 'Running') } } } bắt { $result. Lỗi = $_. Exception.Message }
return $result }
function New-SecureBootTask { [CmdletBinding(SupportsShouldProcess)] param( [string]$Computer = $env:COMPUTERNAME )
$success = $false $errorMsg = $null
# Task definition - matches the original Windows Secure Boot Update task # Sử dụng ComHandler với lớp SBServicing, chạy dưới dạng LocalSystem $taskXml = @" <?xml version="1.0" encoding="UTF-16"?> <Task version="1.6" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <RegistrationInfo> <ngày>02-02-07T16:39:20</Ngày> <SecurityDescriptor>O:BAG:BAD:P(A;; FA;;; BA)(A;; FA;;; SY)(A;; FRFX;; LS)</SecurityDescriptor> <nguồn>'$(@%SystemRoot%\system32\TpmTasks.dll,-601)</Source> <tác giả>là '$(@%SystemRoot%\system32\TpmTasks.dll,-600)</Author> <mô>là '$(@%SystemRoot%\system32\TpmTasks.dll,-604)</Description> <URI>\Microsoft\Windows\PI\Secure-Boot-Update</URI> </RegistrationInfo> <Hiệu trưởng> <Principal id="LocalSystem"> <UserId>sử dụng S-1-5-18</UserId> </Hiệu trưởng> </Hiệu trưởng > <Cài đặt> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> ><0 StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> ><4 ExecutionTimeLimit>PT1H</ExecutionTimeLimit> ><8 MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <StartWhenAvailable>đúng</StartWhenAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <restartOnIdle>false</RestartOnIdle> </IdleSettings> <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine> </Cài đặt> <Kích> <BootTrigger> <trễ>PT5M/</Delay> <lặp lại> <khoảng thời gian>PT12H</Khoảng thời gian> </Lặp lại> </BootTrigger> </Triggers> <Ngữ cảnh Hành động="LocalSystem"> <ComHandler> <ClassId>{5014B7C8-934E-4262-9816-887FA745A6C4}</ClassId> <liệu mới><! [CDATA[SBServicing]]></Data> </ComHandler> </Hành động> </Nhiệm vụ> " @
try { if ($Computer -eq $env:COMPUTERNAME -or $Computer -eq "localhost" -or $Computer -eq ".") { if ($PSCmdlet.ShouldProcess("$TaskPath$TaskName", "Create scheduled task")) { # Lưu XML để tạm thời tệp và nhập $tempFile = [System.IO.Path]::GetTempFileName() $taskXml | Out-File -FilePath $tempFile -Encoding Unicode -Force $output = schtasks.exe /Create /TN "$TaskPath$TaskName" /XML $tempFile /F 2>&1 Remove-Item $tempFile -Force -ErrorAction SilentlyContinue if ($LASTEXITCODE -eq 0) { $success = $true } người khác { $errorMsg = $output -join " " } } } khác { if ($PSCmdlet.ShouldProcess("$Computer\$TaskPath$TaskName", "Create scheduled task")) { $result = Invoke-Command -ComputerName $Computer -ScriptBlock { param($taskPath, $taskName, $xml) $tempFile = [System.IO.Path]::GetTempFileName() $xml | Out-File -FilePath $tempFile -Encoding Unicode -Force $output = schtasks.exe /Create /TN "$taskPath$taskName" /XML $tempFile /F 2>&1 Remove-Item $tempFile -Force -ErrorAction SilentlyContinue @{ ExitCode = $LASTEXITCODE; Đầu ra = $output } } -ArgumentList $TaskPath, $TaskName, $taskXml -ErrorAction Stop nếu ($result. ExitCode -eq 0) { $success = $true } người khác { $errorMsg = $result. Đầu ra -nối " " } } } } bắt { $errorMsg = $_. Exception.Message }
return @{ Thành công = $success Lỗi = $errorMsg } }
function Enable-SecureBootTask { [CmdletBinding(SupportsShouldProcess)] param( [string]$Computer = $env:COMPUTERNAME )
$success = $false $errorMsg = $null
try { if ($Computer -eq $env:COMPUTERNAME -or $Computer -eq "localhost" -or $Computer -eq ".") { if ($PSCmdlet.ShouldProcess("$TaskPath$TaskName", "Enable scheduled task")) { $output = schtasks.exe /Change /TN "$TaskPath$TaskName" /ENABLE 2>&1 if ($LASTEXITCODE -eq 0) { $success = $true } người khác { $errorMsg = $output -join " " } } } khác { if ($PSCmdlet.ShouldProcess("$Computer\$TaskPath$TaskName", "Enable scheduled task")) { $result = Invoke-Command -ComputerName $Computer -ScriptBlock { param($fullTaskName) $output = schtasks.exe /Thay đổi /TN $fullTaskName /ENABLE 2>&1 @{ ExitCode = $LASTEXITCODE; Đầu ra = $output } } -ArgumentList "$TaskPath$TaskName" -ErrorAction Stop nếu ($result. ExitCode -eq 0) { $success = $true } người khác { $errorMsg = $result. Đầu ra -nối " " } } } } bắt { $errorMsg = $_. Exception.Message }
return @{ Thành công = $success Lỗi = $errorMsg } }
# Main execution Write-Host "" Write-Host "========================================" -ForegroundColor Cyan Write-Host " Secure Boot Update Task Enabler" -ForegroundColor Cyan Write-Host "========================================" -ForegroundColor Cyan Write-Host "" Write-Host "Tác vụ: $TaskPath$TaskName" -ForegroundColor Gray Write-Host ""
# Determine target computers $targets = if ($ComputerName) { $ComputerName } khác { @($env:COMPUTERNAME) }
$results = @()
foreach ($computer in $targets) { Write-Host "Check: $computer" -ForegroundColor Yellow $status = Get-SecureBootTaskStatus -Computer $computer nếu ($status. Lỗi) { Write-Host " Lỗi: $($status. Error)" -ForegroundColor Red } elseif (-not $status. TaskExists) { Write-Host " Tác vụ không tồn tại trên hệ thống này" -ForegroundColor Red # Tạo nếu được yêu cầu hoặc nhắc nếu Bật đã được chỉ định $shouldCreate = $Create if (-not $shouldCreate -and $Enable) { Write-Host "" Write-Host " Tác vụ có thể đã bị xóa." -ForegroundColor Yellow nếu ($Quiet) { Write-Host " Tác vụ tự động tạo (chế độ Yên tĩnh)" -ForegroundColor Cyan $shouldCreate = $true } người khác { $confirm = Read-Host " Bạn có muốn tạo lại tác vụ không? (Y/N)" if ($confirm -eq 'Y' -or $confirm -eq 'y') { $shouldCreate = $true } } } if ($shouldCreate) { Write-Host " Đang tạo tác vụ..." -ForegroundColor Yellow $createResult = New-SecureBootTask -Máy tính $computer if ($createResult.Success) { Write-Host " Tác vụ đã tạo thành công" -ForegroundColor Green # Kiểm tra lại trạng thái $status = Get-SecureBootTaskStatus -Máy tính $computer nếu ($status. TaskExists) { $stateColor = if ($status. IsEnabled) { "Green" } else { "Red" } Write-Host " State: $($status. TaskState)" -ForegroundColor $stateColor } } khác { Write-Host " Không thể tạo: $($createResult.Error)" -ForegroundColor Red } } } khác { $stateColor = if ($status. IsEnabled) { "Green" } else { "Red" } Write-Host " State: $($status. TaskState)" -ForegroundColor $stateColor nếu ($status. LastRunTime -and $status. LastRunTime -ne [DateTime]::MinValue) { Write-Host " Lần chạy cuối: $($status. LastRunTime)" -ForegroundColor Gray } nếu ($status. NextRunTime -and $status. NextRunTime -ne [DateTime]::MinValue) { Write-Host " Next Run: $($status. NextRunTime)" -ForegroundColor Gray }
# Enable if requested and currently disabled if ($Enable -and -not $status. IsEnabled) { Write-Host " Cho phép tác vụ..." -ForegroundColor Yellow $enableResult = Enable-SecureBootTask -Máy $computer if ($enableResult.Success) { Write-Host " Tác vụ được kích hoạt thành công" -ForegroundColor Green # Kiểm tra lại trạng thái $status = Get-SecureBootTaskStatus -Máy $computer } khác { Write-Host " Không thể bật: $($enableResult.Error)" -ForegroundColor Red } } elseif ($Enable -and $status. IsEnabled) { Write-Host " Tác vụ đã được bật" -ForegroundColor Green } } $results += $status Write-Host "" }
# Summary Write-Host "========================================" -ForegroundColor Cyan Write-Host "Tóm tắt" -ForegroundColor Cyan Write-Host "========================================" -ForegroundColor Cyan
$enabled = ($results | Where-Object { $_.IsEnabled }).Count $disabled = ($results | Where-Object { $_. TaskExists -and -not $_. IsEnabled }). Đếm $notFound = ($results | Where-Object { -not $_. TaskExists }). Đếm $errors = ($results | Where-Object { $_. Lỗi }). Đếm
Write-Host "Total Checked: $($results.Count)" Write-Host "Enabled: $enabled" -ForegroundColor Green if ($disabled -gt 0) { Write-Host "Disabled: $disabled" -ForegroundColor Red } if ($notFound -gt 0) { Write-Host "Not Found: $notFound" -ForegroundColor Yellow } if ($errors -gt 0) { Write-Host "Errors: $errors" -ForegroundColor Red }
# Return results for pipeline $results