Gosia Wiśniewska
Gosia Wiśniewska

Reputation: 47

How to make array out of string?

I have a string [R1A_0001, R1A_0002, R1A_0003, R1A_0004, R1A_0005] which I need to convert into array in Powershell.

$scripts = "[R1A_0001, R1A_0002, R1A_0003, R1A_0004, R1A_0005]"
Write-Output $scripts
$scripts = $scripts -replace '[\[|\]]','"'
$scripts = $scripts -replace '[,]','","'
$scripts = $scripts -replace '[ ]',''
$scripts = @($scripts)

I would expect to get an array out of this code, but instead I get "R1A_0001","R1A_0002","R1A_0003","R1A_0004","R1A_0005" - still a string... Please help

Upvotes: 0

Views: 48

Answers (1)

Fourat
Fourat

Reputation: 2447

You can use methods from .net string type :

PS P:\> $scripts = "[R1A_0001, R1A_0002, R1A_0003, R1A_0004, R1A_0005]"
PS P:\> $scripts = $scripts.Replace("[","").Replace("]","").Replace(" ","")
PS P:\> $scriptsCsv = $scripts.Split(",")
PS P:\> $scriptsCsv
R1A_0001
R1A_0002
R1A_0003
R1A_0004
R1A_0005
PS P:\> $scriptsCsv.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array

Upvotes: 1

Related Questions