Reputation: 67
I've a folder called c:\mycommands files under this folder are multiple files like: command1.txt command2.txt command3.txt
each file has one line only, like this:
in file command1.txt:
echo "this is command1"
in file command2.txt" echo "this is command2"
and so on
I want to read the filename and it's content into an array/variable pair in order to build a dynamic menu.
so theoretically, all I would need to do in the future is to, drop a file into the folder and program will include it as menu option dynamically. (or remove the file to have it not show up in menu option.
What's the best way to approach this? maybe a do while loop with get-content into an array? Any input would be greatly appreciated. I'm really trying limit or avoid menu maintenance but would rather have the menu bre created dynamically
Upvotes: 1
Views: 4192
Reputation: 76
Here are three variations on the same basic idea, depending on what kind of output you need.
# 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)
Upvotes: 4
Reputation: 394
If I am understanding what you want correctly, this might be able to accomplish it for you.
If will gather a list of all the files in a folder, then get the content from each one and add them to an Array one by one.
[System.Collections.ArrayList]$Files = @(Get-ChildItem "C:\Logs\" |
Where-Object {$_.PSIsContainer -eq $false} |
Select-Object FullName)
[System.Collections.ArrayList]$List_Of_Commands = @()
foreach ($File in $Files) {
[System.Collections.ArrayList]$File_Contents = @(Get-Content $File.FullName)
foreach ($Content in $File_Contents) {
$Array_Object = [PSCustomObject]@{
'Command' = $Content
}
$List_Of_Commands.Add($Array_Object) | Out-Null
}
}
$List_Of_Commands
Upvotes: 0