Setting permissions for ASP.NET application on IIS with PowerShell
Setting the write permission for IIS AppPool using PowerShell
Very often you need to setup ASP.NET Web application on IIS server, you need to setup file and folder permission for your application on order to access content of specific folder.
This can be easily done through Windows Explorer Properties window in the Security tab.
The problem begins when you need to automate this process for example when you are dynamically creating a Virtual Machine instance from a template during autoscaling. At this point you need to automate IIS ASP.NET application setup and as well all the necessary pre requirements on the new Windows system.
For this purpose I wrote a short PowerShell script which can be part of a larger setup script as well.
$Path = "D:\Temp\logs" $User = "IIS AppPool\MyWebsite" $Acl = Get-Acl $Path $Ar = New-Object system.security.accesscontrol.filesystemaccessrule($User,"FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) Set-Acl $Path $Acl
The script is setting permission for IIS Application Pool Identity by looking for a user in IIS AppPool\<AppPool name>, but this can be any identity, which also quite often NETWORK SERVICE
Depending on the complexity and the requirements of the ASP.NET web application, you might have to set different permissions on to the multiple folders.
Of course you can just copy paste and duplicate commands from the snippet above, but more efficient way to do it is in a loop which makes your script more reusable and can be easily part of the larger more complex script without introducing additional complexity.
So we will do this using loop and custom array object.
$iisAppPoolName = "MyWebsite" $isAppPoolPermissions = @( @{user="IIS AppPool" $iisAppPoolName;path="D:\Temp\logs";access="Read";action="Allow"}, @{user="IIS AppPool" $iisAppPoolName;path="D:\Temp\trace";access="Write";action="Allow"} @{user="IIS AppPool" $iisAppPoolName;path="D:\Temp\data";access="FullControl";action="Allow"} ) For ($i=0; $i -lt $isAppPoolPermissions.Length; $i ) { $permisson = $isAppPoolPermissions[$i] $Acl = Get-Acl $permisson.path $Ar = New-Object system.security.accesscontrol.filesystemaccessrule($permisson.user,$permisson.access, "ContainerInherit,ObjectInherit", "None", $permisson.action) $Acl.SetAccessRule($Ar) Set-Acl $permisson.path $Acl }
References
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article