Click here to Skip to main content
15,888,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am not able to add users to local administrator group when the username has space in the middle. I am reading the user name values from CSV file. Is the change need in CSV file or in Powershell script?

Thanks in Adnvance.

What I have tried:

foreach($Computer in $servers) {
    #Write-Host "We can now use the server name [$Computer] in our code"
    $Status=$null
    $Comment = $null
    $ComputerName= $servers.ComputerNM[$count]
    $Usrgroup = $servers.UserGroup  #"Here we get username"
    $ObjName = $servers.UserGroup[$count]
    $count++
    #Write-Host "ComputerName :" $ComputerName
    #Write-Host "Username :" $ObjName
    #Write-Host ("{0}. Working on {1}" -f $count, $ComputerName)
    if(Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
        Write-Verbose "$ComputerName : Online"
        try {
            $GroupObj = [ADSI]"WinNT://$ComputerName/Administrators"
            $GroupObj.Add("WinNT://$ObjDomain/$ObjName")
            $Status = "Success"
            $Comment = "Added $ObjName $ObjectType to Local administrators group on [$ComputerName]"
            Write-Verbose "Successfully added $ObjName $ObjectType to $ComputerName"
        } catch {
            $Status = "Failed"
            $Comment = $ObjectType  + "[$ObjName] - " + $_.toString().replace("`n","").replace("`r","")
            Write-Verbose "Failed to add $ObjName $ObjectType to $ComputerName"
        }
        Add-Content -Path $ResultsFile -Value ("{0},{1},{2}" -f $ComputerName,$Status,$Comment )   

    } else {
        Write-Warning "$ComputerName : Offline"
        Add-Content -Path $ResultsFile -Value ("{0},{1}" -f $ComputerName,"Offline")
    }



---This is my csv format---

ComputerNM || UserGroup
========================
dev || Harry
dev || James Horner --->this one not adding
Posted
Updated 28-Mar-19 5:23am

When a username has spaces within it, PowerShell needs the username to be wrapped within quotation marks.

Here are a couple of Q/As I found with Google, these should be able to get you aimed in the right direction on how to solve your issue:
1. [SOLVED] Powershell Get-ADUser, User with space in username give an error - Spiceworks[^]
2. powershell - Handling names with spaces - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900