在Powershell中根据变量创建显示菜单 [英] Create show-menu in powershell depending on variables

查看:322
本文介绍了在Powershell中根据变量创建显示菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个带有显示菜单的菜单,该菜单取决于计算机上显示的内容.

I want to create a menu with show-menu that will depend on what is present on the computer.

我想在菜单中列出c:\ users \上可用的用户名(基于文件夹名称).

I want to list in the menu usernames available on c:\users\ (based on the folders names).

例如: 在c:\ users中 没有命名的文件夹:

For example : in c:\users there is folder nammed :

homer.simpson
lisa.simpson
bart.simpson

并带有显示菜单,要求用户通过为homer.simpson键入1或为lisa.simpson等键入2来选择其中之一.

and with show-menu ask the user to choose one of them by typing 1 for homer.simpson 2 for lisa.simpson etc ..

我该怎么办?

提前谢谢!

代码

$users = Get-ChildItem "$env:SystemDrive\Users"| ForEach-Object { $_.Name }

foreach ($user in $user)   {

$user
$num++ 

New-Variable -Name "a$num" -Value $user
#Get-Variable -Name "$user$i" 

}



function Show-Menu
{
     param (
           [string]$Title = 'Please select an user'
     )
     cls
     Write-Host "================ $Title ================"

     Write-Host "1: $a1"
     Write-Host "2: $a2"
     Write-Host "3: $a3"
     Write-Host "Q: $a4"
}


do
{
     Show-Menu
     $input = Read-Host "Please make a selection"
     switch ($input)
     {
           '1' {
                cls
                'You chose option #1'
           } '2' {
                cls
                'You chose option #2'
           } '3' {
                cls
                'You chose option #3'
           } 'q' {
                return
           }
     }
     pause
}
until ($input -eq 'q')

推荐答案

尝试一下(基于

根据注释,使用(Get-ChildItem C:\Users).Name获取用户文件夹名称的列表.然后将它们通过管道传递到ForEach-Object循环,该循环首先将计数器变量$i初始化为1.

Per the comments, uses (Get-ChildItem C:\Users).Name to get the list of user folder names. These are then piped to a ForEach-Object loop which starts by initilizing a counter variable $i as 1.

在循环中,它打印出每个文件的名称(现在表示为$_,它是管道中当前项目的自动变量),并使用计数器变量显示带编号的选项.还将每个数字/名称对放在名为$Menu的哈希表中,当通过Read-Host输入选择内容时,该哈希表将用作查找.

In the loop it prints out the name of each file (now represented as $_ which is the automatic variable for the current item in the pipeline) and uses the counter variable to display the numbered options. It also puts each number/name pair in a hashtable named $Menu which is then used as a lookup when the selection is entered via Read-Host.

所选选项将返回到$UserSelection变量.

The selected option is returned to the $UserSelection variable.

这篇关于在Powershell中根据变量创建显示菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