当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何在PowerShell中提示输入?

作者:精品下载站 日期:2024-12-14 06:22:11 浏览:15 分类:玩电脑

如何在PowerShell中提示输入?


[玩转系统] 如何在PowerShell中提示输入?

PowerShell 提供了多种方式来提示用户输入以执行不同的操作。这使您可以创建灵活的、可定制的和交互式的脚本,这些脚本可以接受动态运行时配置、参数和选项,而不是硬编码值。在本综合指南中,我们将探讨 PowerShell 中提示用户输入的各种可用方法。无论是从命令行读取输入、显示 GUI 弹出窗口、提供菜单选项还是验证值,PowerShell 都提供了强大的选项来创建用户友好的输入体验。

PowerShell 提示用户输入简介

通过提示用户输入,您可以创建灵活的 PowerShell 脚本,该脚本可以在运行时接受用户的参数、选项和其他值。提示输入的一些常见原因包括:

  • 要求用户输入凭据进行身份验证
  • 从用户那里获取选择以确定脚本流程和逻辑
  • 接受在脚本中使用的文件名、路径和其他输入值
  • 通过提示用户确认值来验证输入
  • 创建交互式菜单为用户提供选项

PowerShell 提供 cmdlet、读取主机、参数和参数、输入框以及其他技术来适当提示用户。通过 PowerShell 提示用户输入,您可以提示用户输入文件路径、用户名、密码以及成功执行脚本所需的其他参数等信息。

使用 PowerShell 提示用户输入的好处

[玩转系统] 如何在PowerShell中提示输入?

使用 PowerShell 提示进行用户输入的主要好处之一是它使脚本更具交互性。您可以提示用户输入,然后使用该输入执行脚本中的某些任务。这可以使您的脚本更加灵活且更易于使用。此外,PowerShell 提示用户输入可以帮助您自动执行某些需要手动干预的任务。这可以节省您的时间并提高组织内的效率。

使用 Read-Host cmdlet 在 PowerShell 中提示用户输入

在 PowerShell 中获取用户输入的最简单方法是通过 Read-Host cmdlet。此 cmdlet 提示用户输入并等待用户键入响应。它可用于收集各种类型的输入,例如字符串、数字和安全字符串。

PowerShell 提示用户输入的基本语法如下:


Read-Host [-Prompt] <String> [-AsSecureString] [-MaskInput] [<CommonParameters>]
  • -Prompt:指定向用户显示的文本提示。该参数是位置参数,无需显式命名即可使用。例如,读取主机“输入您的姓名”。 Read-Host cmdlet 的输出是一个字符串对象。
  • -AsSecureString:指示输入应被视为安全字符串。这对于密码或其他敏感信息很有用,因为输入被屏蔽并存储在 System.Security.SecureString 对象中。
  • MaskInput:此参数指示应屏蔽输入,类似于 GUI 应用程序中的密码字段。它从 PowerShell 7.2 开始可用。

以下是如何使用 Read-Host cmdlet 获取输入的示例。


# Prompt for a string input
$name = Read-Host -Prompt "Enter your name"

#Get the input and store it in $Age variable name - without Prompt parameter
$Age = Read-Host "Please enter your age" 

Write-Host "Hello $Name, welcome to my script!"

该脚本会向用户提示一条消息,然后将用户输入分配给一个变量。输入的内容将显示为个性化消息。

[玩转系统] 如何在PowerShell中提示输入?

当用户输入值并在 Windows PowerShell 控制台中按“Enter”键时,输入的值将作为明文字符串对象存储在变量 $name 中。 PowerShell 将在提示字符串末尾附加一个冒号。

Read-Host 的一些有用参数包括:

  • 提示 - 指定向用户显示的提示文本。如果字符串包含空格,请将其括在引号中。
  • AsSecureString - AsSecureString 参数屏蔽用户输入,例如密码
  • MaskInput - 在输入时将每个字符屏蔽为 *

例如,提示输入密码:


# Prompt for a secure string input (password)
$Password = Read-Host -Prompt "Enter your password" -AsSecureString

此示例提示用户输入密码。输入时,控制台上的字符位置会显示星号 (*),而不是实际输入的内容。

[玩转系统] 如何在PowerShell中提示输入?

得到用户的确认

您还可以使用 Read-Host 提示用户确认操作。例如:


