How to give a user NTFS rights to a folder, via Powershell

I'm trying to build a script that will create a folder for a new user on our file server. Then take the inherited rights away from that folder and add specific rights back in. I have it successfully adding the folder (if i give it a static entry in the script), giving domain admin rights, removing inheritance, etc...but i'm having trouble getting it to use a variable I set as the user. I don't want there to be a static user each time, I want to be able to run this script, have it ask me for a username, it then goes out and creates the folder, then gives that same user full rights to that folder based on the username i've supplied it. I can use Smithd as a user, like this:

New-Item \\fileserver\home$\Smithd –Type Directory

But can't get it to reference the user like this:

New-Item \\fileserver\home$\$username –Type Directory

Here's what i have:

Creating a new folder and setting NTFS permissions.

$username = read-host -prompt "Enter User Name"

New-Item \\\fileserver\home$\$username –Type Directory

Get-Acl \\\fileserver\home$\$username  

$acl = Get-Acl \\\fileserver\home$\$username

$acl.SetAccessRuleProtection($True, $False)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Domain\Domain Admins","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Domain\"+$username,"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)

Set-Acl \\\fileserver\home$\$username $acl

I've tried several ways to get it to work, but no luck. Any ideas or suggestions would be welcome, thanks.


Solution 1:

At my previous job, I recall being able to use the old 'mkdir' command to create folders in my powershell scripts, but to start I would suggest quoting your path and testing with an echo/write-host at first. Try this, just to test:

write-host "\\${file_server}\home$\${user_name}"

I don't have access to a Windows machine to test, but I'm guessing the '$' may also be an issue.

try this with a back-tick to try and escape the $:

write-host "\\${file_server}\home`$\${user_name}"

and don't continue, until you know that the string is to your liking. I don't think you need the -prompt in your read-host, though it's probably not an issue. write-hosting is always a nice sanity-check.

I hope to get access to a Windows machine soon so I can provide better help.

Also, if interested, you could provide the username as a parameter at the top of the program, so you can either repeatedly call the script from another that reads names from a file of $file_server, $user_name pairs. Just plop a param( [string] $file_server, [string] $user_name )

Good luck! :)