0

still learning powershell. I have a script that moves an xml file based on a search string but it needs to match more than 1 search string and I'm struggling with a way to do this.

Here's the code as I have it, which currently works for a single string:

$SrcDir = "c:\source"
$DestDir = "c:\destination"
$SearchString1 = "String1"
$SearchString2 = "String2"

Get-ChildItem $SrcDir -filter *.xml | 
  Select-String $SearchString1 -List | 
  Select-Object Path | 
  Move-Item -Dest $DestDir

So it's clear what I'm trying to achieve: If the xml file contains $SearchString1 AND $SearchString2 then move from source to destination. I can't seem to make it match both. It's probably very simple, or maybe I need to do it a different way, but I would appreciate some help.

3
  • As Get-Help Select-String says, this cmdlet accepts Regular Expressions. So why not Select-String -Pattern "($SearchString1|$SearchString2)" to make it quite simple? Commented Nov 15, 2017 at 11:29
  • The better soultion for this special case would be "String(1|2)" (or similiar) Commented Nov 15, 2017 at 11:31
  • Possible duplicate of How to use PowerShell select-string to find more than one pattern in a file? Commented Nov 15, 2017 at 14:28

1 Answer 1

0

Looking at Select-String's help:

PS> Get-Help Select-String -Parameter Pattern

-Pattern

Specifies the text to find. Type a string or regular expression. If you type a string, use the SimpleMatch parameter.

To learn about regular expressions, see about_Regular_Expressions.

It says, that -Pattern wants a reqular expression, not a [string]. As suggested by the help page, we learn more about Regular Expressions using Get-Help About_Regular_Expressions.

This results in replacing your statement Select-String $SearchString1 -List with:

Select-String "($SearchString1.*$SearchString2|$SearchString2.*$SearchString1)" -List | #[...]

Will do the trick.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this is much closer, as it now searches against both strings, however it uses OR rather than AND, so it moves it if it matches either rather than both. Also, thanks for the link, it will come in handy while I'm learning.
Sorry I forgot about the and... this is hard using regex. For this I'd recommend you to look at this answer
That didn't move anything at all, but the other answer is indeed what I'm trying to do so I'll work from that and see what I can come up with and post back, thank you for your assistance! I did search but not with 'pattern' as I've not come across that term in powershell before. was searching for 'match multiple strings' which wasn't giving me anything useful

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.