使用New-ADUser创建AD用户时,无法拼接名称与域名的问题求助
Let's work through the problems in your PowerShell script and get those AD users created correctly.
First, let's spot the immediate syntax errors that might be throwing you off (and possibly making you think the UPN拼接 is broken when it's not):
1. DisplayName Variable Syntax Error
Your current DisplayName line has invalid variable referencing:
-DisplayName "$($_.givenname $_.surname)"
PowerShell can't parse two variables stuck together like that. You need to separate them with a space (either inside the string or via explicit concatenation):
-DisplayName "$($_.givenname) $($_.surname)" # OR -DisplayName "$($_.givenname + ' ' + $_.surname)"
2. UPN拼接 Validation
Your UPN format ("{0}@{1}" -f $_.name,"Dev.domain.Net") is actually syntactically correct. If you're still having issues with it, check these points:
- Ensure the
namefield in your CSV has no unexpected characters (spaces, special symbols) that would break the UPN format. - Verify that
Dev.domain.Netis a valid UPN suffix configured in your AD domain (check Domain Properties > UPN Suffixes in Active Directory Domains and Trusts).
Corrected Full Script
Here's the fixed version of your code, with better readability and resolved syntax issues:
Import-Csv "c:\output.csv" | ForEach-Object { New-ADUser -Name $_.name ` -UserPrincipalName ("{0}@{1}" -f $_.name,"Dev.domain.Net") ` -DisplayName "$($_.givenname) $($_.surname)" ` -GivenName $_.givenname ` -Surname $_.surname ` -Path "OU=Workspaces,DC=Dev,DC=domain,DC=Net" ` -AccountPassword (ConvertTo-SecureString "passs" -AsPlainText -Force) ` -Enabled $true }
Notes on the fixes:
- Added spaces between
givennameandsurnamein the DisplayName field - Used backticks (`) to split the command across lines for readability
- Completed the
-Enabledparameter with a valid boolean value ($true)
Additional Troubleshooting Tips
- Double-check your CSV path and ensure the
namecolumn has no empty values - Confirm the account running the script has permissions to create users in the
OU=WorkspacesOU - Test with a single CSV entry first to isolate any remaining issues
内容的提问来源于stack exchange,提问作者Milister

