Issue with Passign a Variable

Welcome Forums General PowerShell Q&A Issue with Passign a Variable

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

4 years, 1 month ago.

  • Author
  • #23432

    Topics: 2
    Replies: 0
    Points: 0
    Rank: Member

    I am new to PowerShell, I have been enjoying building scripts. I am running windows 8.1 with PowerShell 4.0. I have ran across a issue. There is command I use to takes a user name and displays the Machines they are attached to which is

    Get-ADComputer -Filter {Managedby -eq "user123"} | Select-Object Name

    The command works great. I am starting to build a script off this command that will use the computer names for other functions. Here is my script

    function Get-UserLogonComputer
    # The enter the username for this parameter

    Get-ADComputer -Filter {Managedby -eq "$UserName"} | Select-Object Name

    Before I add any else to the script I start simple and make sure each step works When I run this script I get the following error.:
    Get-ADComputer : Identity info provided in the extended attribute: 'ManagedBy' could not be resolved. Reason: 'Cannot find an object with
    identity:"'$UserName" under: 'DC=local,DC=domain,DC=com'.'.
    At C:\TEMP\PS Scipts\UserLastPCLoggedon.ps1:37 char:5
    + Get-ADComputer -Filter {Managedby -eq "$UserName[0]"} | Select-Object Name
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Get-ADComputer], ADIdentityResolutionException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityResolutionException,Microsoft.ActiveDirec

    It looks like it is passing the name of the variable and not the value of it. Any help would be appericated.

  • #23434

    Topics: 9
    Replies: 2322
    Points: 0
    Rank: Member

    The Filter parameter on the AD cmdlets works a bit funny. They take the string representation of whatever you pass in, parse it, and do some basic variable expansion to convert it over to an LDAP filter, but not all PowerShell syntax works the way you expect it to, particularly when so many examples make it look like you're passing in a PowerShell script block.

    Try this and see if it works:

        $filters = @(
            foreach ($user in $UserName) {
                "ManagedBy -eq '$user'"
        $filter = $filters -join ' -or '
        Get-ADComputer -Filter $filter | Select-Object Name

    Because your $UserName parameter is declared as an array, I added some code to handle the case where more than one value is passed in, and I set up the code so all variable expansion is done out in the PowerShell code, rather than relying on whatever the heck it is that the AD cmdlets try to do.

The topic ‘Issue with Passign a Variable’ is closed to new replies.

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