Hello,

So right off the bat I have basically zero experience with powershell either ran running scripts with it that have already been written and tested. I am using a script that grabs student info from a .csv and adds to a OU in AD. here is the script:

----------------------------------------------------------Beginning------------------------------------------------------------------

#Import the PowerShell module containing AD cmdlets
Import-Module ActiveDirectory

write-host “Start Process”
write-host “-------------------------------------”
try
{
#Read the CSV file
$csvPath = “C:\AD_StudentImport\AD_StudentImport.csv”
$csvData = import-csv $csvPath

write-host “Reading the CSV file…”

#Loop through all items in the CSV items
ForEach ($user In $csvData)
{
$saMAccountName = $user.username

#Check if the User exists
$ADuser = Get-ADUser -LDAPFilter “(sAMAccountName=$saMAccountName)”

If ($ADuser -eq $Null)
{
#Create user using New-ADUser cmdlet
$path = ‘OU=Students,DC=iticlassroom,DC=com’
$userPrincipalName = $user.userName + “@iticlassroom.com
$FullName = $user.firstname + " " + $user.lastname
$ScriptPath = “default” + $user.Program + “.bat”
$HomeDirectory = "\martin-fs1\users" + $user.userName

if ($user.Program -eq “AC”)
{
$program = “Air Conditioning”
}

if ($user.Program -eq “INSTR”)
{
$program = “Instrumentation”
}

if ($user.Program -eq “PTECH”)
{
$program = “Process Technology”
}

if ($user.Program -eq “DRAFT”)
{
$program = “Drafting And Design”
}

if ($user.Program -eq “ELECTRIC”)
{
$program = “Instrumentation”
}

if ($user.Program -eq “ELECTRON”)
{
$program = “Instrumentation”
}

if ($user.Program -eq “IT”)
{
$description = “Process Technology”
}

if ($user.Program -eq “MC”)
{
$description = “Drafting And Design”
}

if ($user.Program -eq “OA”)
{
$program = “Process Technology”
}

if ($user.Program -eq “MA”)
{
$program = “Drafting And Design”
}

if ($user.Program -eq “CNST-MGT”)
{
$program = “Construction Management”
}

New-ADUser -Name $saMAccountName -SamAccountName $saMAccountName
-UserPrincipalName $userPrincipalName -GivenName $user.firstname
-Surname $user.lastname -Description $user.stunum
-DisplayName $FullName -EmailAddress $user.EmailLogin
-AccountPassword (ConvertTo-SecureString $user.password -AsPlainText -Force) -Path $path
-ScriptPath $ScriptPath -HomeDirectory $HomeDirectory
-HomeDrive “H:” -Enabled $true
-OtherAttributes @{‘cvProgram’=$program;‘cvStuNum’=$user.stunum;‘cvSyStudentID’=$user.systudentid}

Adding User to Group

Add-ADGroupMember -Identity Students -Members $user.userName

#Set Password to never expire
set-aduser -identity $saMAccountName -PasswordNeverExpires $true

#Check if the User exists
$ADuser = Get-ADUser -LDAPFilter “(sAMAccountName=$saMAccountName)”

if ($ADuser -ne $Null)
{
write-host "- " $user.userName “|Account Created & Added to Students Group” -ForegroundColor green
}

else
{
write-host “WTF!!!” $user.userName -ForegroundColor red
}
}

else
{
write-host "- " $user.userName “|Account Exists” -ForegroundColor yellow
}

if ($user.Program -eq ‘IT’)
{
try
{
Add-ADGroupMember -Identity AdminRights -Member $user.userName
write-host “Student Added to AdminRights Group” -ForegroundColor green
}

catch
{
write-host “Student Already a member of AdminRights Group” -ForegroundColor yellow
}
}

else
{

}

if ($user.Program -eq ‘OA’)
{
try
{
Add-ADGroupMember -Identity AdminRights -Member $user.userName
write-host “Student Added to AdminRights Group” -ForegroundColor green
}

catch
{
write-host “Student Already a member of AdminRights Group” -ForegroundColor yellow
}
}

else
{

}

if ($user.Program -eq ‘DRAFT’)
{
try
{
Add-ADGroupMember -Identity AdminRights -Member $user.userName
write-host “Student Added to AdminRights Group” -ForegroundColor green
}

catch
{
write-host “Student Already a member of AdminRights Group” -ForegroundColor yellow
}
}

else
{

}

if ($user.Program -eq ‘MC’)
{
try
{
Add-ADGroupMember -Identity AdminRights -Member $user.userName
write-host “Student Added to AdminRights Group” -ForegroundColor green
}

catch
{
write-host “Student Already a member of AdminRights Group” -ForegroundColor yellow
}
}

else
{

}

$homeDir = "\martin-fs1\Users"
$sso = $user.userName

If the folder for the user does not exist, make a new one and set the correct permissions.

if ( (Test-Path “$homeDir$sso”) -eq $false)
{
$NewFolder = New-Item -Path $homeDir -Name $sso -ItemType “Directory”
$Rights = [System.Security.AccessControl.FileSystemRights]“FullControl,Modify,ReadAndExecute,ListDirectory,Read,Write”
$InheritanceFlag = @([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount “itimartin.com$sso”
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$ACL = Get-Acl -Path $NewFolder
$ACL.AddAccessRule($objACE)
Set-ACL -Path $NewFolder.FullName -AclObject $ACL

if ( (Test-Path “$homeDir$sso”) -eq $true)
{
write-host “Directory” “$homeDir$sso” “Created” -ForegroundColor green
}

else
{
write-host “WTF!!!” “$homeDir$sso” -ForegroundColor red
}
}

else
{
write-host “Directory” “$homeDir$sso” “Already Exists” -ForegroundColor yellow
}
}
}

catch
{
write-host "Error: " $($.CategoryInfo) -ForegroundColor red
write-host "Message: " $($
.Exception.Message) -ForegroundColor red
}

write-host “-----------------------------------------------------------------”
write-host “End Process”

------------------------------------------------------------End-----------------------------------------------------------------------

The error I receive is this:

----------------------------------------------------------Beginning------------------------------------------------------------------

Error: InvalidOperation: (CN=cdeaton01655…lassroom,DC=com:String) [New-ADUser], ADInvalidOperationException
Message: The parameter is incorrect

------------------------------------------------------------End-----------------------------------------------------------------------

Any and all help greatly appreciated

3 Spice ups

Is this the full OU path? Is Students a part of an OU?

$path = ‘OU=Students,DC=iticlassroom,DC=com’

Also try using splatting instead of back tics in the New-ADUser block.

Please use the </> button to post your script in a format that is easier to read than plain text.

Also, please read this article about guidelines for posting:

Can you post the full error message? Usually it includes the line where the error occurred and the command that caused the error.

Hello Crapula, to answer both questions correct and correct. The DC is iticlassroom.com and the OU is Students.and just so I know that I have this splatting thing right you mentioned, it would look like this?
= <OU=Students> <DC=iticlassroom> <DC=com>

The error appears to be from the New-ADUser command. Backticks ` to continue a command on a new line are not recommended. Splatting is a better practice.

$Arguments = @{
    Name = $saMAccountName
    SamAccountName = $saMAccountName
    UserPrincipalName = $userPrincipalName
    GivenName = $user.firstname
    Surname = $user.lastname
    Description = $user.stunum
    DisplayName = $FullName
    EmailAddress = $user.EmailLogin
    AccountPassword = (ConvertTo-SecureString $user.password -AsPlainText -Force)
    Path = $path
    ScriptPath = $ScriptPath
    HomeDirectory = $HomeDirectory
    HomeDrive = "H:"
    Enabled = $true
     OtherAttribute=@{'cvProgram'=$program;'cvStuNum'=$user.stunum;'cvSyStudentID'=$user.systudentid}
}
New-ADUser @Arguments
2 Spice ups
#Import the PowerShell module containing AD cmdlets
Import-Module ActiveDirectory

write-host "Start Process"
write-host "-------------------------------------"
try
{
    #Read the CSV file
    $csvPath = "C:\AD_StudentImport\AD_StudentImport.csv"
    $csvData = import-csv $csvPath

    write-host "Reading the CSV file......"

    #Loop through all items in the CSV items
    ForEach ($user In $csvData)
    {
        $saMAccountName = $user.username

        #Check if the User exists
        $ADuser = Get-ADUser -LDAPFilter "(sAMAccountName=$saMAccountName)"

        If ($ADuser -eq $Null)
        {
            #Create user using New-ADUser cmdlet
            $path = 'OU=Students,DC=iticlassroom,DC=com'
            $userPrincipalName =  $user.userName + "@iticlassroom.com"
            $FullName = $user.firstname + " " + $user.lastname
            $ScriptPath = "default" + $user.Program + ".bat"
            $HomeDirectory = "\\martin-fs1\users\" + $user.userName
            
            if ($user.Program -eq "AC")
            {
                $program = “Air Conditioning”
            }
            
            if ($user.Program -eq "INSTR")
            {
                $program = “Instrumentation”
            }
            
            if ($user.Program -eq "PTECH")
            {
                $program = “Process Technology”
            }
            
            if ($user.Program -eq "DRAFT")
            {
                $program = “Drafting And Design”
            }
            
            if ($user.Program -eq "ELECTRIC")
            {
                $program = “Instrumentation”
            }
            
            if ($user.Program -eq "ELECTRON")
            {
                $program = “Instrumentation”
            }
            
            if ($user.Program -eq "IT")
            {
                $description = “Process Technology”
            }
            
            if ($user.Program -eq "MC")
            {
                $description = “Drafting And Design”
            }
            
            if ($user.Program -eq "OA")
            {
                $program = “Process Technology”
            }
            
            if ($user.Program -eq "MA")
            {
                $program = “Drafting And Design”
            }
            
            if ($user.Program -eq "CNST-MGT")
            {
                $program = “Construction Management”
            }

            New-ADUser -Name $saMAccountName `
                -SamAccountName $saMAccountName `
                -UserPrincipalName $userPrincipalName `
                -GivenName $user.firstname `
                -Surname $user.lastname `
                -Description $user.stunum `
                -DisplayName $FullName `
                -EmailAddress $user.EmailLogin `
                -AccountPassword (ConvertTo-SecureString $user.password -AsPlainText -Force) `
                -Path $path `
                -ScriptPath $ScriptPath `
                -HomeDirectory $HomeDirectory `
                -HomeDrive "H:" `
                -Enabled $true `
                -OtherAttributes @{'cvProgram'=$program;'cvStuNum'=$user.stunum;'cvSyStudentID'=$user.systudentid}

            # Adding User to Group
            Add-ADGroupMember -Identity Students -Members $user.userName

            #Set Password to never expire
            set-aduser -identity $saMAccountName -PasswordNeverExpires $true
            
            
            
            #Check if the User exists
            $ADuser = Get-ADUser -LDAPFilter "(sAMAccountName=$saMAccountName)"

            if ($ADuser -ne $Null)
            {
                write-host "- " $user.userName "|Account Created & Added to Students Group" -ForegroundColor green
            }
            
            else
            {
                write-host "WTF!!!" $user.userName -ForegroundColor red
            }
        }

        else
        {
            write-host "- " $user.userName "|Account Exists" -ForegroundColor yellow
        }
        
        if ($user.Program -eq 'IT')
        {
            try
            {
                Add-ADGroupMember -Identity AdminRights -Member $user.userName
                write-host "Student Added to AdminRights Group" -ForegroundColor green
            }
            
            catch
            {
                write-host "Student Already a member of AdminRights Group" -ForegroundColor yellow
            }
        }
            
        else
        {
            
        }
        
        if ($user.Program -eq 'OA')
        {
            try
            {
                Add-ADGroupMember -Identity AdminRights -Member $user.userName
                write-host "Student Added to AdminRights Group" -ForegroundColor green
            }
            
            catch
            {
                write-host "Student Already a member of AdminRights Group" -ForegroundColor yellow
            }
        }
            
        else
        {
            
        }
        
        if ($user.Program -eq 'DRAFT')
        {
            try
            {
                Add-ADGroupMember -Identity AdminRights -Member $user.userName
                write-host "Student Added to AdminRights Group" -ForegroundColor green
            }
            
            catch
            {
                write-host "Student Already a member of AdminRights Group" -ForegroundColor yellow
            }
        }
            
        else
        {
            
        }
        
        if ($user.Program -eq 'MC')
        {
            try
            {
                Add-ADGroupMember -Identity AdminRights -Member $user.userName
                write-host "Student Added to AdminRights Group" -ForegroundColor green
            }
            
            catch
            {
                write-host "Student Already a member of AdminRights Group" -ForegroundColor yellow
            }
        }
            
        else
        {
            
        }
        
        $homeDir = "\\martin-fs1\Users\"
        $sso = $user.userName
        
        # If the folder for the user does not exist, make a new one and set the correct permissions.
        if ( (Test-Path "$homeDir$sso") -eq $false)
        {
            $NewFolder = New-Item -Path $homeDir -Name $sso -ItemType "Directory"
            $Rights = [System.Security.AccessControl.FileSystemRights]"FullControl,Modify,ReadAndExecute,ListDirectory,Read,Write"
            $InheritanceFlag = @([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
            $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
            $objType =[System.Security.AccessControl.AccessControlType]::Allow
            $objUser = New-Object System.Security.Principal.NTAccount "itimartin.com\$sso"
            $objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
                    ($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
            $ACL = Get-Acl -Path $NewFolder
            $ACL.AddAccessRule($objACE)
            Set-ACL -Path $NewFolder.FullName -AclObject $ACL
            
            if ( (Test-Path "$homeDir$sso") -eq $true)
            {
                write-host "Directory" "$homeDir$sso" "Created" -ForegroundColor green
            }
            
            else
            {
                write-host "WTF!!!" "$homeDir$sso" -ForegroundColor red
            }
        }
        
        else
        {
            write-host "Directory" "$homeDir$sso" "Already Exists" -ForegroundColor yellow
        }
    }
}

catch
{
    write-host "Error: "  $($_.CategoryInfo) -ForegroundColor red
    write-host "Message: " $($_.Exception.Message) -ForegroundColor red
}

write-host "-----------------------------------------------------------------"
write-host "End Process"

Sorry about the plain text, and as for the “splatting” I’m not sure how to implament that in the current code. Will it work if I just replace the current ( #Create user using New-ADUser cmdlet) section?

See my example of splatting above.

1 Spice up

Splatting is a technique where you pass parameters to a commandlet in a collection (hashtable, array, etc.) rather than using switches. This is done to improve readability and code reuse.

# This is the traditional way, hard to read
Get-ChildItem -Path "\\server\share\folder\subfolder\yet anothe subfolder" -Include "*.pdf", "*.docx" -Filter "*report*" -File -Recurse

# splatting, much nicer
$options = @{
    Path    = "\\server\share\folder\subfolder\yet anothe subfolder"
    Include = "*.pdf", "*.docx"
    Filter  = "*report*" 
    File    = $true 
    Recurse = $true
}
Get-ChildItem @options
1 Spice up

Looking at the script there are several errors and areas for improvement.

A glaring issue is that long string of IFs to set a single variable value, $program. That is what switch statements are for. there are also a couple of cases where $description is set instead, which is never used in the rest of the script:

if ($user.Program -eq "ELECTRON") {
    $program = “Instrumentation”
}
            
if ($user.Program -eq "IT") {
    $description = “Process Technology”
}
            
if ($user.Program -eq "MC") {
    $description = “Drafting And Design”
}

So, when a student is in IT or MC their program get sets to a previous value.

There is also the incorrect use of try-catch.

Plus whatever editor you used to post the script uses “smart” or typographical quotes. Never a good idea when working with code. I suggest you stick to Visual Studio Code with the official PowerShell plugin.

1 Spice up

Thanks for the great advice I will work on all these things, downloading visual studio code now.

Glad you got some inspiration. VS Code rocks!

And in future, please do not post such long scripts here. At 250 lines this is excessive;.

Here is a snippet showing how much more readable code can be when you use the appropiate language construct.

$program = switch ($user.Program) {    
    "AC" { "Air Conditioning" }
    "INSTR" { "Instrumentation" }
    "PTECH" { "Process Technology" }
    "DRAFT" { "Drafting And Design" }
    "ELECTRIC" { "Instrumentation" }
    "ELECTRON" { "Instrumentation" }
    "IT" { "Process Technology" }
    "MC" { "Drafting And Design" }
    "OA" { "Process Technology" }
    "MA" { "Drafting And Design" }
    "CNST-MGT" { "Construction Management" }
    default {$user.Program}
}

54 lines became 14.

I also included a default case so that programs missing from the switch statement still have a meaningful value.