Bulk folder creation

Hi & merry xmas, I need help with a bulk user creation script. I am using the import-csv cmdlet and a for each loop with new-aduser to import the new users into ad but I need to create a folder on another server, share it, set share permissions and set permissions for each user. Every user should have a folder with the same name as their login, shared as that name with a $ sign at the end and with everyone full control set on the share permission and standard permissions (inherited for that directory) plus full control permission for the user the folder is named after. Thanks to the import-csv cmdlet I have a variable that can used with for each to provide a list of folder names but am stuck on how I would go about doing this, preferably in one line / loop so to make it as efficient as possible maybe using test-path as a safety. Any ideas would be greatly appreciated. Thanks in advance
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

JAN PAKULAICT Infranstructure ManagerCommented:
I am not sure if you i get your question.

But if you are suing csvde you can do that


A) objectClass - User.  Simple and easy we want to create a user and not a computer

and not an OU.

B) sAMAccountName - This is the logon name, maximum of 11 characters.  What the

user should put in the Ctrl, Alt Delete logon box.  Keep this name simple for now.  

Remember we just want to get the prototype import working and then we can add more

LDAP fields.

C) DN - Distinguished name, for example, CN= Firstname


DN is the hardest LDAP field to create.  Let us break it down into 3 elements.

1) User name -  CN= Firstname Surname.  If it were me, the value would be  CN=Janekpakula.  In this context think of CN= as meaning common name, or just plain name.

2) Organizational name - OU=Newport.  All you have to worry about is have you

created an OU called Newport in your domain?  If not, then either create one, or

change this value to OU=YourOU.

3) Domain name - dc=domain, dc=com.  Is your domain called something like

mydom.com?  or is it plain mydom (no .com, .net or .co.uk).  It is essential to

find out what your domain is called, and only you know the answer.

So of this were your domain the third DN element would be, dc=cp,dc=com.  

Incidentally, dc stands for domain context not domain controller.







#modify attached csv to your requirements ( subfolders will be created during first

#login - just make sure that permissions on share are right
# more here : http://technet.microsoft.com/en-us/library/cc757013(WS.10).aspx
# home directory and profile path can be the same - unless you want to split it

#like me between several servers (depands on amount of users you have)

#before running it copy csv to this location c:\csvde\
#from cmd (as admin run that)

csvde –i –f c:\csvde\import.csv

#csvde doesnt suppport importing password - you have to do it later using that:

dsquery user OU=userscontainer,OU=Sirename,DC=domainname,DC=co,DC=uk | dsmod user  

-pwd somepassword1! -mustchpwd yes
Dead_EyesAuthor Commented:
Hi, sorry I probably phrased that badly. I have my script to create users and that works fine. Each user has a home drive set to N: and points to \\servername\username$\Documents. What my script does not do is create the username folder and share it, the share needs to be created user the D:\users folder on my file server. For example if I create the users sam, tim and fred. I need the script to connect to the file server, create the folders, D:\users\sam, D:\users\tim and D:\users\fred, set sam to have full control permissions on D:\users\sam set tim to have full control permissions on D:\users\tim etc. Then set the share to \\fileserver\sam$, \\fileserver\tim$ etc. and ser share permissions to everyone full control. the script needs to run from any remote machine with rsat tools installed obviously under a user with domain admin credentials. Servers are running 2012 R2 and client machines are running windows 8.1
JAN PAKULAICT Infranstructure ManagerCommented:
are these new users?
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Dead_EyesAuthor Commented:
yes they will be
JAN PAKULAICT Infranstructure ManagerCommented:
better solution would be to do that


and use windows to do this folder creation and sharing  job for you

Table 7.7  in


i would suggest to change gp slightly so you have access:
 No permissions is the default unless the Add the Administrator security group to the roaming user profile share policy setting is set, in which case the Administrators group has full control. (The Add the Administrator security group to the roaming user profile share policy setting requires Windows 2000 Service Pack 2 or later).
JAN PAKULAICT Infranstructure ManagerCommented:
i would also suggest using dfs name instead of fie server name.

