簡體   English   中英

Powershell - 用文本文件制作菜單

[英]Powershell - Make a menu out of text file

在我嘗試學習 Powershell 的冒險中,我正在對我制作的腳本進行擴展。 這個想法是通過將“.iso”文件添加到文件夾中來制作腳本。 它將在菜單中使用該內容,以便我以后可以使用它為 Hyper-V 中的 WM 選擇一個iso文件

這是我如何首先獲取內容的版本

Get-ChildItem -Path C:\iso/*.iso -Name > C:\iso/nummer-temp.txt
Add-Content -Path C:\iso/nummer.txt ""
Get-Content -Path C:\iso/nummer-temp.txt | Add-Content -Path C:\iso/nummer.txt

運行此代碼時,它將發送我想要的輸出。 但我的問題是如何在菜單中使用此輸出?

這是在 powershell 中執行此操作的最佳實踐方法:

#lets say your .txt files gets this list after running get-content



$my_isos = $('win7.iso','win8.iso','win10.iso')

$user_choice = $my_isos | Out-GridView -Title 'Select the ISO File you want'  -PassThru

#waiting till you choose the item you want from the grid view
Write-Host "$user_choice is going to be the VM"

我不會像我在評論中提到的那樣嘗試使用 System.windows.forms 實用程序來實現它,除非您想呈現更“好看”的表單。

如果您不想使用圖形菜單,而是使用控制台菜單,則可以使用以下功能:

function Show-Menu {
    Param(
        [Parameter(Position=0, Mandatory=$True)]
        [string[]]$MenuItems,
        [string] $Title
    )

    $header = $null
    if (![string]::IsNullOrWhiteSpace($Title)) {
        $len = [math]::Max(($MenuItems | Measure-Object -Maximum -Property Length).Maximum, $Title.Length)
        $header = '{0}{1}{2}' -f $Title, [Environment]::NewLine, ('-' * $len)
    }

    # possible choices: digits 1 to 9, characters A to Z
    $choices = (49..57) + (65..90) | ForEach-Object { [char]$_ }
    $i = 0
    $items = ($MenuItems | ForEach-Object { '{0}  {1}' -f $choices[$i++], $_ }) -join [Environment]::NewLine

    # display the menu and return the chosen option
    while ($true) {
        cls
        if ($header) { Write-Host $header -ForegroundColor Yellow }
        Write-Host $items
        Write-Host

        $answer = (Read-Host -Prompt 'Please make your choice').ToUpper()
        $index  = $choices.IndexOf($answer[0])

        if ($index -ge 0 -and $index -lt $MenuItems.Count) {
            return $MenuItems[$index]
        }
        else {
            Write-Warning "Invalid choice.. Please try again."
            Start-Sleep -Seconds 2
        }
    }
}

有了它,你稱之為:

# get a list if iso files (file names for the menu and full path names for later handling)
$isoFiles = Get-ChildItem -Path 'D:\IsoFiles' -Filter '*.iso' -File | Select-Object Name, FullName
$selected = Show-Menu -MenuItems $isoFiles.Name -Title 'Please select the ISO file to use'
# get the full path name for the chosen file from the $isoFiles array
$isoToUse = ($isoFiles | Where-Object { $_.Name -eq $selected }).FullName

Write-Host "`r`nYou have selected file '$isoToUse'"

例子:

 Please select the ISO file to use --------------------------------- 1 Win10.iso 2 Win7.iso 3 Win8.iso Please make your choice: 3 You have selected file 'D:\\IsoFiles\\Win8.iso'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM