Reputation: 21
I am trying to create a folder and set permissions on those folders within one PowerShell script. The script won't change the permissions when run the first time. I have to run the script twice to set the permissions. Not sure what could be causing this odd behavior.
$desired_install_loc = ${env:ProgramFiles}
$base_path = Join-Path $desired_install_loc 'Base_Test';
$install_path = Join-Path $base_path 'Install_Test';
function Create-Directory {
if( !(Test-Path $base_path )){
New-Item -ItemType Directory -Force -Path $base_path;
}
if( !(Test-path $install_path) ){
New-Item -ItemType Directory -Force -Path $install_path;
}
}
function Replace-FolderPerms($folder_path) {
$acl = (Get-Acl -Path $folder_path);
$add_rule = (New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users","Read", "Allow"));
$acl.SetAccessRuleProtection($true,$true)
$acl.SetAccessRule($add_rule)
Set-ACL $folder_path $acl;
}
Create-Directory;
Replace-FolderPerms $base_path;
Replace-FolderPerms $install_path;
Creates the folders, but does not set the permissions afterwards.
Upvotes: 1
Views: 4002
Reputation: 21
I was attempting to keep old permissions by setting SetAccessRuleProtection($true, $true)
. Setting the second argument to $false
and fully building out the permissions did the trick.
$desired_install_loc = ${env:ProgramFiles}
$base_path = Join-Path $desired_install_loc 'Base_Test';
$install_path = Join-Path $base_path 'Install_Test';
function Create-Directory {
if( !(Test-Path $base_path )){
New-Item -ItemType Directory -Force -Path $base_path;
}
if( !(Test-path $install_path) ){
New-Item -ItemType Directory -Force -Path $install_path;
}
}
function Replace-FolderPerms($folder_path) {
$acl = (Get-Acl -Path $folder_path);
$add_rule = (New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users","Read", "Allow"));
$add_rule_admin = (New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"));
$add_rule_system = (New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"));
$acl.SetAccessRuleProtection($true,$false);
$acl.AddAccessRule($add_rule);
$acl.AddAccessRule($add_rule_admin);
$acl.AddAccessRule($add_rule_system);
$acl | Set-ACL -Path $folder_path;
}
Create-Directory;
Replace-FolderPerms $base_path;
Replace-FolderPerms $install_path;
Upvotes: 1