String trim and split

I have a text file that I read and I need to get the values from.

Example text file:

[Site 01]

[Site 02]

Currently my code reads through the file and places each each as an array entry for each line DBServer= that is found and this text file can have many sites:

$NumOfSites = Get-Content $Sites | Select-String -Pattern "DBServer=" -Context 0,3 $i = 0 $NumOfSites | ForEach-Object { $svr = $NumOfSites[$i] -isplit "\n" | % { ($_ -isplit 'DBServer=').Trim()[1] } $db = $NumOfSites[$i] -isplit "\n" | % { ($_ -isplit 'DBName='.Trim())[1] } $uid = $NumOfSites[$i] -isplit "\n" | % { ($_ -isplit 'Username='.Trim())[1] } $pswd = $NumOfSites[$i] -isplit "\n" | % { ($_ -isplit 'Password='.Trim())[1] } $i = $i+1 }

I can't get each attribute to split out properly without some extra spaces or something nicely as a string variable. I just need to extract the info to put into an SQL connection line as variables from the format of the file example I have.


Other than the record headers (i.e. [Site 01]) the rest can be handled by ConvertFrom-StringData just fine. We can just convert the records to objects directly splitting on the header row more or less. ConvertFrom-StringData turns a multi-line string into a hashtable, and you can just cast that as a [PSCustomObject] and viola, you have objects that are easy to use.

$NumOfSites = Get-Content $Sites -raw $SiteObjects = $NumOfSites -split '\[.+?\]'|%{[PSCustomObject](ConvertFrom-StringData -StringData $_)}

Then you can manipulate $SiteObjects however you see fit (output to CSV if you want, or filter on any property using Select-Object). Or, if you're looking to make connections you can loop through it building your connections as needed...

ForEach($Connection in $SiteObjects){ $ConStr = "Server = {0}; Database = {1}; Integrated Security = False; User ID = {2}; Password = {3};" -f $Connection.DBServer.Trim(), $Connection.DBName.Trim(), $Connection.Username.Trim(), $Connection.Password.Trim() <Do stuff with SQL> }

<strong>Edit:</strong> Updating my answer since the sample text was changed to add <pre> and </pre>. We just need to remove those, and since the OP is getting errors about methods on null values we'll filter for null as well.

$NumOfSites = Get-Content $Sites -raw $SiteObjects = $NumOfSites -replace '<.*?>' -split '\[.+?\]' | ?{$_} |%{[PSCustomObject](ConvertFrom-StringData -StringData $_)} ForEach($Connection in $SiteObjects){ $svr = $Connection.DBServer.Trim() $db = $Connection.DBName.Trim() $uid = $Connection.Username.Trim() $pwd = $Connection.Password.Trim() }


Here's a suggestion if you only care about getting the value after the equals:

Get-Content Example.txt | ForEach-Object { Switch -Regex ($_) { 'dbs.+=' { $svr = ($_ -replace '.+=').Trim() .. etc .. } }

Get-Content piped to ForEach-Object will interpret each line as its own object.


Edit: You were most of the way there, but it's unnecessary to -split the lines

$NumOfSites = Get-Content $Sites | Select-String -pattern "DBServer=" -Context 0,3 $NumOfSites | ForEach-Object { Switch -Wildcard ($_) { 'DBS*=' { $svr = ($_ -replace '.+=').Trim() } 'DBN*=' { $db = ($_ -replace '.+=').Trim() } 'U*=' { $uid = ($_ -replace '.+=').Trim() } 'P*=' { $pw = ($_ -replace '.+=').Trim() } } }


  • Can I run Robotium tests automatically in parallel on multiple emulators?
  • Android : Strike out Text with bold or thicker line than default STRIKE_THRU_TEXT_FLAG
  • Swift gives “self used before all stored procedures are initialized” error when building child nodes
  • How to calculate total across columns but one?
  • firebase, how to update data at a key
  • Attemping to change attributes of $(this) inside success function
  • How to extract a number from a string [duplicate]
  • Updating and removing unique join relationships in CakePHP
  • How to use the resource module to measure the running time of a function?
  • Python: Split a String Field into 3 Separate Fields using Lambda
  • end daemon processes with multiprocessing module
  • how can I compare dates in array to find the earliest one?
  • Lua: Line breaks in strings
  • Divide a $1 by 3 and adjusting 1 cent
  • Google Places API - Find a company's CID and LRD
  • Validate jQuery plugin, field not required
  • jQuery: add elements until a particular height is reached
  • How do I shift the decimal place in Python?
  • Is there a way to save the selected text and highlight it again once the page is refreshed?
  • Reading a file into a multidimensional array
  • Reduction and collapse clauses in OMP have some confusing points
  • rspec simple example getting error on request variable in integration test
  • How can I extract results of aggregate queries in slick?
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Converting a WriteableBitmap image ToArray in UWP
  • preg_replace Double Spaces to tab (\\t) at the beginning of a line
  • D3 nodes and links from JSON with nested arrays of children
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Projection media query: browser support and workarounds?
  • htaccess rewriting URLs with multiple forward slashes
  • Weird JavaScript statement, what does it mean?
  • How do you troubleshoot character encoding problems?
  • R: gsub and capture
  • AT Commands to Send SMS not working in Windows 8.1
  • How to format a variable of double type
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Turn off referential integrity in Derby? is it possible?
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++
  • How to Embed XSL into XML