Link to home
Start Free TrialLog in
Avatar of SLPowers
SLPowersFlag for United States of America

asked on

PowerShell convert a text to array

I have no doubt this will be ridiculously simple for most and I hate asking.

Have always used a workaround for the bottom 2 scenarios that only involve an extra line or 2 but I also know there is a better way and frankly my way has become embarrassing.  I am sure in uses the @ and or split but can’t make it work.
How can I make the $List and $header into an array for either of the 2 below scenarios without my stupid workarounds where I pipe them into temp text files.

I want to run actions on each word in the below examples but it obviously treats the $List and $Header as one string.  
 
Foreach ($word in $List) {
}
# Or
Foreach ($word in $Header) {
}

Thanks



$List = "Computer
SubOU
BusinessRole
Location
Department
ModelType
AssetTag
AssignedTo
LocCode
SerialNumber
RoomNumber
GroupMembership
MachineNumber
Comments
Add/Remove"

 $header = "Computer SubOU BusinessRole Location Department ModelType AssetTag AssignedTo LocCode SerialNumber RoomNumber GroupMembership MachineNumber Comments Add/Remove"
Avatar of Qlemo
Qlemo
Flag of Germany image

You can use an array from start, or split the text on space / newline
$header = "Computer", "SubOU","BusinessRole" # and so on
$header = "Computer SubOU BusinessRole Location Department ModelType AssetTag AssignedTo LocCode SerialNumber RoomNumber GroupMembership MachineNumber Comments Add/Remove" -split ' '

Open in new window

For newline, use -split "`n".
Avatar of Rgonzo1971
Rgonzo1971

Hi,

pls try

$headers = "Computer SubOU BusinessRole Location Department ModelType AssetTag AssignedTo LocCode SerialNumber RoomNumber GroupMembership MachineNumber Comments Add/Remove".split(' ')

Regards
Avatar of SLPowers

ASKER

Thanks both of those work for $header but what about $list?
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks so much.

After being provided the -split option i looked deeper into it and discovered this.

-split '[\n]'

That seems to work the the $List string.

I appreciate the guidance and have a great day.
Yes, that works too, but it is a regular expression then. Overcomplicated. You use a regex only if you need some kind of condition (e.g. phrases, or combination of delimiters) to determine where to split.