foreach and out-file- no data

Occasional Contributor

Hi,

I need to return  a list of active users:  Display name etc. but no data is exported to my out-file. Any clues would be highly appreciated . Thanks

 

 

$users = Get-Content "C:\dump\usernames2.txt"
foreach ($user in $users)
{
if (Get-ADUser -ldapfilter "(samaccountname=$user)" -Properties displayname,mail,distinguishedName | Select-Object -Property displayname,mail,distinguishedName)
{
out-file "c:\dump\usersexist.txt"
}
else
{
Add-Content "C:\dump\namenotfound.txt" "$user"
}
}

 

I

 

4 Replies
I see you are using the -ldapfilter filter and then labeling a SamAcountName.

Assuming you are piping in the SamAcountName.
Try Get -ADUser -identity $_.$User

yes, the file contains SamAccountNames

I tried the -identity para but received the error below

Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and
then try running the command again.
At line:4 char:26
+ if (Get-ADUser -identity ($_.$User) -Properties displayname,mail,dist ...
+ ~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and
then try running the command again.
At line:4 char:26
+ if (Get-ADUser -identity ($_.$User) -Properties displayname,mail,dist ...
+ ~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

I would always display my output first to be sure I was getting something returned to the console.
Then write the output to a file.

@DarrenRD 

Hi

What are you expecting from the out-file, where is the inputObject, at least you will need to pipeline it with another command.

if you are talking about dumping the console output to a file, then this is a console redirection, read about it here.

anyway

 

 

 

$users = Get-Content "C:\usernames2.txt"
foreach ($user in $users)
{
try{
    $Value=Get-ADUser -ldapfilter "(samaccountname=$user)" -Properties displayname,mail,distinguishedName -ErrorAction stop| Select-Object -Property displayname,mail,distinguishedName 
    if ($Value.count -eq 0){
        Add-Content "C:\namenotfound.txt" "$($user)"
        }
        else{

    add-Content -Path 'C:\UserFound.txt' -Value $Value 
    }
}
catch{
Write-Host $_.exception.message

}
}

 

 

 

Check the code above