1
votes

I am fairly new to powershell and I am currently employing it to work around a few administration tasks for the Helpdesk.

I have a problem with trying to move an AD object (forgive me if the following terminology is used incorrectly) based on the property of on object from an imported CSV.

The CSV is: UserPrincipalname,UserToAccess,DaysToLive

[email protected],[email protected],90

and so on...

I then pass the array through a ForEach loop to move the AD account:

foreach ($line in $import) {Get-ADUser -filter {userPrincipalName -eq $_.UserToAccess} -SearchBase "DistinguishedName of OU" | Move-ADObject -TargetPath 'DistinguishedName of OU'}

Subsequently I am getting the following error:

Get-ADUser : Variable: '' found in expression: $.UserToAccess is not defined. At D:\jason\EnableArchiveAccess.ps1:17 char:29 + foreach ($line in $import) {Get-ADUser -filter {userPrincipalName -eq $.UserToA ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException + FullyQualifiedErrorId : Variable: '' found in expression: $_.UserToAccess is not defined.,Microsoft.ActiveDirec
tory.Management.Commands.GetADUser

I have been able to use the above logic to unhide users from the GAL and I have checked the array and the properties are there as noteproperties.

I assume it's because I am using not AD variables in the command but any help would be much appreciated but if I find the answer sooner I will post back.

3

3 Answers

4
votes

Just looking at that, I think you need to change

$_.UserToAccess

to

$line.UserToAccess
1
votes

The other alternative would be:

$import | foreach{
  Get-ADUser -filter {userPrincipalName -eq $_.UserToAccess} `
  -SearchBase "DistinguishedName of OU" `
  | Move-ADObject -TargetPath 'DistinguishedName of OU'}
0
votes

This is one of the common mixups in PowerShell. There are in fact two foreach "keywords". One is alias of the Foreach-Object cmdlet and is used as such:

$Items = 1,2,3
$Items | foreach { $_ }

The $_ in the example means the current object. That is 1 on first pass, 2 on second pass and 3 on the third.

The second foreach is keyword and is used as such

$Items = 1,2,3
foreach ($item in $items) {
    $item
}

In this example the $item represents the current object.

So in your example you have to use $list instead of $_.