powershellsplittrimends-with

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=PCName\SQL_Instance. The values I'm working with look like...

Provider=SQLOLEDB;Server=PCName\SQL_Instance;SomeOtherCrap=moreWords;ThisGoes=OnAndOn
Proer=SQLOLEDB;Server=PCName\SQL_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.


Solution

  • 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=PCName\SQL_Instance;SomeOtherCrap=moreWords;ThisGoes=OnAndOn"
     $string.Split(";") | Where {$_.startswith("Server")}
     Server=PCName\SQL_Instance
     ($string.Split(";") | Where {$_.startswith("Server")}).split("=")[1].split("\")[0]
     PCName