PowerShell读取队列数脚本空数组错误,求非正则替代方案
Hey there! Let's tackle your problem step by step—first fixing that annoying null array error, then giving you regex-free alternatives as you requested.
That error pops up because Select-String isn't finding a match for your regex pattern, so .Matches ends up being $null. When you try to access .Groups[1] on a null value, PowerShell throws that error. Here's why it might be happening and how to fix it:
- File encoding issues: The
bpdbjobstool might be writing the output file in an encoding thatSelect-Stringdoesn't parse correctly by default. Try explicitly setting the encoding when writing the file:.\bpdbjobs -summary -L | Out-File -Path $Output -Encoding ASCII - Add fault tolerance: Always check if the match was found before trying to access groups. Update your regex-based code to handle missing matches:
$matchResult = Select-String -Pattern "Queued:\s+(\d+)" -Path $Output if ($matchResult) { $Queued = [int]$matchResult.Matches.Groups[1].Value } else { Write-Warning "Couldn't find the 'Queued:' line in the output file" exit 1 # Or handle this error however makes sense for your workflow }
Since you'd rather avoid regex, here are three straightforward methods that work with your file's format:
Method 1: String Splitting (Simple & Reliable)
Read the file, filter for the "Queued:" line, split on the colon, trim whitespace, and convert to an integer:
$queuedLine = Get-Content $Output | Where-Object { $_ -like "Queued:*" } if ($queuedLine) { $Queued = [int]($queuedLine -split ":")[1].Trim() } else { Write-Warning "Queued jobs line not found in output" exit 1 }
Method 2: ConvertFrom-String (Structured Parsing)
If you're using PowerShell 5.1 or newer, ConvertFrom-String lets you define a template to parse the entire summary at once—great if you ever need other job counts later:
# Define a template that matches your summary line format $summaryTemplate = @" Queued: {Queued:int} Waiting-to-Retry: {WaitingToRetry:int} Active: {Active:int} Successful: {Successful:int} Partially Successful: {PartiallySuccessful:int} Failed: {Failed:int} Incomplete: {Incomplete:int} Suspended: {Suspended:int} Total: {Total:int} "@ # Parse the entire file into a structured object $jobSummary = Get-Content $Output -Raw | ConvertFrom-String -TemplateContent $summaryTemplate $Queued = $jobSummary.Queued # Access the Queued count directly
Method 3: Basic Select-String Match + Replace
Use Select-String just to find the line, then strip out the "Queued:" text instead of using regex capture groups:
$queuedLine = Select-String -Pattern "Queued:" -Path $Output | Select-Object -ExpandProperty Line if ($queuedLine) { $Queued = [int]($queuedLine -replace "Queued:", "").Trim() } else { Write-Warning "Queued jobs line missing from output" exit 1 }
Here's your complete script with error handling and the string-splitting method integrated:
$Output = 'D:\alec.data\QueuedJobss.txt' $nbAdminPath = 'D:\program files\veritas\netbackup\bin\admincmd' # Switch to NetBackup admin directory (fail fast if path is invalid) Set-Location -Path $nbAdminPath -ErrorAction Stop # Generate the job summary file with explicit encoding .\bpdbjobs -summary -L | Out-File -Path $Output -Encoding ASCII # Extract Queued job count (regex-free) $queuedLine = Get-Content $Output | Where-Object { $_ -like "Queued:*" } if (-not $queuedLine) { Write-Warning "Failed to locate 'Queued:' entry in the job summary" exit 1 } $Queued = [int]($queuedLine -split ":")[1].Trim() # Send alert if threshold is exceeded if ($Queued -gt 100 ) { $MailArgs = @{ To = 'alb2112@test.com' From = 'netbackup@test.com' Subject = 'Over 100 Queued Jobs!' Attachments = $Output Body = 'Check Environment' SmtpServer = 'smtp.test.com' } Send-MailMessage @MailArgs }
- Adding
-ErrorAction Stopto commands likeSet-Locationhelps catch issues (like a missing NetBackup path) before they cause bigger problems. - Explicitly setting file encoding avoids hidden character mismatches that can break string matching.
- All the regex-free methods are more readable if you're not comfortable with regex, and they work perfectly for your simple, consistent summary format.
内容的提问来源于stack exchange,提问作者AB2112

