PowerShell函数变量传递异常求助:User-Search输出为空
Hey there, let's figure out why your script isn't capturing and displaying your input correctly—this is a super common gotcha with PowerShell's built-in variables!
The Core Issue: Using $input as a Custom Variable/Parameter
$input is a reserved automatic variable in PowerShell. It’s designed specifically to handle pipeline input, so when you try to use it as your own parameter or variable name, PowerShell overrides it behind the scenes. That’s exactly why your input value is showing up empty.
Step-by-Step Fixes
Here's how to adjust your script to work as expected:
- Rename all instances of
$inputto a custom name that doesn’t clash with PowerShell’s built-ins (I’ll use$searchTermin the example below). - Fix the
pausecommand: PowerShell doesn’t have a nativepausecmdlet—we’ll use PowerShell-native syntax to pause the script instead for better reliability.
Corrected Script
# Rename parameter from $input to $searchTerm to avoid variable conflict function User-Search($searchTerm) { Write-Host "Searching for user: $searchTerm" # PowerShell-native pause: wait for user to press Enter $null = Read-Host "Press Enter to continue" } function Show-Menu { param ( [string]$Title = 'Main Menu' ) cls Write-Host "================ $Title ================" Write-Host " " Write-Host "Specify computer / username" Write-Host " " Write-Host "Q: Press 'Q' to quit." Write-Host " " } do { Show-Menu # Rename variable from $input to $searchTerm $searchTerm = Read-Host "Search" # Pass the renamed variable to the function User-Search -searchTerm $searchTerm } until ($searchTerm -eq 'q')
What Changed?
- Renamed
$inputto$searchTerm: This avoids overriding PowerShell’s automatic$inputvariable, so your user input is now correctly captured and passed to the function. - Replaced
pausewithRead-Host: Uses PowerShell’s native command to pause the script, which works consistently across all PowerShell environments (unlike relying on the batchpausecommand that might fail in some contexts).
Now when you run the script, entering a username or computer name will correctly appear in the "Searching for user:" message, and pressing Q will exit the loop as intended.
内容的提问来源于stack exchange,提问作者FailingFrank

