Skip to main content

How to use PowerShell to create an IIS Application Pool, and set the identity it runs under to a network domain account.

function New-RemoteIISAppPool {
    param (
        [string]$ServerName,
        [string]$AppPoolName,
        [System.Management.Automation.PSCredential]$ServerCredential,
        [System.Management.Automation.PSCredential]$AppPoolCredential
    )

    # Script block to create the application pool and set the identity
    $scriptBlock = {
        param ($AppPoolName, $AppPoolCredential)
        Import-Module WebAdministration

        # Create a new application pool
        New-WebAppPool -Name $AppPoolName

        # Set the application pool identity to the specified network domain account
        Set-ItemProperty "IIS:\AppPools\$AppPoolName" -Name processModel.identityType -Value 3
        Set-ItemProperty "IIS:\AppPools\$AppPoolName" -Name processModel.userName -Value $AppPoolCredential.UserName
        Set-ItemProperty "IIS:\AppPools\$AppPoolName" -Name processModel.password -Value $AppPoolCredential.GetNetworkCredential().Password

        Write-Output "Application pool '$AppPoolName' created and configured to run under the account '$($AppPoolCredential.UserName)'."
    }

    # Use PowerShell remoting to execute the script block on the remote server
    Invoke-Command -ComputerName $ServerName -Credential $ServerCredential -ScriptBlock $scriptBlock -ArgumentList $AppPoolName, $AppPoolCredential
}

# Example usage
$remoteServerCred = Get-Credential -Message "Enter the credentials for the remote server"
$appPoolCred = Get-Credential -Message "Enter the credentials for the application pool account"
New-RemoteIISAppPool -ServerName "RemoteServerName" -AppPoolName "YourAppPoolName" -ServerCredential $remoteServerCred -AppPoolCredential $appPoolCred