arrays - Powershell读取文件夹下的文件名并读取每个文件内容以创建菜单项
问题描述
我有一个名为 c:\mycommands 的文件夹,该文件夹下的文件是多个文件,例如: command1.txt command2.txt command3.txt
每个文件只有一行,如下所示:在文件 command1.txt 中:
echo "this is command1"
在文件 command2.txt" 回声 "这是 command2"
等等
我想将文件名及其内容读取到数组/变量对中,以构建动态菜单。
所以理论上,我将来需要做的就是将文件放入文件夹中,程序会将其作为菜单选项动态包含在内。(或删除文件以使其不显示在菜单选项中。
解决这个问题的最佳方法是什么?也许是一个带有get-content的do while循环到一个数组中?任何投入将不胜感激。我真的在尝试限制或避免菜单维护,但宁愿动态创建菜单
解决方案
以下是相同基本思想的三种变体,具体取决于您需要什么样的输出。
# 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)
推荐阅读
- reactjs - 获取 Redux 中所有相关方法的完整调用堆栈
- c# - 通过代码创建和执行的 SSIS 包需要在多次运行后重新启动服务
- php - 从 csv 文件读取数据并使用 phpspreadsheet 写入 excel
- jquery - 获取ajax加载元素的值
- node.js - JWS 传输最佳实践
- apache-kafka - Kafka 连接 - SpoolDir 源连接器未显示
- javascript - 将插入符号移到使用环绕内容创建的跨度之外
- python - Python:来自标准输入的多个文本处理
- python - tkinter NameError:未定义名称“表达式”
- c# - 处理 avalonia 位图的正确方法是什么?