Assign User to IIS AppPool via Powershell
I tried this code and it appears to work fine. However, i noticed if you assign the username and password to an account that does not exist the code continues without issue. In addition, if you assign an invalid account and call stop() and then start() the IIS pool indeed stops and starts!! Furthermore, when I go to InetMgr and start,stop or recylce the pool it also stops and starts without complaining!
I was hoping that adding an invalid account would throw an error effectively allowing me to test the validity of an account. Why does it behave this way?
$loginfile = "d:\temp\Logins.csv"
$csv = Import-Csv -path $loginfile
ForEach($line in $csv){
$poolid = "MyDomain\" + $line.Login;
Write-Host "Assigning User to Pool:" $poolid;
$testpool = get-item iis:\apppools\test;
$testpool.processModel.userName = $poolid;
$testpool.processModel.password = $line.Pwd;
$testpool.processModel.identityType = 3;
$testpool | Set-Item
$testpool.Stop();
$testpool.Start();
Write-Host "IIS Recycled";
$testpool = get-item iis:\apppools\test;
write-开发者_StackOverflow中文版host "New Pool User: " $testpool.processModel.userName;
write-host "New Pool PWd: " $testpool.processModel.password;
}
You should always validate your credentials before setting the pool identity. This can be accomplished via the PrincipalContext .NET class -- specifically look at PrincipalContext.ValidateCredentials(user, password).
Sample:
#-- Make sure the proper Assembly is loaded
[System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") | out-null
#-- Code to check user credentials -- put in function but here are the guts
#-- Recommend you use SecureStrings and convert where needed
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ct,"domainname"
$isValid = $pc.ValidateCredentials("myuser","mypassword")
If local account change the $ct to 'Machine' ContextType.
Start and Stop are something of a misnomer. They should really be named Enable and Disable.
The worker process for the pool won't actually "start" until it needs to service a request.
It's at that point authentication takes place. If the username and password are invalid then you'll get a 503 Service Unavailable response and three events (5021, 5057 and 5059) logged by the WAS in the System event log.
There is no up-front checking of the validity of a pool's identity when using the API's. Only the IIS management console performs these checks.
精彩评论