Unexpected token '$regex

This topic contains 3 replies, has 3 voices, and was last updated by  Chris Bakker 1 year, 6 months ago.

  • Author
  • #33126

    Wei-Yen Tan

    Hi guys,

    I have been trying to debug this issue with my code.

    What I am trying to do is listed in the comment based help but on this line:

    $a | Select -ExpandProperty samaccountname | Get-Aduser |
    where {"$_.$ADProperty" -$Operator "$regex"

    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:

    $a = get-adgroupmember -identity $ADGroup
    $a | Select -ExpandProperty samaccountname | Get-Aduser | where {$_.givenname -match "^[A-Z]"}

    it does work.

    The full copy of my script is below. Any help most appreciated.

    function Extract-ADGroupmember
    [Parameter(Mandatory = $true,
    ValueFromPipeline = $true,
    ValueFromPipelineByPropertyName = $true,
    Position = 1)]
    [Parameter(Mandatory = $true,
    Position = 2)]
    [ValidateSet("givenname", "surname")]
    Position = 3)]
    $Operator = "match",
    [Parameter(Mandatory = $true,
    Position = 4)]
    Import-Module ActiveDirectory
    $a = get-adgroupmember -identity $ADGroup

    $a | Select -ExpandProperty samaccountname | Get-Aduser |
    where {"$_.$ADProperty" -$Operator '$regex'


  • #33127

    Dave Wyatt

    You can't use a variable in place of an operator like that (-$Operator).

  • #33129

    Wei-Yen Tan

    Sorry I posted twice. I'll copy what I have over here.

    So I can't paramaterize that operator at all?

  • #60826

    Chris Bakker

    I think this would do the trick:

    $operator = 'match'
    $command= "1 -$operator 1"
    Invoke-Expression $command

You must be logged in to reply to this topic.