Reputation: 351
I have the following code:
$myString = "Name=Tony;Fee=10;Account=Premium"
$splitString = "$($myString)".Split(";")
$name = $splitString -match "Name=(?<content>.*)"
$acct = $splitString -match "Account=(?<content>.*)"
$name
$acct
Result:
Name=Tony
Account=Premium
How can I get it to return just the value? Example:
Tony
Premium
Thanks in advance
Upvotes: 2
Views: 146
Reputation: 26325
I would use -split
here to to construct a hashtable of key value pairs:
$myString = "Name=Tony;Fee=10;Account=Premium"
# Create hashtable
$ht = @{}
# Spit string by ';' and loop over each item
foreach ($item in $myString -split ';') {
# Split item by '=' to get key value pair
$pair = $item -split '='
# Set key value pair into hashtable
$ht[$pair[0]] = $pair[1]
}
# Output values you want
$ht.Name
$ht.Account
# Tony
# Premium
Which also is beneficial if you need to lookup other values.
Upvotes: 1
Reputation: 8868
Here's another approach using -Split
and taking advantage of the text's format using ConvertFrom-StringData
$name, $acct = "Name=Tony;Fee=10;Account=Premium" -split ';' |
ConvertFrom-StringData | ForEach-Object {$_.name,$_.Account}
Upvotes: 1
Reputation: 439727
Combine -split
, the string splitting operator, with a switch
statement and its -Regex
switch:
$name, $acct =
switch -Regex ("Name=Tony;Fee=10;Account=Premium" -split ';') {
'^(?:Name|Account)=(?<content>.*)' { $Matches['content'] }
}
Upvotes: 4