problem in Get-Aduser

Hi friends

i have lost my patiense & i will cry.

it's about 1 hour that i am struggling with a simple issu.

in my domain i have 3 users called u1, u2, u3    both names & samAccount names are same for each user.

when i run 

PS C:\> Get-Aduser -filter {name -eq "u1"}   ----> it works

but followings doesn't work & show no output:

$i = 1

PS C:\> Get-Aduser -filter {name -eq "u$i"}   ----> no result (nothing is shown in output)

a Guy said: " PowerShell won't resolve the variable name inside a scriptblock.  You have to define you're username outside and then use the variable"

but the problem is, without -filter, if the command checks the existence of an object in AD & in case that object is not present, it produces the error.

let me clarify:

i am writing a function that checks the existence of say these 3 users in AD database & if they don't exist in AD, (without getting the error which describes "object not found"), creates them.

for ($i = 1; $i -le 3; $i++){ 
     if (!(Get-ADUser -Filter {name -eq "u$i"})) {New-ADuser -name "u$i"} 
     }

#if we don't use script block , i will get a terminating error & the code won't continue:
 
   for ($i = 1; $i -le 3; $i++){ 
      if (!(Get-ADUser "u$i")) {New-ADuser -name "u$i"} 
     }

Get-ADUser : Cannot find an object with identity: 'u1' under: 'DC=HP,DC=lab'.

At C:\Users\Administrator\Desktop\Untitled2.ps1:2 char:13

+       if (!(Get-ADUser "u$i")) {New-ADuser -name "u$i"}

+             ~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (u1:ADUser) [Get-ADUser], ADIdentityNotFoundException

    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNo 

   tFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

 

The '++' operator works only on numbers. The operand is a 'System.String'.

At C:\Users\Administrator\Desktop\Untitled2.ps1:1 char:27

+    for ($i = 1; $i -le 3; $i++){

+                           ~~~~

    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException

    + FullyQualifiedErrorId : OperatorRequiresNumber





March 8th, 2015 1:30am

Your string concatenations must be done properly. 


Free Windows Admin Tool Kit Click here and download it now
March 8th, 2015 3:09am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics