title: PowerShell Select-String regular expression to locate two strings on the same line
body: <p>How do I use Select-String cmdlet to search a text file for a string which starts with a specific string, then contains random text and has another specific string towards the end of the line? I'm only interested in matches across a <strong>single line</strong> in the text file, not across the entire file.</p>
  
  <p>For example I am searching to match both 'Set-QADUser' and 'WhatIf' on the same line in the file. And my example file contains the following line:</p>
  
  <p><strong>Set-QADUser -Identity $($c.ObjectGUID) -ObjectAttributes @{extensionattribute7=$ekdvalue} -WhatIf | Out-Null</strong></p>
  
  <p>How do I use Select-String along with a Regular Expression to locate the pattern in question? I tried using the following and it does work but it also matches other instances of either 'Set-QADUser' or 'WhatIf' found elsewhere in the text file and I only want to match instances when both search strings are found on the same line.</p>
  
  <pre><code>Select-String -path "test.ps1" -Pattern "Set-QADUser.*WhatIf" | Select Matches,LineNumber
  </code></pre>
  
  <p>To make this more complicated I actually want to perform this search from within the script file that is being searched. Effectively this is used to warn the user that the script being run is currently set to 'WhatIf' mode for testing. But of course the regEx matches the text from the actual Select-String cmd within the script when it's run - so it finds multiple matches and I can't figure out a very good way to overcome that issue. So far this is what I've got:</p>
  
  <pre><code>#Warn user about 'WhatIf' if detected
  $line=Select-String -path $myinvocation.mycommand.name -Pattern "Set-QADUser.*WhatIf" | Select Matches,LineNumber
  If ($line.Count -gt 1)
  {
      Write-Host "******* Warning ******"
      Write-Host "Script is currently in 'WhatIf' mode; to make changes please remove '-WhatIf' parameter at line no. $($line[1].LineNumber)"
  }
  </code></pre>
  
  <p>I'm sure there must be a better way to do this. Hope somebody can help.</p>
  
  <p>Thanks</p>