Expanding a string inside a scriptblock

Tagged: 

This topic contains 8 replies, has 3 voices, and was last updated by Profile photo of Al Al 7 months ago.

  • Author
    Posts
  • #60300
    Profile photo of Al
    Al
    Participant

    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
    Profile photo of Dan Potter
    Dan Potter
    Participant

    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
    Profile photo of Al
    Al
    Participant

    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
    Profile photo of Dan Potter
    Dan Potter
    Participant

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

    • #60363
      Profile photo of Al
      Al
      Participant

      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
    Profile photo of Dan Potter
    Dan Potter
    Participant

    Is it valid/legal?

    NO

  • #60531
    Profile photo of Daniel Krebs
    Daniel Krebs
    Moderator

    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
    Profile photo of Daniel Krebs
    Daniel Krebs
    Moderator

    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
      Profile photo of Al
      Al
      Participant

      That's it! Thanks.

You must be logged in to reply to this topic.