I wrote a script to create a new folder based on some company variables and later on add a group with users to handle the permissions on this folder.
I can not find a decent way to add one, or more, AD groups to a folder in the same script.
Here is my script:
$parentfolder = Read-Host -Prompt "Please enter the name of the parent folder (i.e. FOLDER1234)"
$folder = Read-Host -Prompt "Please enter the name of the new network folder"
New-Item \\DC02\product\$parentfolder\$folder -type directory
Write-Host "Folder has been created!"
Start-Sleep -s 2
$newgroup = Read-Host -Prompt "Please enter the new group name for this folder (1234-1234-12xx format)"
$description = Read-Host -Prompt "Please enter the abbreviation of the product (i.e. PDPROD)"
NEW-ADGroup -Name $newgroup -GroupScope Global -Description $description -Path "OU=Project Groups,DC=ourdomain,DC=nl"
do {
$stringquit = Read-Host -Prompt "Please enter the member username's to add or press Q if you are done."
$userfilter3 = Get-ADUser -Filter {sAMAccountName -eq $stringquit}
if ($userfilter3 -eq $Null,"Q") {
Write-Host = "User does not exist in AD, please try again"
Start-Sleep -s 1
} else {
if ($stringquit -ne "Q") {
Write-Output -InputObject $stringquit | Out-File -Append c:\userlist.csv
} else {
Write-Host "You pressed Q, moving on."
}
}
} until ($stringquit -eq "Q")
$addgroup = "cn=$newgroup,ou=Project Groups,dc=ourdomain,dc=nl"
$list = Get-Content c:\userlist.csv
foreach ($user in $list) {
Add-ADGroupMember -Identity $addgroup -Member $user
}
#set permissions
$acl = Get-Acl \\DC02\product\$parentfolder\$folder
$ar = New-Object System.Security.AccessControl.FileSystemAccessRule("1234-all","Modify"."ContainerInherit,ObjectInherit","None","Allow")
$acl.SetAccessRule($ar)
Set-Acl \\DC02\product\$parentfolder\$folder $acl
Replace SetAccessRule() with AddAccessRule().
Related
1st I want to create a folder then make it a shared folder and last I want to give different permissions for different users to the shared folder on Windows 7 PowerShell v2.0.
The other functions are working but Adding share permission function not working. I looked up and found that share permissions can be given while creating a shared folder but I want to add other users too.
Also, I've looked Shared folder permission!
Powershell, how to add permission to shared folder
Permissions on shared folder with PowerShell
powershell share permission level on a folder
cls
function CreateSharedFolder{
$FolderName = Read-Host "Enter Folder Name"
$SharedFolderName = Read-Host "Enter Shared Folder Name[Default same as Folder Name]"
if(!$SharedFolderName){
$SharedFolderName = $FolderName
}
$CheckSharedFolderExists = Get-WmiObject Win32_Share -filter "name='$SharedFolderName'" -ErrorAction SilentlyContinue
if($CheckSharedFolderExists){
Write-Host "Duplicate Share. Shared Folder with this name already exists" -ForegroundColor Red
break
}
else{
Write-Host "No Existing Shared Folder Found with this name" -ForegroundColor Green
}
$FolderPath = Read-Host "Enter Folder Path[Default current path/location]"
if(!$FolderPath){
$ParentDirectoryPath = Get-Location
$FolderPath = Join-Path $ParentDirectoryPath $FolderName
}
$CheckFolderExists = Test-Path -Path $FolderPath
if($CheckFolderExists){
Write-Host "Folder with this name already exists"
$UserInput = Read-Host "Do you want to make shared Folder? [y]Yes [n]No[Default]"
if($UserInput -ne "y"){
Write-Host "You selected NO"
break
}
}
else{
$NewFolder = New-Item -Path $FolderPath -type Directory
Write-Host "Creating New folder ..." -ForegroundColor Green
}
$Shares = [WMICLASS]"Win32_Share"
$createShare = $Shares.Create($FolderPath, $SharedFolderName, 0)
switch($createShare.ReturnValue){
0{
Write-Host "Shared folder created successfully" -ForegroundColor Green
}
1{
}
}
$SharedFolderExists = Get-WmiObject Win32_Share -filter "name='$SharedFolderName'" -ErrorAction SilentlyContinue
# $sharedFolderExists
if($SharedFolderExists){
Write-Host "Shared folder exists" -ForegroundColor Green
}else{
Write-Host "Shared Folder does not exists " -ForegroundColor Red
}
}
function Get-ListofSharedFolder{
$SharedFolders = Get-WmiObject Win32_Share
$SharedFolders
}
function CheckSharedFolderPermission{
$SharedFolderName = Read-Host "Enter Shared Folder Name"
$SharedFolder = Get-WmiObject -Class Win32_Share -Filter "name='$SharedFolderName'"
if(!$SharedFolder){
Write-Host "Shared Folder with this name DOES NOT EXISTS" -ForegroundColor Red
break
}
$SharedFolder | Get-Acl
# $SharedFolder | Get-Acl | Format-List *
}
function AddSharedFolderPermission{
$SharedFolderName = Read-Host "Enter Shared Folder Name"
$SharedFolder = Get-WmiObject -Class Win32_Share -Filter "name='$SharedFolderName'"
$SharedFolder
$folderPath
if(!$SharedFolder){
Write-Host "Shared Folder with this name DOES NOT EXISTS" -ForegroundColor Red
break
}else{
Write-Host "Shared Folder with thi name found" -ForegroundColor Green
}
$FolderPath = Read-Host "Enter Folder Path[Default current path/location]"
if(!$FolderPath){
$ParentDirectoryPath = Get-Location
$FolderPath = Join-Path $ParentDirectoryPath $FolderName
}
$FolderPath
$AccountName = Read-Host "Enter User/Group Name:
Users
Administrators
Everyone
or Any Other User/Group name(Custom Name)
"
$AccessRightUserInput = Read-Host "Enter Access Right Type:
0. Full
1. Read [Default]
2. Change
"
switch($AccessRightUserInput){
0{
$AccessRight = "FullControl"
}
1{
$AccessRight = "Read"
}
2{
$AccessRight = "Modify"
}
default{
$AccessRight = "Read"
}
}
switch($AccessRightUserInput){
0{
$ShareRight = "FULL"
}
1{
$ShareRight = "Read"
}
2{
$ShareRight = "Change"
}
default{
$ShareRight = "Read"
}
}
net share $SharedFolderName="$ParentDirectoryPath" /grant:$AccoutName,$ShareRight
# Write-Host "Share Permission $ShareRight given to user/group $AccountName"
#Give Access Permission
$Acl = Get-Acl -Path $FolderPath
$permission = "$AccountName", "$AccessRight", "ContainerInherit,ObjectInherit", "None", "Allow"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($permission)
$Acl.SetAccessRule($AccessRule)
$Acl | Set-Acl $FolderPath
Write-Host "$AccessRight given to user/group `"$AccountName`"" -ForegroundColor Green
}
#CreateSharedFolder
AddSharedFolderPermission
Error:
net : The syntax of this command is:
At C:\Users\Sheraram Prajapat\Desktop\shared folder win7.ps1:131 char:5
+ net share $SharedFolderName="$ParentDirectoryPath" /grant:$Accout ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The syntax of this command is::String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
NET SHARE
sharename
sharename=drive:path [/GRANT:user,[READ | CHANGE | FULL]]
[/USERS:number | /UNLIMITED]
[/REMARK:"text"]
[/CACHE:Manual | Documents| Programs | BranchCache | None]
sharename [/USERS:number | /UNLIMITED]
[/REMARK:"text"]
[/CACHE:Manual | Documents | Programs | BranchCache | None]
{sharename | devicename | drive:path} /DELETE
sharename \\computername /DELETE
also this command create a share folder and give permission to it, it can't give permission to already created or existing shared folder
I'm trying to write a script where I can create home folders for users on a primary domain controller or on all domain controllers for later DFS configuration. Script works like a charm when I write directly to A:$homeFolder. But in order to write to backup domain controllers I have to use the format \DC01.carpal.local\A$\homeFolder, and it throws an error that the syntax isn't correct. Creating the folder works, sharing doesn't. Error and code below
function Set-HomeFolder
{
$fqdn = Get-ADDomain | Select -ExpandProperty ReplicaDirectoryServers
$fqdn[0]
function Set-HomePDC
{
Get-HomeShareInfo
$PBCPath = '\\'+$fqdn[0]+'\'+$global:FolderVol+'\' ## \\dc01.carpal.local\A$\homeFolder\ ##
New-Item -Path $PBCPath -Name $global:homeFolder -ItemType "directory"
$company = Read-Host "Create home folders for users from company" ## Root OU where users reside ##
Write-Host $PBCPath$global:homeFolder
New-SmbShare -Name $global:shareName -Path $PBCPath$global:homeFolder -FullAccess ("Administrator") -ChangeAccess ("DL_$company")
$userRoot = '\\'+$fqdn[0]+'\'+$global:homeFolder+'\'
$homeDrive = Read-Host "Enter the name of the drive letter"
$homeDrive = $homeDrive + ":"
$samName = Get-ADUser -Filter * -SearchBase "OU=Users,OU=$company,$global:ou" | Select -ExpandProperty SamAccountName
foreach ($name in $samName)
{
$homeDirectory = $userRoot + $name ## \\DC01.carpal.local\Home\Ben001
Set-ADUser $name –HomeDrive $homeDrive –HomeDirectory $homeDirectory
New-Item –path "$global:FolderVol$homeFolder" -Name $name -type directory -force
$acl = Get-Acl $homeDirectory
$acl.SetAccessRuleProtection($True, $False)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($name,"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $homeDirectory $acl
}
}
function Set-HomeAllDC
{
Get-HomeShareInfo
}
if ($fqdn.GetType().BaseType.Name -eq "Array")
{
echo "`n"
Write-Host " !! Replica Domain Controllers detected !!" -ForegroundColor Red
echo "`n"
Start-Sleep -s 1
Write-Host "Configure home folders on all Domain Controllers [1]"
Write-Host "Configure home folders only on Primary Domain Controller [2]"
echo "`n"
$answer = Read-Host "Please select an option"
if ($answer -eq 1)
{
Set-HomeAllDC
}
if ($answer -eq 2)
{
Set-HomePDC
}
elseif ($answer -ge 2 -or $answer -eq "")
{
echo "`n"
Write-Host "Please provide a value between 1 and 2" -ForegroundColor Red
Start-Sleep -s 1
}
}
else
{
Set-PDCHome
}
}
function Get-HomeShareInfo
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.rootfolder = "MyComputer"
if($foldername.ShowDialog() -eq "OK")
{
$volume = $foldername.SelectedPath ## A:\
$global:FolderVol = $volume.Replace(':\','$')
}
$global:homeFolder = Read-Host "Enter the name of your home folder"
$global:shareName = Read-Host "Enter the share name"
}
Set-HomeFolder
I have this code which deletes User Profiles off a remote machine. The removal of profiles work just fine but, the Aesthetic of doing so doesn't. What do i mean?
I'm passing the user display names to an index and making a selection out of it, and that works fine in regards to assigning the proper names to the appropriate Index Number its associated to in C:\users.
The next line of code is it grabbing the selections i made, and running through them displaying the same name i did for the index, and then it goes off to delete the CIM instance.
So my question is, why is it not passing the subexpression $userinfo1 that is already made and not putting it into the next block of code, for example, the following works as in grabbing the proper Display Name and assigning it to the proper Number:
$menu = (get-childitem "\\$cn\c$\users" | sort LastWriteTime -Descending).Name
$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
$userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name ", "" 2>&1 | Out-String -Stream
if ($userinfo.Length -lt 4) {
"$user - NO DISPLAY NAME in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 2) {
"$user - account not in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 0){
$userinfo # output
}
}
}
}
Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"
Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White
for ($i=0; $i -lt $userinfo1.Count; $i++) {
Write-Host "$($i): $($userinfo1[$i])"
} #END LIST OF POSSIBLE NAMES
Write-Host ""
Write-Host "For multiple users, seperate using a SPACE(1 2 3)"
$selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"
$selection = $selection -split " "
but, the next block doesn't associate the display name (that was captured in $userinfo1) with the number i select and it just continues to display the first display name with the rest of the profiles its reiterating through:
foreach($Profile in $menu[$selection]){
Write-Host "Deleting user: $(,$userinfo1[$selection]) `
ID:$Profile "}
Hopefully this makes sense, and if anyone can point me in the right direction id greatly appreciate it!
Heres the rest of the script, please feel free to use it as it does work for deleting the actual profile off the system and not just the files.
#Deletes a profile properly off remote machine. WARNING: DOES NOT BACK UP DATA! Use at your own peril. Delprofile
$cn = Read-Host -Prompt "Enter Computer Name"
$ping = Test-Connection -ComputerName $cn -Count 1 -Quiet
If($ping -eq $false){ Write-Host "Computer seems to be offline, please check name spelling." -ForegroundColor DarkYellow; Write-Host ""; &PFL-Delete } else {
$menu = (get-childitem "\\$cn\c$\users" | sort LastWriteTime -Descending).Name
$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
$userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name ", "" 2>&1 | Out-String -Stream
if ($userinfo.Length -lt 4) {
"$user - NO DISPLAY NAME in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 2) {
"$user - account not in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 0){
$userinfo # output
}
}
}
}
Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"
Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White
for ($i=0; $i -lt $userinfo1.Count; $i++) {
Write-Host "$($i): $($userinfo1[$i])"
} #END LIST OF POSSIBLE NAMES
Write-Host ""
Write-Host "For multiple users, seperate using a SPACE(1 2 3)"
$selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"
$selection = $selection -split " "
foreach($Profile in $menu[$selection]){
Write-Host "Deleting user: $(,$userinfo1[$selection]) `
ID:$Profile "
$del = Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile }
If($del -eq $null){Write-Warning "No CIM instance found on system, profile has been deleted but files persist. Delete manually!"} else{
Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile } | Remove-CimInstance -WhatIf
Write-Host "user profile has been deleted" -ForegroundColor Red
Write-Host ""}
}
}
#CountPs $cn
12/31/2020 - EDIT:
Here is the finished result:
Function Delete-PFL{
#Deletes a profile properly off remote machine. WARNING: DOES NOT BACK UP DATA! Use at your own peril. Delprofile
$cn = Read-Host -Prompt "Enter Computer Name"
$ping = Test-Connection -ComputerName $cn -Count 1 -Quiet
If($ping -eq $false){ Write-Host "Computer seems to be offline, please check name spelling." -ForegroundColor DarkYellow; Write-Host ""; &Delete-PFL } else {
$menu = (get-childitem "\\$cn\c$\users" | sort LastWriteTime -Descending).Name
$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
$userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name ", "" 2>&1 | Out-String -Stream
if ($userinfo.Length -lt 4) {
"$user - NO DISPLAY NAME in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 2) {
"$user - ACCOUNT NOT in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 0){
$userinfo # output
}
}
}
}
Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"
Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White
for ($i=0; $i -lt $userinfo1.Count; $i++) {
Write-Host "$($i): $($userinfo1[$i])"
} #END LIST OF POSSIBLE NAMES
Write-Host ""
Write-Host "For multiple users, seperate using a SPACE(1 2 3)"
$selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"
$selection = $selection -split " "
foreach($index in $selection) {
$Profile = $menu[$index]
Write-Host "Deleting user: $($userinfo1[$index]) `
ID:$Profile "
$del = Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile }
If($del -eq $null){Write-Warning "No CIM instance found on system, profile has been deleted but files persist."
Write-Host "Attempting to delete files, please wait. . ."
Remove-Item -Path "\\$cn\c$\users\$Profile" -Force -WhatIf
Write-Host ""
Start-Sleep -Seconds 2
Write-Host "Checking if Files are still there. . ."
$TestPath = Test-Path -Path "\\$cn\c$\users\$Profile"
If($TestPath -eq $false){ Write-Host "Profile Files have been deleted. `
Continuing. . . ." -ForegroundColor Green
}
} else{
Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile } | Remove-CimInstance -WhatIf
Write-Host "user profile has been deleted" -ForegroundColor Red
Write-Host ""
}
}
}
#CountPs $cn
}
Remember to remove the -whatif parameter. Enjoy!
$selection is an array of indices, so in your foreach loop you must refer to the single index at hand, not to $selection as a whole, to get the desired display output.
The conceptually clearest approach is probably to iterate over the indices contained in $selection:
foreach($index in $selection) {
$Profile = $menu[$index]
Write-Host "Deleting user: $($userinfo1[$index]) `
EDIPI:$Profile "
# ...
}
My boss gave me a task to do in PowerShell, he wanted me to write a script.
The script should make a folder and ask for foldername then make 2 groups with read write, then make 2 users, one in each group and ask what user should be in what group. And after that, make rights for the groups to the folders.
I already have the first part in place, make a folder and make it ask for what name:
$foldername1 = read-host -Prompt 'input folder name'
new-item "c:\temp\$foldername1" -type Directory
The problem is when I'm making groups and users. There is no path?
The syntax reads:
New-LocalUser [-Name] <String> [-AccountExpires <DateTime>] [-AccountNeverExpires] [-Confirm] [-Description <String>] [-Disabl
ed] [-FullName <String>] -NoPassword [-UserMayNotChangePassword] [-WhatIf] [<CommonParameters>]
And the same for new-localgroup
How do I choose the path for the user/group I am making?
I'm new to Powershell and new in my internship.
There is no such thing as a path for a local user.
You will see local user using either PowerShell or the GUI: Start => Computer Management => System Tools => Local Users and Groups
This sample might be aligned with what you're looking for.
$foldername1 = read-host -Prompt 'input folder name'
new-item "c:\temp\$foldername1" -type Directory
$group1 = read-host -Prompt 'input first group name'
$group2 = read-host -Prompt 'input second group name'
New-LocalGroup -Name $group1
New-LocalGroup -Name $group2
$user1 = read-host -Prompt 'input first user name'
$user2 = read-host -Prompt 'input second user name'
New-LocalUser -Name $user1
New-LocalUser -Name $user2
$addGroup1 = read-host "Which user in" $group1
if ($addGroup1 -match $user1)
{
Add-LocalGroupMember -Group $group1 -Member $user1
}
if ($addGroup1 -match $user2)
{
Add-LocalGroupMember -Group $group1 -Member $user2
}
$addGroup2 = read-host "which user in" $group2
if ($addGroup2 -match $user1)
{
Add-LocalGroupMember -Group $group2 -Member $user1
}
if ($addGroup2 -match $user2)
{
Add-LocalGroupMember -Group $group2 -Member $user2
}
write-host "Current members in" $group1 $group2
Get-LocalGroupMember -Group $group1
Get-LocalGroupMember -Group $group2
$rule1 = New-Object System.Security.AccessControl.FileSystemAccessRule
("$group1","ReadAndExecute","Allow")
$rule2 = New-Object System.Security.AccessControl.FileSystemAccessRule
("$group2","ReadAndExecute","Allow")
$acl = get-acl "c:\temp\$foldername1"
$acl.SetAccessRule($rule1)
$acl.SetAccessRule($rule2)
$acl | select -ExpandProperty access
I am working on a PS script to automate new network accounts, their home folder and exchange mailbox. We have multiple Domain controllers so am looking for a way of creating a network account on one domain controller but creating the home directory on a different site with its own domain controller. I have tried this but when setting permissions an issue has occurred because the account has not replicated over to the other DC. Anyone have any ideas to get around this?
New Account Function
Function New-BVStandardUser
{
Param (
$FirstName,
$LastName,
$CallRef,
$SiteName,
$EmployeeID,
$ExpiryDate,
$InternetAccess,
$ExternalEmailAccess
)
$ImportGroups = Import-Csv -Path "\\UKSP-FS01\Lawsonja$\Scripts\New-ADUser\SiteGroups.csv" -Delimiter ","
$ImportServers = Import-Csv -Path "\\UKSP-FS01\Lawsonja$\Scripts\New-ADUser\SiteServers.csv" -Delimiter ","
$ImportOUs = Import-Csv -Path "\\UKSP-FS01\Lawsonja$\Scripts\New-ADUser\SiteOUs.csv" -Delimiter ","
# Convert the first and last name so it does not have special characters for the email address/ UPN
$LastNameEdit = $LastName -replace '[^a-zA-Z]', ''
$FirstNameEdit = $FirstName -replace '[^a-zA-Z]', ''
# Fetch a free username from AD based on the provided first and last name from the user
$Username = Get-ADUsername -FirstName $FirstNameEdit -LastName $LastNameEdit
# Generate a random password using the imported module
$Password = Get-Randompassword
# Create the AD account based on the inputted fields
$Params = #{
DisplayName = "$($LastName), $($FirstName)"
DirectoryName = "$($LastName), $($FirstName)"
SamAccountName = "$Username"
UserPrincipalName = "$FirstNameEdit.$LastNameEdit#Bakkavor.com"
Comment = "Created $($env:USERNAME) - $(Get-Date -Format dd/MM/yy) - $($CallRef)"
GivenName = "$FirstNameEdit"
Surname = "$LastNameEdit"
Description = "$($SiteName) User"
Enabled = $true
ChangePasswordAtLogon = $true
Path = "$ImportOUs.$($SiteName)"
HomeDirectory = "\\$ImportServers.$($SiteName)\$Username$"
HomeDrive = "U"
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
try
{
New-ADUser #Params -ErrorAction Stop
Write-Verbose -Verbose "Network Account Created"
}
catch
{
Write-Warning "Error creating network account. Error: $($_.Exception.Message)"
break
}
New Home Drive Function
Function New-BVUDrive
{
Param
(
$Username,
$Server
)
# Connect to the relevant server in CSV, create new folder, create new SMB Share for the user and add share/ NTFS permissions
Invoke-Command -ComputerName $Server -ArgumentList $Username -ErrorAction Stop -ScriptBlock
{
param($Username)
$FindShare = (Get-SmbShare -Name Users$).Path
if($FindShare -eq $true)
{
try
{
New-Item -ItemType Directory -Path "$FindShare\$Username" -ErrorAction Stop
New-SmbShare -Name "$Username$" -Path "$FindShare\$Username" -FullAccess "AD\Server Admins", "AD\Domain Admins" -ChangeAccess "AD\$Username" -ErrorAction Stop
$Acl = Get-Acl "$FindShare\$Username"
foreach($Rule in $Acl.Access)
{
$Acl.RemoveAccessRule($Rule)
}
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule("Everyone","FullControl","Allow")
$Acl.SetAccessRule($Ar)
$Acl.SetAccessRuleProtection($false, $true)
Set-Acl "$FindShare\$Username" $Acl -ErrorAction Stop
}
catch
{
Write-Warning "U drive failed to create. Error: $($_.Exception.Message)"
}
}
else
{
Write-Warning "Users$ share not found on server"
}
}
}
Have you tried using the SID?
In the second function New-BVUDrive, replace the username with SID. and use the following cmdlet to get the SID:
(Get-ADUser -Identity $SamAccountName).SID.Value
you will be able to set the ACL now, until the data will replicate you will see in the security tab the SID, but the user will be able to access the folder if he will try.
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule ($SIDIdentity, 'FullControl', ('ContainerInherit','ObjectInherit'), 'None','Allow')
Hope it will help.