Expanding a string inside a scriptblock

Welcome Forums General PowerShell Q&A Expanding a string inside a scriptblock

This topic contains 8 replies, has 3 voices, and was last updated by

Al
 
Participant
1 year, 10 months ago.

  • Author
    Posts
  • #60300
    Al

    Participant
    Points: 0
    Rank: Member

    I wonder if it is legal/valid to expand a local variable inside a script block, which will be used on some cmdlet PARAMETER ( maybe AD cmdlet ):

    $a='Ro'
    $sb={Name -like "$a*"} # the expansion would occur here -> $sb={Name -like 'Ro*'}
    Get-ADUser -Filter $sb ...
    # would use $sb again with other cmdlet parameters
    

    Is it valid/legal?

  • #60319

    Participant
    Points: 21
    Rank: Member

    My lawyer says don't do that. He wouldn't defend the use of like.

    $a='potter, dan'
    $sb={anr -eq $a}
    Get-ADUser -Filter $sb

  • #60346
    Al

    Participant
    Points: 0
    Rank: Member

    Definitely, a good lawyer, so good that "escaped" my question and answered you about a question I did not do. What about my original question: " expanding a string inside a script block: is it valid/legal (under PS rules)/correct?
    In other words, is this assignment

    $sb={Name -like "$a*"}
    

    equivalent to this one

    $sb={Name -like " Ro*"}
    

    under the context of my original question?

  • #60349

    Participant
    Points: 21
    Rank: Member

    I have yet to find the rule book for powershell. Does it work?

    • #60363
      Al

      Participant
      Points: 0
      Rank: Member

      Please, in this thread just answer my question(s), if you know the answer ( it doesn't seem to be true ).
      As to your question, please, start your own thread, and wait some reply...

  • #60396

    Participant
    Points: 21
    Rank: Member

    Is it valid/legal?

    NO

  • #60531

    Moderator
    Points: 24
    Team Member
    Rank: Member

    The good thing about the Active Directory cmdlets is that you can provide a normal string for the filter with the same syntax.

    $a = 'Ro'
    $filter = " Name -like '$a*' "
    Get-ADUser -Filter $filter
    

    I hope that helps.

  • #60532

    Moderator
    Points: 24
    Team Member
    Rank: Member

    As alternative you could also you below syntax if you really want a scriptblock:

    $a = 'Ro'
    $sb = [scriptblock]::Create("Name -like '$a*'")
    Get-ADUser -Filter $sb
    
    • #60565
      Al

      Participant
      Points: 0
      Rank: Member

      That's it! Thanks.

The topic ‘Expanding a string inside a scriptblock’ is closed to new replies.