powershell - 仅运行选定的命令/行
问题描述
假设我有以下包含几个 powerhsell 命令的 Powershell 脚本
Get-Service -Name BITS
Get-Service -Name WinDefend
Get-Service -name Winmgmt
Get-Service -Name WdNisSvc
我怎样才能让我的脚本像这样询问它会运行 4 个命令中的哪一个
Select which command you would like to run:
1. Get-Service -Name BITS
2. Get-Service -Name WinDefend
3. Get-Service -name Winmgmt
4. Get-Service -Name WdNisSvc
他们根据我的选择将只运行想要的命令
编辑:到目前为止,我现在能够解决问题,但现在的问题是:如何向用户提示这些,以便用户可以选择它们并保存答案,以便我可以在“Write-Host”之后使用它现在我们可以执行 [$输入]””
$input = Read-Host -Prompt 'Select what operation you want to perform'
1. Get-Service -Name BITS
2. Get-Service -Name WinDefend
3. Get-Service -name Winmgmt
4. Get-Service -Name WdNisSvc
if ($input) {
Write-Host "Now we can perform [$input]"
**here should then answer be executed**
} else {
Write-Warning -Message "No input selected"
}
解决方案
您可以创建如下所示的菜单。
如果您有兴趣了解菜单上的应用:
$services = @(
'BITS'
'WinDefend'
'Winmgmt'
'WdNisSvc'
)
$servCount = $services.Count
do
{
# Phrase this correctly so it's clear user should select a Number
'Select a Service you would like to query:'
$services | ForEach-Object -Begin { $i = 1 } -Process {
"$i. $_"; $i++
}
switch -Regex($selection = Read-Host)
{
"^[1-$servCount]{1}$" {
Get-Service $services[$selection-1]
'Press ENTER to continue...'
Read-Host
Clear-Host
break
}
"Q" { break }
Default { Write-Warning 'Invalid Selection!' }
}
}
until($selection -eq 'Q')
推荐阅读
- javascript - React 重新渲染与功能重新评估
- jira - 通过 REST API 发现 Jira 自定义字段
- ios - 是否可以使用 Google Cast SDK 进行屏幕镜像?
- authentication - 新主机迁移后,多供应商 CS-Cart 管理面板访问引发错误
- javascript - 在输入搜索和 onClick 后渲染元素
- python - 计算策略梯度的损失
- r - 逻辑回归误差(glm.fit 中的误差(x = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, : NA/NaN /Inf in 'x') in r
- java - 删除后如何修复recyclerView中的项目重复?
- jenkins - MSTestPublisher 说 Jenkins 中的权限被拒绝
- c# - 建立具有客户端配置文件c#的openvpn连接