$Confirm = Read-Host -Prompt "Are you sure you want to delete the file (Y/N)"
if ($confirm -eq 'y') {
  # Delete file
} else {
  Write-Host "Deletion cancelled"
}

这会在删除文件之前显示一条提示,要求确认。这将验证输入,并执行适当的代码块。请注意,Read-Host 只能接受 8190 个字符作为用户输入。

使用脚本中的参数提示用户输入

对于更复杂的输入,您可以在运行 PowerShell 脚本时接受参数和参数。参数允许您以命名方式输入值,例如 -Name 或 -Path。

例如,我们可以定义一个名为 install-script.ps1 的 PowerShell 脚本,它接受参数:


param(
  [string]$Name,
  [string]$Path
)

Write-Output "Installing $Name to path $Path"

然后我们可以运行它并传递输入值:


.\install-script.ps1 -Name MyApp -Path C:\Apps

对于提示选项,您可以使用参数集来接受不同的参数输入组合。您还可以接受位置值的参数输入。因此,组合参数和参数可以提供强大的输入提示。更多信息请参见:PowerShell 函数参数

等待用户输入

在某些场景下,您可能需要等待连续的用户输入。您可以通过使用 Read-Host 循环来实现此目的,允许用户多次提供输入,直到他们选择退出。


# Initialize a flag to control the loop
$continue = $true

# Start the loop
while ($continue) {
    $input = Read-Host "Enter some input or type 'Q' to quit"
    
    if ($input -eq "q") {
        # If the user enters 'exit', set the flag to false to exit the loop
        $continue = $false
    } else {
        # Process the user's input (in this example, we just display it)
        Write-Host "You entered: $input"
    }
}

Write-Host "User chose to exit. Script completed."

您可以根据用户的输入或特定要求修改脚本以包含更复杂的逻辑或操作。

验证用户输入

您可以验证用户输入是否符合特定条件或标准。让我们看看如何使用循环来使用输入验证。例如,您想获取用户的年龄参数。


# Promp for user input with validation
Do {
    $Age = Read-Host -Prompt "Please enter your age"
} While ($Age -notmatch '^\d+$')

# Output the entered age
Write-Host "You entered age: $Age"

这将提示您输入有效的号码。

同样,您可以使用 IF 条件来验证用户输入并根据用户输入采取操作。


$userInput = Read-Host "Enter a number between 1 and 10"
if ($userInput -ge 1 -and $userInput -le 10) {
    Write-Host "Valid input: $userInput"
} else {
    Write-Host "Invalid input. Please enter a number between 1 and 10."
}

如果您使用函数参数,则可以使用以下属性验证用户输入:ValidateSet、ValidateRange、ValidatePattern 等。更多信息请参阅:在 PowerShell 中验证函数参数

实现菜单来提示用户输入

要提供交互式菜单选项,您可以在循环内使用 Read-Host 来显示选项并获取菜单选项。例如,创建一个简单的菜单,允许用户执行基本的系统任务,例如检查系统信息、列出目录中的文件以及关闭计算机:


# Define a function to display the system operations menu
function Show-SystemMenu {
    Clear-Host  # Clear the console to keep it clean
    Write-Host "=== System Operations Menu ==="
    Write-Host "1. Display System Information"
    Write-Host "2. List Files in a Directory"
    Write-Host "3. Shut Down Computer"
    Write-Host "4. Exit"
}

# Display the system operations menu initially
Show-SystemMenu

# Start the menu loop
while ($true) {
    $choice = Read-Host "Select an operation (1-4):"
    
    # Validate user input
    if ($choice -match '^[1-4]$') {
        switch ($choice) {
            1 {
                # Display system information
                Write-Host "System Information:"
                Get-ComputerInfo | Format-Table -AutoSize
                Read-Host "Press any key to continue..."
            }
            2 {
                # List files in a directory
                $directory = Read-Host "Enter the directory path:"
                Get-ChildItem -Path $directory
                Read-Host "Press any key to continue..."
            }
            3 {
                # Shut down the computer
                Write-Host "Shutting down the computer..."
                #Stop-Computer -Force
            }
            4 { exit }  # Exit the loop when 'Exit' is selected
        }
    }
    else {
        Write-Host "Invalid input. Please select a valid option (1-4)."
        Start-Sleep -Seconds 2  # Pause for 2 seconds to display the message
    }

    # Redisplay the system operations menu
    Show-SystemMenu
}

这将显示一个菜单,提示选择,并根据使用 switch 语句选择的菜单选项执行不同的代码块。

