简体   繁体   中英

Force Powershell to create AD user folder when setting HomeDirectory value

During the New-ADUser command: -HomeDirectory = '\sharedrive\folder$%username%'

When this value is set in Powershell, the value appears as \\sharedrive\usersfolder$\%username% under the Home Directory.

Result:
它看起来像这样。

However, if I manually enter that same string into the Active Directory Users and Computers menu and then hit apply, it autofills to the person's username where %username% exists and creates a folder on that share drive with proper permissions, shown below:

这是应用后的样子。

How can I get Powershell to autofill this username and create the folder? Just writing the string out with the user's name does not work.

I think there are a couple of problems here. PowerShell doesn't know how to interpret your input string '\sharedrive\folder$%username%'

For one, it is a literal string - so even if PowerShell knew that $%username% meant "convert this value to the username environment variable" it would still interpret it as the literal characters entered in the string. What you're appearing to try and do is string interpolation which requires that you use double quotes " .

Second, the %username% portion is not the way that you use environment variables in PowerShell. There are a few ways to get this value. $env:USERNAME should work on windows, so would [Environment]::username .

So you would want to do something like this "\sharedrive\folder$([Environment]::username)"

for a user 'someuser' this would return "\sharedrive\foldersomeuser"

Try something like this:

$NewUser = Read-Host "please enter a username"
New-ADUser -Name "$NewUser" -HomeDirectory "\sharedrive\folder\$NewUser"

Btw Efie is absolutely right about how environment variables are being passed, but the other thing is that those variables he mentioned will be the variables of whomever is running the script, not the user you are creating.

You're confusing both environment variables AND how these values are set in ADUC and when using Powershell cmdlets.

%username% is a Windows environment variable which can be translated, thus when you hit the "Apply" button the ADUC console translates the username from the account you're creating, then in the background goes and creates that folder using the credentials of whoever is running ADUC, then (if you hit the "Yes" button) also repermissions it to give that user Full Control .

Once again its the ADUC which creates the folder for you, it doesn't happen just because you set those properties on the account object. If you want Powershell to do this then you need to carry out the folder creation and permissioning yourself, either manually or via more Powershell scripting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM