Search code examples
powershellactive-directorypowershell-4.0

Using property names from a CSV in foreach


I am trying to import a CSV containing information on a large amount of users and computers. I am using this CSV to build my Active Directory. I am trying to build the computers and am having an issue with the foreach loops and I believe I may be misunderstanding them. Here is the relevant section of my code:

$adusercsv = Import-CSV .\tst.csv
foreach ($_.computername in $adusercsv)
{
    if ($_.city -eq "Vancouver")
    {
        New-ADComputer -Name $_.computername -Path OU=Computers,OU=Vancouver,DC=VANDC
    }
    if ($_.city -eq "Calgary")
    {
        New-ADComputer -Name $_.computername -Path OU=Computers,OU=Calgary,DC=InternalCAL
    }
}

This code throws the syntax error:

At line:21 char:12
+ foreach ($_.computername in $adusercsv)
+            ~
Missing 'in' after variable in foreach loop.
At line:21 char:39
+ foreach ($_.computername in $adusercsv)
+                                       ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingInInForeach

How do I read each line from the array?


Solution

  • First off, the $_ is the default variable representing the current object in the pipeline. You are trying to assign the current computer to the computername property of an undefined variable... try this instead

    $OUs = @{
        Vancouver = 'OU=Computers,OU=Vancouver,DC=VANDC'
        Calgary = 'OU=Computers,OU=Calgary,DC=InternalCal'
    }
    $aduserscsv = Import-CSV .\tst.csv
    foreach ($row in $aduserscsv) {
            New-ADComputer -Name $row.Computername -path $OUs.($row.city)
    }
    

    This has no error checking in, which would be advisable, but it demonstrates how you use the foreach (){} loop and how you don't need to check the property of the city if your values are in your source data