when you upgrade server you just changing dfs path - users wont notice anything
Mohammed KhawajaManager - Infrastructure:  Information TechnologyCommented:
I would use PSEXEC.EXE, take a look at http://technet.microsoft.com/pl-PL/sysinternals/bb897553.aspx for more information.
Dead_EyesAuthor Commented:
Hi, sorry I can’t see how this sets folder permissions or creates folders. Also if I followed this route I would have to abandon the current layout which will probably be unacceptable to most admins who already have their system setup this way.
Mohammed KhawajaManager - Infrastructure:  Information TechnologyCommented:
Few things:

1.  Create shares using net share command (http://www.windows-commandline.com/list-create-delete-network-shares/)
2.  Set permission using CACLS.EXE  (http://support.microsoft.com/kb/135268 and http://support.microsoft.com/kb/318754)

You would still use PSEXEC.EXE to run the commands remotely on a different server.
Dead_EyesAuthor Commented:
1.) I am aware of net share but that command does not create a folder it only shares it
2.) Also aware of CACLS
3.) I need this to be powershell a script and I think Enter-PSSession replaces the need for PSEXEC in powershell
JAN PAKULAICT Infranstructure ManagerCommented:
Well this is just Microsoft best practice


you can do all that in group policy.

On the My Documents Properties page, in the Target folder location drop down box select Create a folder for each user under the root path. In the Root Path text box, type the name of the shared network folder to use, or click Browse to locate it. Note: Unlike Windows 2000, you do not need to type in the %username% variable. The folder redirection code will automatically create a My Documents folder for each user, inside a folder based on their user name. For example, type \\FolderServer\MyDocumentsFolders rather than \\FolderServer\MyDocumentsFolders\%username% as you would on Windows 2000.

Dead_EyesAuthor Commented:
I see what your saying any maybe that would be a better way of doing things but unfortunately I am stuck with the model I have been given and with a structure I don't have the authority to change so I am stuck with the need to create a script that automates folder creation and sharing
JAN PAKULAICT Infranstructure ManagerCommented:
in essence you would have to give the user ability to create folder then share it and set permissions on it using his/her username -


(i know that this is only UNC/console access)- not a "system" like with Group policy - so security goes  through the window here.

D:\users\  would still have to be shared for this to work properly  - how user tim is going to know that this folder is suppose to be created  on D:\users\ not C:\users\ (using script)

(it can be hidden share like  \\fileserver\share$\ )

so if you are creating new users folders i would strongly suggest to do it the "right way"

If you have DFS you can use  Access Based Enumeration (thick box)

so other users will never see other users folders - but admin will see them all

if you really want to go your way do that (2 scripts)

create users$ share on the server to simplify things use 7.7 table from ms (my previous posts)

First CMD

