it says this “Unexpected token ‘$regex’ in expression or statement” in Powershell. I am not quite sure why it is doing this as if I am writing it out in the console:
The problem is that you’re trying to use -$Operator instead of just -match. You can’t substitute operators with variables that way. (You’ve also got double-quotes around $_.$ADProperty and single quotes around $regex, neither of which are likely to work the way you want them to.)
If you’re using PowerShell v3 or later, you can take advantage of Where-Object’s new parameter sets and splatting to accomplish something very similar, though:
If you’re stuck supporting PowerShell v2, then you’ll have to do a bit more work. I think what I might do in that case is create a script block according to the operator that was passed in. Something like this:
Thank you very much for the reply. We have a Win2012 R2 management box at the place where we are at…so the first option is on the table with Where-Object parameter sets. I tried to add what you have with the splatting but I got no results when I should have got some results.
When I ran it through the debugger, the operator splat value didn’t contain any values. Is there something that I am missing such as defining
I understand what you are trying to do, but when I evaluate $splatoperator, Powershell returns the value of the splat as a system.collections.hashtable.
Ok…but ithen when powershell is interpreting the hash, shouldnt it show the $operator value?
For some reason I don’t think its getting the operator correctly as I am getting the error:
ERROR: Where-Object : A positional parameter cannot be found that accepts argument ‘[1]’.
Extract-ADGroupmember.ps1 (55, 4): ERROR: At Line: 55 char: 4
That worked and using the syntax below works and gives the result that I want.
What was confusing me was seeing the splat with a value of $true. I learn something new everyday!
You’re getting hung up on the hyphen. That’s the syntax for operators (and parameters), but when you’re using splatting, you don’t need the hyphen. Maybe PowerShell’s smart enough to ignore it; dunno, never tried, because that’s not how the documentation says it’s supposed to work.
Ahhh ok. My apologies Dave, you are right. I checked again without the - and it gave me the desired result. Using the hypen didn’t give me the results properly.
Thanks for correcting my assumptions. Reading through the help about_splatting it wasnt apparent to me of what you said.
In either case this whole exercise is very fruitful.