Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

split - Powershell Get Value from string knowing it always starts with a string and ends with a string

I am running a SQL query and need to pull a machine name out of the field. The results have multiple entries separated by semicolons. I only care about the value for Server=PCNameSQL_Instance. The values I'm working with look like...

Provider=SQLOLEDB;Server=PCNameSQL_Instance;SomeOtherCrap=moreWords;ThisGoes=OnAndOn
Proer=SQLOLEDB;Server=PCNameSQL_Instance;SsdgsdfomeOtherCrap=moreWords;TzfdzdfghisGoes=OnAndOn

The server= will always contain my PC name (local Access DB install) and they will all be the same even though there re multiple lines. I really only need to get the name once. And while I already split the values by the ; my brain is too fried to figure out how to get the server name from the results. I'm sure this is painfully obvious as the value is handed to you on a platter but I'm not that smart to even be able to figure out how to search the answer.

question from:https://stackoverflow.com/questions/65866232/powershell-get-value-from-string-knowing-it-always-starts-with-a-string-and-ends

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use StartsWith("Server") to filter out the required object, then throw in another split on "=" and "/", probably easier with RegEx, but I like splits e.g.:

 $string = "Provider=SQLOLEDB;Server=PCNameSQL_Instance;SomeOtherCrap=moreWords;ThisGoes=OnAndOn"
 $string.Split(";") | Where {$_.startswith("Server")}
 Server=PCNameSQL_Instance
 ($string.Split(";") | Where {$_.startswith("Server")}).split("=")[1].split("")[0]
 PCName

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...