powershell - 如何通过按 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
}
如果我想更改域,我希望能够逃脱它
解决方案
使用Read-Host
您无法执行此操作,但您可以考虑使用图形输入对话框而不是在控制台中进行提示。毕竟,Get-Credential
cmdlet 还显示一个 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 循环,否则继续执行代码。
推荐阅读
- mongodb - 当我添加文档时,MongoDB 游标是否“自动增长”
- javascript - 在纯 JS 或 Angular 中替换字符串 URL 子域
- ruby - 为什么 require_all 在 Sinatra 助手中不起作用?
- vba - Excel VBA 将参数传递给 OLEDBConnection
- r - R - 用两个表格计算百分比
- c++ - uint32_t 指针指向与 uint8_t 指针相同的位置
- azure - 自动缩放在 Azure Kubernetes 服务 (AKS) 中不起作用
- c# - 当我使用 HttpWebRequest C# 重定向到 url 时收到错误请求 (400)
- git - 为什么我收到“错误未能推送一些参考”?
- javascript - 重构异步道具更新