Search code examples
c#iiscakebuild

Remotely set file permission to IIS AppPool user with C#


So far all the Googling on this has talked about domain users, or running the process on the machine locally, neither of which is a fit for me.

I'm running a process our build/deployment server (a Cake build script running on Team City, or locally on my machine) that deploys a wep application to IIS on a remote server. As part of this I need to set the permissions on the directory it deploys to so that IIS can see and run the application. My issue is that the virtual account (IIS AppPool\MyAppPool) that is created cannot be seen from the Team City server, so I cannot set the permission. I get an exception:

System.Security.Principal.IdentityNotMappedException: Some or all identity references could not be translated.

So, is there any way to set the file permission of a folder on the Web Server from a Team City server or my local machine to permit access through a virtual IIS AppPool account? (Since I'm using Cake Build, any solutions in C# would be ideal, but I can launch other processes if absolutely necessary)


Solution

  • Going by some of the comments to the question, I came up with this as my final solution:

    function Add-RemoteAcl
    (
        [string]$computerName,
        [string]$directory,
        [string]$user,
        [string]$permission
    )
    {
        $session = New-PSSession -ComputerName $computerName;
        Invoke-Command -Session $session -Args $directory, $user, $permission -ScriptBlock {
            param([string]$directory,[string]$user,[string]$permission)
            $acl = Get-Acl $directory;
            $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, $permission, "ContainerInherit, ObjectInherit", "None", "Allow");
            if ($accessRule -eq $null){
                Throw "Unable to create the Access Rule giving $permission permission to $user on $directory";
            }
            $acl.AddAccessRule($accessRule)
            Set-Acl -aclobject $acl $directory
        };
        Remove-PSSession $session;
    }