I am trying to import multiple user accounts from a csv file into powershell script. The script is running, but i do not see any added useres under the OU i created in AD. I do get an error message when running the script: "The seach filter cannot be recognized". What can be the error here?
Update: The script is now updated after the comment tips.
Import-Module activeDirectory
$csvpath = $PSScriptRoot + "\produksjonsbrukereImport.csv"
if (Test-Path $csvpath) {
$csvpath = "C:\script\produksjonsbrukereImport.csv"
$csv = Import-Csv -Delimiter "," -Path $csvpath -Encoding UTF7
$OUBasePath = ",OU=Produksjon,OU=OpMeis,DC=OpMeis,DC=local"
$logpath = "$PSScriptRoot\import-brukere-loggfil.txt"
}
foreach ($line in $csv) {
#Lagrer variabler
$fornavn = $line.fornavn
$etternavn = $line.etternavn
#$navn = ($fornavn + " " + $etternavn)
$beskrivelse = $line.beskrivelse
$passord = $line.Passord
$avdeling = $line.avdeling
#$brukernavn = ($fornavn.Substring(0,3) + $etternavn.Substring(0,3)).tolower()
$brukernavn = $brukernavn -replace "æ", "a"
$brukernavn = $brukernavn -replace "å", "a"
$brukernavn = $brukernavn -replace "ø", "o"
$principal = $brukernavn + "@OpMeis.local"
$profPath = ($profBasePath + $brukernavn)
$profPathTrue = $profPath + ".V2"
#Genererer OU-path basert på avdelingsnavn
$OU = ("OU=" + $avdeling + $OUBasePath)
}
if (!(get-aduser -Filter {sAMAccountName -eq $brukernavn})) {
$logg = "Forsøker å legge til bruker for $navn - brukernavn: $brukernavn, passord: $passord, avdeling: $avdeling"
#Skriver til skjerm og lagrer i loggfil
Write-Host $logg
try {
New-ADUser -Name $navn -GivenName $fornavn `
-Surname $etternavn –DisplayName $navn `
-sAMAccountName $brukernavn `
-Description $beskrivelse -Path $OU `
-AccountPassword (ConvertTo-SecureString $passord -AsPlainText -Force) -Enabled $true `
-ChangePasswordAtLogon $true `
-UserPrincipalName $principal `
# -ProfilePath $profPath `
-Passthru | Out-file -FilePath $logpath -Append
Start-Sleep -Milliseconds 500
ADD-ADGroupMember (“G_” + $line.avdeling) –members $brukernavn
Start-Sleep -Milliseconds 100
$logg | Out-File -FilePath $logpath -Append
Write-Host "Bruker: $brukernavn lagt til i AD"
$logg | Out-File -FilePath $logpath -Append
Write-Host "Bruker: $brukernavn lagt til i AD"
} #END TRY
#Ved feil, skriv til loggfil
catch {
$ErrorMessage = $_.Exception.Message | Out-File -FilePath $logpath -Append
$FailedItem = $_.Exception.ItemName | Out-File -FilePath $logpath -Append
}
}