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 ?
Use Get-Command as the Equivalent of Which Command in PowerShell. The Get-Command cmdlet displays all commands installed on the computer, including cmdlets , aliases , functions , filters , scripts , and applications .
One of the most common ways to trim strings in PowerShell is by using the trim() method. Like all of the other trimming methods in PowerShell, the trim() method is a member of the System. String . NET class.
Being a cross-platform scripting language, PowerShell on Linux supports all of the commonly known commands from CMD and Linux's command line shell such as sudo apt update . No need to open a Bash terminal! From here on out you can run thousands of built-in PowerShell commands.
The findstr command is a Windows grep equivalent in a Windows command-line prompt (CMD). In a Windows PowerShell the alternative for grep is the Select-String command.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With