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
Related
I’m trying to delete certain files from a Sharepoint folder, however no matter what I try, I cannot get it to delete. I have an exclusions list, for the names of pictures that should not be deleted. I have attached one of many tries. Anyone know what to do?
The exclusionslist and the loop can write out the names to delete without any problems, and the below code gives no error-codes.
$siteurl = “https://sharepoint.com/sites/Some/Sharepoint/Folder”
$username = “AdminAccount”
$securePassword = ConvertTo-SecureString “MuchSecurePassWord” -AsPlainText -Force
$O365Credential = New-Object System.Management.Automation.PsCredential($username, $securePassword)
$count = 0
$exclusions = import-csv “Downloads\exclusions.txt”
$excounter = $exclusions.Count
write-host “Files to not delete $excounter”
Connect-PnPOnline -Url $siteurl -Credentials $O365Credential
$items = Get-PnPFolderItem -FolderSiteRelativeUrl "/Picture Folder/Test" -ItemType File
$ListItemCount = $items.Count
Write-Host $ListItemCount
$Found = 0
foreach ($item in $items)
{
foreach ($User in $exclusions)
{
#Write-Host $item.Name " " $User.User
if ($item.Name -eq $User.User)
{
# Write-Host $item.Name " " $User.User
$Found = 1
}
}
if($Found -eq 0)
{
$Name = $item.Name
Write-host "Delete: " $item.Name $Found
$item.DeleteObject()
}
$Found=0
}
I'm hoping to delete photos, that are not on the exclusions list.
Instead of:
$item.DeleteObject()
Use:
Remove-PnPFile -ServerRelativeUrl $item.ServerRelativeURL
Docs:
https://pnp.github.io/powershell/cmdlets/Remove-PnPFile.html
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 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.
On Sharepoint Online, using Powershell, I am trying to set list item permissions, and am finding dozens of tutorials that use a RoleDefinitionBindingCollection($ctx) call...
When I do this, though, I get the following error:
New-Object : Cannot find an overload for "RoleDefinitionBindingCollection" and
the argument count: "1".At
C:\Users\thebear\Desktop\SEDA\SEDASetIPPermissions.ps1:172 char:31
+ ... entReader = New-Object Microsoft.SharePoint.Client.RoleDefinitionBind ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
I am iterating through Doclib folders, then through the Folder.Files, checking for a value in a custom field, and setting the permissions on the matching items. EDIT: Here is the full code:
# cd 'C:\Users\thebear\Desktop\SEDA'
# .\SEDASetIPPermissions test KLY KLY1
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
If($($args.Count) -ne 3)
{
Write-Host “Usage: .\SEDASetIPPermissions <'prod' or 'test'> <ProgCode i.e. 'LCL' or 'All'> <IPGroup i.e. 'KLY1' or 'All'>"
break
}
$Site = if($args[0] -eq 'prod') {'sedasearch'} elseif ($args[0] -eq 'test') {'sedasearchtest'}
$Lib = $args[1]
$IPGroup = $args[2]
# Get Connected
$Cred = Get-Credential
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $Cred.UserName, $Cred.Password
$Url = "https://MySite.sharepoint.com/sites/$Site"
Connect-SPOnline -Url $Url -Credentials $Credentials
# Get Client Context
$ctx = Get-SPOContext
$ctx.RequestTimeout = 1000000
$ctx.ExecuteQuery()
# Get Web & Lists
$web = $ctx.Web
$ctx.Load($web)
$ctx.Load($web.Lists)
$ctx.Load($web.RoleDefinitions)
$ctx.ExecuteQuery()
$lists = $web.Lists
# Get Site Groups
$groups = $web.SiteGroups
$ctx.Load($groups)
$ctx.ExecuteQuery()
# Get Target Group
$groupFound = $false
$ScriptStart = Get-Date
foreach ($group in $groups)
{
if ($group.Title -eq "SEDA Admins")
{
$AdminGroupID = $group.Id
}
elseif($group.Title -eq $IPGroup + " Security Group")
{
$groupFound = $true
$IPGroupID = $group.Id
Write-Host "`n'$IPGroup Security Group' Found...`n" -ForegroundColor Green
}
}
if (!$groupFound) { Write-Host "`n'$IPGroup Security Group' NOT Found...`n" -ForegroundColor Red; break }
# Get Target List
$list = $lists.GetByTitle($Lib + " Library")
$ctx.Load($list)
$ctx.Load($list.RootFolder)
$ctx.Load($list.Fields)
$ctx.ExecuteQuery()
if($list -ne $null)
{ "`n'{0}' Found...`n" -f $list.Title | Write-Host -ForegroundColor Green }
else
{ "`n'{0}' NOT Found...`n" -f $list.Title | Write-Host -ForegroundColor Red; break }
# Get List Folders
$folders = $list.RootFolder.Folders
$ctx.Load($folders)
$ctx.ExecuteQuery()
$folders = $folders | sort Name
# Set Up Group and Admin Permissions (if not already there)
$RoleDefinitions = $web.RoleDefinitions
$ctx.Load($RoleDefinitions)
$ctx.ExecuteQuery()
$foundIPGroupRole = $false
$foundIPAdminRole = $false
foreach ($role in $RoleDefinitions)
{
if ($role.Name -eq "Read")
{
$IPGroupRole = $role
$foundIPGroupRole = $true
}
elseif ($role.Name -eq "Full Control")
{
$IPAdminRole = $role
$foundIPAdminRole = $true
}
}
# Set the permissions for 'IP Group'
$roleAssignmentReader = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($ctx)
$roleAssignmentReader.Add($IPGroupRole)
# Set the permissions for 'IP Admin'
$roleAssignmentAdmin = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($ctx)
$roleAssignmentAdmin.Add($IPAdminRole)
# Set Counters
$FileCount = 0
$FailCount = 0
foreach ($folder in $folders)
{
$FolderFileCount = 0
$ctx.Load($folder)
$ctx.Load($folder.ListItemAllFields)
$ctx.ExecuteQuery()
if ($folder.ItemCount -lt 5000)
{
$files = $folder.Files
$ctx.Load($files)
$ctx.ExecuteQuery()
"`nProcessing Folder {0}..." -f $folder.Name | Write-Host -ForegroundColor Green
}
else
{ "`nFolder {0} Exceeds 5000 Items...`n" -f $folder.Url | Write-Host -ForegroundColor Red; continue }
foreach ($file in $files)
{
$ctx.Load($file)
$ctx.Load($file.ListItemAllFields)
$ctx.ExecuteQuery()
$item = $file.ListItemAllFields
$ctx.Load($item)
$ctx.ExecuteQuery()
$name = $file.Name
$group = $item.get_item('IPGroup')
if($group -eq $IPGroup)
{
"`nProcessing File {0}...`n" -f $name | Write-Host -ForegroundColor Green;
# Break inheritance on the list item and remove existing permissons.
# NOTE: Use $item.ResetRoleInheritance() to Restore Roll Inheritance
$item.BreakRoleInheritance($false, $true)
# Apply the two permission roles to the list item.
$ctx.Load($item.RoleAssignments.Add($IPGroupID, $roleAssignmentReader))
$ctx.Load($item.RoleAssignments.Add($AdminGroupID, $roleAssignmentAdmin))
# Update the list item and execute
$item.Update()
$ctx.ExecuteQuery()
"`nProcessed File {0}...`n" -f $name | Write-Host -ForegroundColor Green;
}
$FolderFileCount += 1
if($FolderFileCount % 1000 -eq 0) { "{0}K" -f ($FolderFileCount/1000).ToString() | Write-Host }
elseif($FolderFileCount % 100 -eq 0) {Write-Host '*'}
else {Write-Host -NoNewline '.'}
}
}
“`n{0} Files Processed, {1} Error(s), Elapsed Time: {2}" -f $FileCount, $FailCount, $((Get-Date) - $ScriptStart) | Write-Host
$ctx appears to be legit... what else could be causing this error (for a day now)?
This error occurs since RoleDefinitionBindingCollection constructor expects ClientRuntimeContext object but the following line:
$ctx = Get-SPOContext
returns object of OfficeDevPnP.Core.PnPClientContext type. Even though it inherits from ClientRuntimeContext object (PnPClientContext -> ClientContext -> ClientRuntimeContext) it could not be used for instantiating of Microsoft.SharePoint.Client.RoleDefinitionBindingCollection object.
Solution
One option would be to replace the lines:
Connect-SPOnline -Url $Url -Credentials $Credentials
#Get Client Context
$ctx = Get-SPOContext
with
$ctx = Get-Context -WebUrl $Url -UserName $Credentials.UserName -Password $Credentials.Password
where
Function Get-Context([String]$WebUrl,[String]$UserName,[System.Security.SecureString]$Password) {
$context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)
return $context
}
which returns Microsoft.SharePoint.Client.ClientContext object.
According to this link below. The Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($ctx) is looking for a url as an argument, not a filename.
https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.roledefinitionbindingcollection.aspx
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().