Issue with Passign a Variable

Hello,
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
{
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact=‘Low’)]
Param
(
# The enter the username for this parameter
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
Position=0)]
[string]$UserName
)

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

}

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: (:slight_smile: [Get-ADComputer], ADIdentityResolutionException
    • FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityResolutionException,Microsoft.ActiveDirec
      tory.Management.Commands.GetADComputer

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

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:

Process
{
    $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.