通过Powershell将用户分配给IIS AppPool

Chi*_*ago 13 powershell iis-7

我尝试了这个代码,似乎工作正常.但是,我注意到如果您将用户名和密码分配给不存在的帐户,代码将继续存在而不会出现问题.此外,如果您分配一个无效的帐户并调用stop()然后启动(),IIS池确实会停止并启动!! 此外,当我去InetMgr并启动,停止或重新启动游泳池时,它也停止并开始而没有抱怨!

我希望添加无效帐户会导致错误,从而有效地允许我测试帐户的有效性.为什么它会这样?

$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-host "New Pool User: " $testpool.processModel.userName;
   write-host "New Pool PWd: " $testpool.processModel.password;
}
Run Code Online (Sandbox Code Playgroud)

小智 8

在设置池标识之前,应始终验证凭据.这可以通过PrincipalContext .NET类完成 - 具体来看PrincipalContext.ValidateCredentials(用户,密码).

样品:

#-- 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")
Run Code Online (Sandbox Code Playgroud)

如果本地帐户将$ ct更改为'Machine'ContextType.