0
votes

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?

3

3 Answers

1
votes

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

0
votes

$_ is used for the current value in the pipeline. In this case, you should not use it.

Try this out:

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

Have a look on this page for an example.

You can try like this :

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