Inserting string into command

Welcome Forums General PowerShell Q&A Inserting string into command

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

 
Participant
1 year, 9 months ago.

  • Author
    Posts
  • #76468

    Participant
    Topics: 21
    Replies: 30
    Points: 0
    Rank: Member

    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

    Keymaster
    Topics: 13
    Replies: 4872
    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    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

    Participant
    Topics: 21
    Replies: 30
    Points: 0
    Rank: Member

    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!

The topic ‘Inserting string into command’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort