首页 > 解决方案 > 如何通过按 Escape 来逃脱读取主机?

问题描述

只是想知道是否可以通过按转义键在 while 循环中转义读取主机。

我试过做一个 do-else 循环,但它只会识别读取主机之外的按钮按下。

这基本上就是我所拥有的

#Import Active Directory Module
Import-Module ActiveDirectory

#Get standard variables
$_Date=Get-Date -Format "MM/dd/yyyy"
$_Server=Read-Host "Enter the domain you want to search"

#Request credentials
$_Creds=Get-Credential

while($true){

    #Requests user input username
    $_Name=Read-Host "Enter account name you wish to disable"

    #rest of code
    }

如果我想更改域,我希望能够逃脱它

标签: powershellpowershell-ise

解决方案


使用Read-Host您无法执行此操作,但您可以考虑使用图形输入对话框而不是在控制台中进行提示。毕竟,Get-Credentialcmdlet 还显示一个 GUI。

如果这是您的选择,可以使用以下方法完成:

function Show-InputBox {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Message, 

        [string]$Title = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.PSCommandPath),

        [string]$defaultText = ''
    )
    Add-Type -AssemblyName 'Microsoft.VisualBasic'
    return [Microsoft.VisualBasic.Interaction]::InputBox($Message, $Title, $defaultText)
}

while($true) {
    $_Name = Show-InputBox "Enter account name you wish to disable"
    if ([string]::IsNullOrWhiteSpace($_Name)) {
        # the box was cancelled, so exit the loop
        break
    }
    # proceed with the rest of the code
}

如果用户按下Esc键、单击Cancel或将输入留空,则可以退出 while 循环,否则继续执行代码。


推荐阅读