如何将哈希表导入PowerShell以匹配现有格式并用于指定代码?
First, let's fix the syntax of your original hashtable—there are a couple missing commas and an incomplete entry that would cause errors. Here's the corrected version with clean formatting (I filled in the cut-off "Scientific soft..." entry with examples; feel free to replace those with your actual tools):
$MenuGroups = @{ "1. Internet & Network tools" = "Microsoft Edge", "Internet Explorer" "2. Microsoft Office" = "Excel 2016", "Outlook 2016", "PowerPoint 2016", "Publisher 2016", "Word 2016" "3. Text, file & programming tools" = "Calculator", "Notepad++" "4. Media tools" = "XBOX", "NONE" "5. Scientific software" = "Matlab", "SPSS" # Swap with your actual tools }
Now, to modularize this so you can tweak menu items without touching your main script, here are two straightforward methods:
Option 1: Dot-Source a Separate .ps1 File
This is the quickest approach for simple edits.
- Create a new file (e.g.,
MenuConfig.ps1) and paste the corrected hashtable into it. Save it in the same folder as your main script. - At the top of your main script, add this line to load the hashtable into your script's scope:
. .\MenuConfig.ps1 # The dot and space are critical—they "dot-source" the file to import variables
From now on, just edit MenuConfig.ps1 whenever you need to update menu groups or items, and your main script will automatically use the new values.
Option 2: Use a PowerShell Data File (.psd1)
This is a more robust choice for configuration data, as it enforces valid syntax and is purpose-built for storing settings.
- Create a new file named
MenuConfig.psd1and paste this formatted content (note the@()array syntax for each group's items):@{ "1. Internet & Network tools" = @("Microsoft Edge", "Internet Explorer") "2. Microsoft Office" = @("Excel 2016", "Outlook 2016", "PowerPoint 2016", "Publisher 2016", "Word 2016") "3. Text, file & programming tools" = @("Calculator", "Notepad++") "4. Media tools" = @("XBOX", "NONE") "5. Scientific software" = @("Matlab", "SPSS") } - In your main script, import the data file like this:
$MenuGroups = Import-PowerShellDataFile -Path .\MenuConfig.psd1
Using the Hashtable in Your Code
Once imported, you can use $MenuGroups exactly as if it was defined directly in your script. For example, to loop through groups and display items for your menu:
foreach ($group in $MenuGroups.GetEnumerator()) { Write-Host "`n* $($group.Key):" foreach ($item in $group.Value) { Write-Host " - $item" } }
This will output your menu structure neatly, ready to integrate into your existing logic.
内容的提问来源于stack exchange,提问作者Powershelling