if exist "\\fileserver\users$\%USERNAME%" (
   set TEST=changed
) else (
   set TEST=needToChange

if not exist "\\fileserver\users$\%USERNAME%" md "\\fileserver\users$\%USERNAME%"

if "%TEST%"=="needToChange" (
   echo y| cacls \\fileserver\users$\%USERNAME% /t /g yourdomainname\%USERNAME%:F "yourdomainname\Domain Admins":F


second PS

#Create a single share  
     $fullSharename="\\$remote_pc\" + ($dir -replace ":","$")  
     if (create-share  -computername $remote_pc -FolderName $dir -Sharename $ShareName)  
         set-permission -fullpath $fullSharename -user "%USERDOMAIN%\%USERNAME%"  


i think :)

i haven't test it - you you will have to fiddle with it a  bit :)
Dead_EyesAuthor Commented:
Ok I have got as far as getting stuck on the second hop rule of powershell I tried a simple script to see if I could get it going. See below:
$credential = Get-Credential -Credential test\administrator
$session = New-PSSession -ComputerName WIN2K12R2SRV.test.Net -Credential $credential -Authentication Credssp

Invoke-Command -Session $session -ScriptBlock {Get-ChildItem -Path C:\testfolder | Out-File -FilePath \\rsat\c$\testresults\test.txt}

But got the following results:

New-PSSession : [WIN2K12R2SRV.test.Net] Connecting to remote server WIN2K12R2SRV.test.Net failed with the following error message : The WinRM client cannot process
the request. A computer policy does not allow the delegation of the user credentials to the target computer because the computer is not trusted. The identity of the
target computer can be verified if you configure the WSMAN service to use a valid certificate using the following command: winrm set winrm/config/service
'@{CertificateThumbprint="<thumbprint>"}'  Or you can check the Event Viewer for an event that specifies that the following SPN could not be created:
WSMAN/<computerFQDN>. If you find this event, you can manually create the SPN using setspn.exe .  If the SPN exists, but CredSSP cannot use Kerberos to validate the
identity of the target computer and you still want to allow the delegation of the user credentials to the target computer, use gpedit.msc and look at the following
policy: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Fresh Credentials with NTLM-only Server Authentication.  
Verify that it is enabled and configured with an SPN appropriate for the target computer. For example, for a target computer name "myserver.domain.com", the SPN can
be one of the following: WSMAN/myserver.domain.com or WSMAN/*.domain.com. Try the request again after these changes. For more information, see the
about_Remote_Troubleshooting Help topic.
At C:\Users\rsat\Desktop\credssp.ps1:2 char:12
+ $session = New-PSSession -ComputerName WIN2K12R2SRV.test.Net -Credential $crede ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : -2144108124,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the
command again.
At C:\Users\rsat\Desktop\credssp.ps1:4 char:25
+ Invoke-Command -Session $session -ScriptBlock {Get-ChildItem -Path C:\testfolder | Out- ...
+                         ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

Not sure I really understand what the error is trying to tell me but I know its going to be a nightmare if it starts wanting certificates
Sorry, I don't have time to write the script to fully answer your question, but if you're stuck with CredSSP I can help with that.  The two best links I've found for explaining this are

You don't need to use certificates to get this working.  Run Get-WSManCredSSP in an administrative session to see to what machines you have configured credentials to be delegated from the machine you are running the script.  Except for very targeted scenarios, usually I would suggest the results to be something like the below.
The machine is configured to allow delegating fresh credentials to the following target(s): wsman/*.somedomain.com

Open in new window

You set this by running
Enable-WSManCredSSP -role client -delegatecomputer *.domain.com

Open in new window

Dead_EyesAuthor Commented:
Hi, just reading through those articles to see what I had missed as I have run the server and client side Enable-WSManCredSSP cmdlet already. Thanks for the re-assurance about certificates :). Will let u know how I get on.
Dead_EyesAuthor Commented:
Hi unfortunately despite checking through the articles I still can't get it to work....Not sure why remoting in powershell is so damn difficult :(
Dead_EyesAuthor Commented:
I think I asked to much of one question here I am going to close the question and start smaller

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
I'll leave it to your discretion whether you want to close the question or not, but if you want you can open a new question for CredSSP and then come back to this one to continue where you left off.

Regarding PS Remoting, just wanted to clarify that PS Remoting and the use of CredSSP are two separate things (though they are complementary).  So first I would make sure that remoting is working correctly with a simple command like
invoke-command -computername comp1 -scriptblock { ipconfig }

Open in new window

then move on to getting credssp to function with ps remoting.
Sounds like you have already done the steps, but I'll lay them out anyway.  One thing that I found a little confusing for some reason when first going through this was the use of the terms "client" and "server" and which machines they would apply to.
The local host is the client, and is the machine where you would actually type the invoke-command command.  It's here that you would enter
Enable-WSManCredSSP -role client -delegatecomputer *.domain.com

Open in new window

The target machine is the server, and is the machine to which you establish the remote session and where you want to execute the scriptblock portion of the invoke-command command.  It's here that you would enter
Enable-WSManCredSSP -role server

Open in new window

If you used a FQDN (or wildcard with domain) when specifying the -delegatecomputer parameter of Enable-WSManCredSSP, remember that you have to use the FQDN when establishing the remote PS session.  Easiest test is something like
Invoke-Command -ComputerName comp1.domain.com -ScriptBlock {Test-Path \\server\share} -Authentication Credssp -Credential domain\adminuser

Open in new window

Dead_EyesAuthor Commented:
Question covered to much making people unable to help effectively
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.