创建确认弹出窗口和输入框提示

如果您需要一种更加用户友好和交互式的方式来提示输入,可以使用 System.Windows.Forms 命名空间创建弹出输入框。这种方法使您能够为脚本设计图形用户界面 (GUI)。


Add-Type -AssemblyName System.Windows.Forms
$InputBox = [System.Windows.Forms.MessageBox]::Show("Do you want to continue?", "Confirmation", [System.Windows.Forms.MessageBoxButtons]::YesNo)
$InputBox

这是另一张带图标的:


Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$UserInput = [System.Windows.Forms.MessageBox]::Show("Do you want to proceed execution?","Continue script execution" , "YesNo", "Question")

创建图形输入框可以显着增强用户体验,特别是对于非技术用户而言。

[玩转系统] 如何在PowerShell中提示输入?

您还可以使用 Windows 脚本宿主对象来显示弹出提示:


$Prompt = New-Object -ComObject wscript.shell    
$UserInput = $Prompt.popup("Do you want to proceed execution?",0,"Continue script execution",4+32)
If($UserInput -eq 6)
{
    Write-host -f Green "Script Execution Continued..."
}
Else
{
    Write-host -f Yellow "Script Execution Aborted!" 
}

使用输入框提示输入

要提供交互式输入提示,您可以创建一个输入框。例如:


# Prompt the user for input using InputBox
$input = [Microsoft.VisualBasic.Interaction]::InputBox("Please enter your name:", "User Input", "")

# Check if the user provided input
if ([string]::IsNullOrWhiteSpace($input)) {
    Write-Host "User canceled input."
} else {
    Write-Host "You entered: $input"
}

这会向用户显示一个输入弹出窗口。您可以检查输入并根据它继续执行脚本。

[玩转系统] 如何在PowerShell中提示输入?

使用 PowerShell GUI 获取用户输入

虽然 PowerShell 提示用户输入是一项强大的功能,但您可以根据需要使用其他替代方案。其中一种替代方案是 PowerShell 弹出输入。此功能允许您创建提示用户输入的图形用户界面 (GUI)。这是一个例子:


# Load the System.Windows.Forms assembly
Add-Type -AssemblyName System.Windows.Forms

# Create a form object
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Enter the value"
$Form.Size = New-Object System.Drawing.Size(300,200)
$Form.StartPosition = "CenterScreen"

# Create a label to display instructions
$label = New-Object Windows.Forms.Label
$label.Text = "Enter your input:"
$label.Location = New-Object Drawing.Point(20, 20)
$form.Controls.Add($label)

# Create an OK button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Point(100,75)
$Button.Size = New-Object System.Drawing.Size(100,30)
$Button.DialogResult = [Windows.Forms.DialogResult]::OK
$Button.Text = "OK"
$Form.Controls.Add($Button)

# Create a text box for user input
$InputBox = New-Object System.Windows.Forms.TextBox
$InputBox.Location = New-Object System.Drawing.Point(50,50)
$InputBox.Size = New-Object System.Drawing.Size(200,20)
$Form.Controls.Add($InputBox)

# Show the form as a dialog box
$Result = $Form.ShowDialog()

# Check if the OK button was clicked
if ($Result -eq [Windows.Forms.DialogResult]::OK) {
    $userInput = $InputBox.Text
    Write-Host "You entered: $userInput"
}

# Dispose of the form
$form.Dispose()

此示例创建一个 GUI,提示用户输入,然后在控制台中显示输入。

[玩转系统] 如何在PowerShell中提示输入?

有多种资源可帮助您掌握用户输入的 PowerShell 提示。以下是有关用户输入的 Read-Host 提示的官方文档:Read-Host Cmdlet Microsoft Docs

概括

在这份综合指南中,我们介绍了基本的控制台输入、从用户处获取确认、GUI 输入框、参数化脚本以及用于连续用户交互的菜单。通过掌握这些概念和实际示例,您就可以创建交互式且用户友好的 PowerShell 脚本:

  • Read-Host cmdlet 提示输入
  • 接受参数和参数
  • 通过 WinForms 输入框
  • 循环使用 Read-Host 的菜单

使用这些提示技术可以创建能够以友好的方式接受运行时配置和用户输入的脚本。这比硬编码值提供了更大的灵活性,并提高了自动化程度。通过遵循本文中概述的方法,您可以熟练使用此功能并创建更高效、更灵活的脚本。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