Home > OS >  I want to split a string from : to \n in Powershell script
I want to split a string from : to \n in Powershell script

Time:05-30

I am using a config file that contains some information as shown below.

User1:[email protected]
User1_Role:Admin
NAME:sdfdsfu4343-234324-ffsdf-34324d-dsfhdjhfd943
ID:xyz@abc-demo-test-abc-mssql
Password:rewrfsdv34354*fds*vdfg435434

I want to split each value from*: to newline* in my Powershell script. I am using -split '[: \n]' it matches perfectly until there is no '' in the value. If there is an '*' it will fetch till that. For example, for Password, it matches only rewrfsdv34354. Here is my code:

$i = 0
foreach ($keyOrValue in $Contents -split '[: *\n]') {
  if ($i   % 2 -eq 0) { 
    $varName = $keyOrValue 
  } 
  else { 
    Set-Variable $varName $keyOrValue 
  } 
}

I need to match all the chars after : to \n. Please share your ideas.

CodePudding user response:

It's probably best to perform two separate splits here, it makes things easier to work out if the code is going wrong for some reason, although the $i % 2 -eq 0 part is a neat way to pick up key/value.

I would go for this:

# Split the Contents variable by newline first
foreach ($line in $Contents -split '[\n]') {
   # Now split each line by colon
   $keyOrValue = $line -split ':'
   # Then set the variables based on the parts of the colon-split
   Set-Variable $keyOrValue[0] $keyOrValue[1]
}

CodePudding user response:

You could also convert to a hashtable and go from there, e.g.:

$h = @{}
gc config.txt | % { $key, $value = $_ -split ' *: *'; $h[$key] = $value } 

Now you have convenient access to keys and values, e.g.:

$h

Output:

Name                           Value
----                           -----
Password                       rewrfsdv34354*fds*vdfg435434
User1                          [email protected]
ID                             xyz@abc-demo-test-abc-mssql
NAME                           sdfdsfu4343-234324-ffsdf-34324d-dsfhdjhfd943
User1_Role                     Admin

Or only keys:

$h.keys

Output:

Password
User1
ID
NAME
User1_Role

Or only values:

$h.values

Output:

rewrfsdv34354*fds*vdfg435434
[email protected]
xyz@abc-demo-test-abc-mssql
sdfdsfu4343-234324-ffsdf-34324d-dsfhdjhfd943
Admin

Or specific values:

$h['user1']   ", "   $h['user1_role']

Output:

[email protected], Admin

etc.

  • Related