What is an equivalent of *Nix 'cut' command in Powershell?
powershell, powershell-2.0, split
Solution
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
Problem
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 ?