1

I'm providing the user 2 dropdown lists (1. "Region" and 2. "Site"), the second list dependant/dynamic on the first list selection. When a "Region" item is selected, I'm doing a select-string to lookup a file which has all region/site information to return all lines which match the selected Region plus the 2 lines below that to give the site line. I then tidy up and search those results to return just the site lines. I can then update the "Site" dropdown box with only sites relevant to the region the user selected. This is to split the number of sites listed on the screen.

eg. siteinfo.txt:

[UK - London]
Region = EMEA
Timezone = xxx
Site = London

[AU - Brisbane]
Region = APAC 
Timezone = xxx
Site = Brisbane

eg. Script (with "APAC" selection in region list):

$input = get-content C:\Temp\siteinfo.txt
$SearchString = 'Region = APAC' 
$SearchStringsite = 'SiteName = '
$sitelist = $input | select-string $SearchString -Context 2 | select-string "Site = " | ForEach-Object {$_ -Replace $SearchStringsite,""} 

The above script fails with no error and also tried splitting the select-string commands and inject the region results into a variable into the select-string but get the same.

However I was able to write the first select-string results to a file, then read that file into the second select-sting and it works. I am trying to avoid having to output to a file as the environment could have locked down write policies where the script is run.

Any ideas how to accomplish this?

1 Answer 1

2

The problem is that Select-String returns MatchInfo objects, but the default display makes it look like it's just returning a strings. To get to the context lines, you have to reference them as .context.postcontext

I traded your $input for $data ($input is actually reserved as an automatic variable), and folded it at the pipes for readablility:

$data = get-content C:\Temp\siteinfo.txt
$SearchString = 'Region = APAC' 
$SearchStringsite = 'SiteName = '
$sitelist = $($data |
 select-string $SearchString -Context 2).Context.PostContext |
 select-string "Site = " |
 ForEach-Object {$_ -Replace $SearchStringsite,""} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.