Inserting string into command

This topic contains 2 replies, has 2 voices, and was last updated by  Aaron 2 months, 2 weeks ago.

  • Author
    Posts
  • #76468

    Aaron
    Participant

    Hello, why doesnt something like this work?

    $query = "$_.passwordneverexpires -eq $true"
    
    (Get-ADUser -filter * -Properties PasswordNeverExpires,passwordlastset,lastlogontimestamp | ?{$_.enabled -eq $true} | select name,PasswordNeverExpires,passwordlastset,@{name = 'LastLogon';Expression = ({get-date $_.lastlogontimestamp -UFormat '%D %R'})} | Where-Object {$query)})
    

    I see that when put in "'s it shows the command, and runs if i were to copy paste, but it just display all results, not the pipeline item in $query?

    And how can i get it to execute?

  • #76472

    Don Jones
    Keymaster

    Strings aren't automatically processed as code – they're strings. Even in double quotes with a subexpression, the result is a string, not the $True/$False that Where-Object needs to see.

    $query = {$_.passwordneverexpires -eq $true}

    Defines a script block, which is code. You could probably pass that directly to the Where-Object parameter...

    Where-Object $query

    You could possibly also use the call operator (https://ss64.com/ps/call.html) to "invoke" the string, although that's kind of a poor practice in terms of readability.

    I'll also note that in this specific example, you're probably not in an efficient model. You've already got a Where-Object clause; just do all your filtering there. And, it might be worth writing an -LdapFilter instead, for Get-ADUser, so you could do all your filtering right on the DC.

  • #76498

    Aaron
    Participant

    Thanks Don, I really appreciate the advice!

    I was able to get it after using an 'invoke-expression' cmdlet and minor altering, but you make good points on using the ldapfilter, i'll look into it.

    Thanks again!

You must be logged in to reply to this topic.