PowerShell脚本路径数量输入校验逻辑修复求助
Let's resolve the input validation issue in your script. The core problem with your original line 4 check is that it doesn't reliably validate if the input is a positive integer—using -as for type conversion has quirks that lead to false positives (like treating valid integers as doubles) and false negatives (non-numeric strings get converted to 0, which triggers the error branch incorrectly).
Instead, we'll use [int]::TryParse()—a robust method to verify if input is a valid integer, paired with a check to ensure it's greater than 0. Here's the fully fixed script with clean, reliable validation:
Clear-Host Get-Date # Reusable function to validate positive integer input function Get-ValidPathCount { param( [string]$PromptText ) $inputValue = Read-Host $PromptText $parsedNumber = 0 # Check if input is a valid integer AND greater than 0 if ([int]::TryParse($inputValue, [ref]$parsedNumber) -and $parsedNumber -gt 0) { return $parsedNumber } return $null } # First input attempt $pathCount = Get-ValidPathCount "`n `n Enter number of paths" if ($pathCount -eq $null) { Write-Host "Error: Value entered is non-numeric, a float, negative, or 0.`nPlease enter a valid positive integer." -ForegroundColor Black -BackgroundColor Cyan # Second input attempt $retryPathCount = Get-ValidPathCount "`n `n Re-Enter number of paths" if ($retryPathCount -ne $null) { $validCount = $retryPathCount } else { Write-Host "Error: Invalid input again. Please re-run the script." -ForegroundColor Black -BackgroundColor Cyan exit } } else { $validCount = $pathCount } # Proceed to collect paths and retrieve ACLs Write-Host "`n `n \\ServerName\FilePath `n `n Enter paths in the format above (or local paths like C:\Folder)" For($i=1; $i -le $validCount; $i++) { $targetPath = Read-Host "`n `nEnter File path no. $i " Write-Host "`n `n" if (Test-Path -Path $targetPath) { # Removed unnecessary foreach loop (original code was iterating over each character in the path string) Get-Acl -Path $targetPath | Format-List } Else { Write-Host "Error: Path '$targetPath' does not exist" -ForegroundColor Black -BackgroundColor Cyan } } Write-Host "`n `n `n `t `t `t------------------------------------------------------THE END------------------------------------------------------`n"
Key Fixes & Improvements:
- Robust validation with
TryParse: This method only returns$truefor valid integers, avoiding the issues of-asconversion (which turns non-numeric strings into 0, and treats integers as doubles). - Reusable validation function:
Get-ValidPathCounteliminates code duplication between the first and second input attempts, keeping the script clean. - Fixed path iteration bug: Your original
foreach($path in $paths)loop was unnecessary—$pathswas a single string input, so the loop was iterating over each character in the path. We removed this to correctly retrieve the ACL for the target path. - Clarified path format: Updated the example to include both UNC paths and local paths for clarity.
- Cleaner variable names: Renamed variables like
$pathsto$targetPathto make the code more readable and avoid confusion.
How the Validation Works:
[int]::TryParse() takes the input string and a reference variable to store the parsed integer. It returns $true only if the input is a valid integer. We add an extra check to ensure the parsed number is greater than 0, so:
- Non-numeric strings (e.g., "abc") are rejected
- Floats (e.g., "2.5") are rejected
- Negative numbers or 0 are rejected
- Only positive integers (1, 2, 3, etc.) pass validation
内容的提问来源于stack exchange,提问作者Ishan Sharma

