Ralluhb Ralluhb - 4 months ago 14
PowerShell Question

How to output to two columns in Powershell with XML

I have a simple menu to run some tasks, the menu reads variables through an xml config.

At the moment it outputs to screen like this:


  1. App One.

  2. App Two.

  3. App Three.

  4. App Four.



However I would like to output it like this (due to menu getting larger):


  1. App One. 3. App Three.

  2. App Two. 4. App Four.



Can you look at this code and advise how I can implement the above?

[xml]$Config=@"
<?xml version="1.0"?>
<Menu>
<Head>
Dashboard
</Head>
<Actions>
<Id>
<Option>1</Option>
<Description>App One</Description>
</Id>
<Id>
<Option>2</Option>
<Description>App Two</Description>
</Id>
<Id>
<Option>3</Option>
<Description>App Three</Description>
</Id>
<Id>
<Option>4</Option>
<Description>App Four</Description>
</Id>
</Actions>
</Menu>
"@

foreach ($Item in @($Config.Menu.Actions.Id))
{
Write-Host ("{0}.`t{1}." -f $Item.Option,$Item.Description)}


Would I need to use maybe split/regex?

Answer

The following code will add a newline character (`n) to the menu string if the item count is even. Meaning you will have two items on each line of your menu.

$c = 1 
$menu = ""

foreach ($Item in @($Config.Menu.Actions.Id)) {

    $menu += ("{0,2}.`t{1,10}." -f $Item.Option,$Item.Description)
    If($c % 2 -eq 0){$menu +="`n"}

    $c++
}

Write-Host $menu

Using -f you can format your columns to a set size, the following formats $Item.Option to have a 2 width and $Item.Description to have a width of 10 characters.

"{0,2}.`t{1,10}." -f $Item.Option,$Item.Description