Unexpected token '$regex

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Chris Bakker Chris Bakker 3 weeks, 4 days ago.

  • Author
    Posts
  • #33126
    Profile photo of Wei-Yen Tan
    Wei-Yen Tan
    Participant

    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.

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

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

    }

  • #33127
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

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

  • #33129
    Profile photo of Wei-Yen Tan
    Wei-Yen Tan
    Participant

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

    So I can't paramaterize that operator at all?

  • #60826
    Profile photo of Chris Bakker
    Chris Bakker
    Participant

    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.