none
Varaible interpolation in a regex RRS feed

  • Question

  • This command returns nothing:

    PS C:\Windows\system32> Get-ADComputer -Filter 'OperatingSystem -like "*$([regex]::Escape($OS_type))*"' -Properties * | Select-Object Name

    Though:

    PS C:\Windows\system32> "*$([regex]::Escape($OS_type))*"
    *7*

    But this does:

    PS C:\Windows\system32> Get-ADComputer -Filter 'OperatingSystem -like "*7*"' -Properties * | Select-Object Name

    Name         
    ----         
    PC01565      
    LFL7-VPC

    I am confused and any help understanding what I am doing wrong would be greatly appreciated.     

    Monday, May 22, 2017 3:15 PM

Answers

All replies

  • Why do you need the [Regex]::Escape method?


    -- Bill Stewart [Bill_Stewart]

    Monday, May 22, 2017 3:29 PM
    Moderator
  • You are right I don't:

    PS C:\Windows\system32> "*$OS_type*"
    *7*

    PS C:\Windows\system32> Get-ADComputer -Filter 'OperatingSystem -like "*$OS_type*"' -Properties * | Select-Object Name

    But it still returns nothing.

    Monday, May 22, 2017 3:40 PM
  • I suggest learning about string in PowerSHell

    $OS_type = '*7*'
    Get-ADComputer -Filter "OperatingSystem -like '$OS_type'" | Select-Object Name

    OR

    $OS_type = '7'
    Get-ADComputer -Filter "OperatingSystem -like '*$OS_type*'" | Select-Object Name


    \_(ツ)_/

    Monday, May 22, 2017 3:46 PM
  • Use -LDAPFilter instead.


    Get-ADComputer -LDAPFilter "(operatingSystem=*$OS_type*)"
    


    -- Bill Stewart [Bill_Stewart]

    Monday, May 22, 2017 3:47 PM
    Moderator
  • This works. Thanks.

    But I still don't know why my two attempts failed

    Monday, May 22, 2017 3:59 PM
  • Thanks.
    Monday, May 22, 2017 3:59 PM
  • But is not usable in in my situation because:

    $OS_type=Read-Host-Prompt"Enter the OS type"

    Monday, May 22, 2017 4:02 PM
  • But is not usable in in my situation because:

    $OS_type=Read-Host-Prompt"Enter the OS type"

    There is no reason why that won't work

    $OS_type = Read-Host 'Enter the OS type [7,2008,2012]'
    Get-ADComputer -Filter "OperatingSystem -like '*$OS_type*'" | Select-Object Name

    Which works fine for me. Answer 7 or 2008 or 2012 and it works.


    \_(ツ)_/


    • Edited by jrv Monday, May 22, 2017 4:12 PM
    Monday, May 22, 2017 4:12 PM
  • Strange, that's how I started out but had to look for different ways of doing it because it wasn't returning anything.
    Monday, May 22, 2017 5:06 PM