29

I have following content in a configuration file (sample.cfg),

Time_Zone_Variance(Mins):300
Alert_Interval(Mins):2
Server:10.0.0.9
Port:1840

I'm trying to store an each values after the : by using split in PowerShell. but i'm not able to produce require output.

Can someone tell me how to use PowerShell split for the above problem ?

4 Answers 4

26

You can read the contents of the file using Get-Content, then pipe each line through ForEach-Object, then use the split command on each line, taking the second item in the array as follows:

$filename = "sample.cfg"

Get-Content $filename | ForEach-Object {
    $_.split(":")[1]
}

Output

300
2
10.0.0.9
1840

Update

I prefer the approach by @AnsgarWiechers, but if you really need specifically named values you could create a hashtable and replace the name with the value:

$configValues = @{
    hour    = "Time_Zone_Variance(Mins)"
    min     = "Alert_Interval(Mins)"
    server  = "Server"
    port    = "Port"
}

Get-Content $filename | ForEach-Object {

    # Courtesy of Ansgar Wiechers
    $key, $value = $_ -split ':', 2

    foreach($configValuesKey in $($configValues.keys)) {
        if ($configValues[$configValuesKey] -eq $key)
        {
            $configValues[$configValuesKey] = $value
        }
    }
}

write-host "`nAll Values:"
$configValues
write-host "`nIndividual value:"
$configValues.port

Output

All Values:

Name                           Value                                                                                             
----                           -----                                                                                             
port                           1840                                                                                              
min                            2                                                                                                 
server                         10.0.0.9                                                                                          
hour                           300                                                                                               

Individual value:
1840
3
  • David thanks, Can you tell me how to store each value in a variable like $hour = 300, $min = 2, $server = 10.0.0.9, $port = 1840 Jul 8, 2014 at 16:43
  • 1
    For individually named variables you could do something like $configValues.Keys | % { New-Variable -Name $_ -Value $configValues[$_] }. Jul 9, 2014 at 10:22
  • great answers here. if you happen to be splitting on space instead of colon, and your data may have a variable number of spaces as a single delimiter, don't forget to collapse them via something like ($_ -replace ' *', ' '). Oct 20, 2021 at 18:35
17

How's this?

function cut {
  param(
    [Parameter(ValueFromPipeline=$True)] [string]$inputobject,
    [string]$delimiter='\s+',
    [string[]]$field
  )

  process {
    if ($field -eq $null) { $inputobject -split $delimiter } else {
      ($inputobject -split $delimiter)[$field] }
  }
}


PS C:\> 'hi:there' | cut -f 0 -d :
hi

PS C:\> 'hi:there' | cut -f 1 -d :
there

PS C:\> 'hi:there' | cut -f 0,1 -d :
hi
there

PS C:\> 'hi:::there' | cut -f 0 -d :+
hi

PS C:\> 'hi   there' | cut
hi
there
2
  • It is close to 'cut' - only new line characters should not be inserted. Input is one line, output is as many lines as number of fields you selected. +1 anyway.
    – vt100
    Jan 5, 2018 at 11:54
  • The output is actually an array, but powershell displays it that way.
    – js2010
    Jan 5, 2018 at 23:46
8

For a more succint syntax, this will also do the trick:

((Get-Content "your-file.txt") -Split ":")[1]

So the trick to use the -Split method is to have a String object returned by Get-Content (alias cat can also be used, actually), and from the resulting String[] object you can use the brackets to extract the nth item.

Note: Using -Split without parenthesis around Get-Content won't work since -Split is not a parameter name for that command... 🤷‍♂️

3
  • I converted the output of ns-lookup to a string but that does not work : (nslookup X.Y.Z.T | Out-String).Split(' ')[-1]
    – SebMa
    Jul 11, 2022 at 13:41
  • 1
    I tried this : (nslookup 172.16.78.12)[-3..-2] > your-file.txt and then I type your command but it only processed the first line.
    – SebMa
    Jul 11, 2022 at 14:10
  • 1
    This answer is wrong because it works only for a single line. Please stop upvoting it!
    – user829755
    Jul 11 at 10:50
6

I suppose you don't want to just split the lines, but actually create key/value pairs. That could be achieved like this:

$config = @{}
Get-Content 'C:\path\to\sample.cfg' | % {
  $key, $value = $_ -split ':', 2
  $config[$key] = $value
}

You could also use the ConvertFrom-StringData cmdlet:

Get-Content 'C:\path\to\sample.cfg' | % {
  ConvertFrom-StringData ($_ -replace ':','=')
}

The -replace operation is necessary, because ConvertFrom-StringData expects key and value to be separated by =. If you could change the delimiter in the config file from : to =, you could use ConvertFrom-StringData $_ without replacement.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.