首页 > 解决方案 > Powershell读取文件夹下的文件名并读取每个文件内容以创建菜单项

问题描述

我有一个名为 c:\mycommands 的文件夹,该文件夹下的文件是多个文件,例如: command1.txt command2.txt command3.txt

每个文件只有一行,如下所示:在文件 command1.txt 中:
echo "this is command1"

在文件 command2.txt" 回声 "这是 command2"

等等

我想将文件名及其内容读取到数组/变量对中,以构建动态菜单。

所以理论上,我将来需要做的就是将文件放入文件夹中,程序会将其作为菜单选项动态包含在内。(或删除文件以使其不显示在菜单选项中。

解决这个问题的最佳方法是什么?也许是一个带有get-content的do while循环到一个数组中?任何投入将不胜感激。我真的在尝试限制或避免菜单维护,但宁愿动态创建菜单

标签: arrayspowershellmenuswitch-statement

解决方案


以下是相同基本思想的三种变体,具体取决于您需要什么样的输出。

# Storing output in a hash table (key/value pairs)
$resultHash = @{}
Get-ChildItem -Path C:\mycommands -File |
    ForEach-Object {$resultHash.Add($_.Name, (Get-Content -Path $_.FullName))}


# Storing output in an array of psobjects
$resultArray = @()
Get-ChildItem -Path C:\mycommands -File | 
    ForEach-Object {
                        $resultArray += (New-Object -TypeName psobject -Property @{"NameOfFile"=$_.Name; "CommandText"=(Get-Content -Path $_.FullName);})
                    }


# Outputting psobjects to the pipeline
Get-ChildItem -Path C:\mycommands -File | 
    ForEach-Object {
                        New-Object -TypeName psobject -Property @{"NameOfFile"=$_.Name; "CommandText"=(Get-Content -Path $_.FullName);}
                }



# Making a nice menu out of the hash table version
$promptTitle = "My menu"
$promptMessage = "Choose from the options below"
$promptOptions = @()
foreach ($key in $resultHash.Keys)
{
    $promptOptions += New-Object System.Management.Automation.Host.ChoiceDescription $key, $resultHash[$key]
}
$promptResponse = $host.ui.PromptForChoice($promptTitle, $promptMessage, $promptOptions, 0) 

推荐阅读