You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell函数变量传递异常求助:User-Search输出为空

Fixing Your PowerShell User Search Script

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:

  1. Rename all instances of $input to a custom name that doesn’t clash with PowerShell’s built-ins (I’ll use $searchTerm in the example below).
  2. Fix the pause command: PowerShell doesn’t have a native pause cmdlet—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 $input to $searchTerm: This avoids overriding PowerShell’s automatic $input variable, so your user input is now correctly captured and passed to the function.
  • Replaced pause with Read-Host: Uses PowerShell’s native command to pause the script, which works consistently across all PowerShell environments (unlike relying on the batch pause command 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:57:43