Powershell splitting string array into separate objects

Soldato
Joined
8 Mar 2005
Posts
3,674
Location
London, UK
I'm trying to split a string array into separate and new objects, for instance;
Code:
Get-CMDLet Fooapp | AppName, Accounts
Produces;
Code:
AppName: Fooapp
Accounts: {FooaccountA, FooaccountB, FooaccountC}
What I want to do is split out the string array into separate objects;iterating however many items are in the string array; for instance as follows;
Code:
AppName: Fooapp
Accounts1: fooaccountA
Accounts2: fooaccountB
Accounts3: fooaccountC
Breaking the string array into a single string with a space delimiter via; (I know this is spurious and unnecessary)
Code:
Get-CMDLet <variable> | AppName, @{Name='Accounts';Expression={[string::join(" ",($_.accounts))}}
Gets me to here;
Code:
AppName: Fooapp
Accounts: FooaccountA FooaccountB FooaccountC
It's the final bit which I'm struggling with. Any help or pointers would be greatly appreciated.
Cheers, Paul.
 
Associate
Joined
2 Jul 2003
Posts
2,442
Think I got what you want:

Code:
$AppName = "Fooapp"
$Accounts = @("FooaccountA", "FooaccountB", "FooaccountC")

$Fooapp = "" | Select AppName, Accounts
$Fooapp.AppName = $AppName
$Fooapp.Accounts = $Accounts

#$Fooapp

# Build the field list
$ItemCount = ($Fooapp.Accounts).Count
$Fields = "AppName,"
For ($i = 1; $i -Le $ItemCount; $i++)
{
    If ($i -lt $ItemCount)
    {
        $Fields += "Account$i" + ","
    }
    Else
    {
        $Fields += "Account$i"
    }
}

$Record = "" | Select $Fields.Split(',')
$Record.AppName = $Fooapp.AppName

For ($i = 1; $i -Le $ItemCount; $i++)
{
    $Record."Account$i" = $Fooapp.Accounts[$i -1] 
}

$Record

First bit is just me trying to replicate your object.
Just assign your get command to $Fooapp and should do the rest!
 
Back
Top Bottom