We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Create app pool using Windows Powershell script

sunilbains
sunilbains asked
on
Medium Priority
4,478 Views
Last Modified: 2012-08-09
I am using power shell script to Create app pool. Its creating app pool with all default settings. is there any way i can give my own settings values for idletimeout, check mark for recycling worker process, memory ..... Iam not able to find corresponding command line values for all default app pool parameters. Can Somebody help here.





$IIsAppPool = New-Object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/AppPools")
$Child = $IIsAppPool.psbase.children.Add($AppPoolName,"IIsApplicationPool")
$Child.psbase.CommitChanges()
$child.put("IdleTimeout",30)
$child.put("PeriodicRestartTime",0)

Open in new window

Comment
Watch Question

Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Your values above are fine, but you do need to run "CommitChanges()" again to actually set them.

As for the rest of the values, they are:

Recycling:

Recycle worker process (number of requests) - PeriodicRestartRequests
Recycle worker process at the following times - PeriodicRestartSchedule (array)
Maximum Virtual Memory (in MB) - PeriodicRestartMemory (** in KB **)
Maximum Used Memory (in MB) - PeriodicRestartPrivateMemory (** in KB **)

Performance:

Shutdown process after being idle for (time in minutes) - idleTimeout
Limit the kernel request queue (number of requests) - AppPoolQueueLength
Enable CPU Monitoring (if the following are set):
  Maximum CPU Use (percentage) - CPULimit ( * 1000; 100% = 100000)
  Refresh CPU Usage Numbers (in minutes) - CPUResetInterval
  Action performed when CPU usage exceeds maximum CPU - CPUAction (No Action = 0; Shutdown = 1)
Maximum number of worker processes - MaxProcesses

Health:

Enable Pinging - PingingEnabled (On = 1; Off = 0)
Ping worker process (frequency in seconds) - PingInterval
Enable Rapid-Fail Protection - RapidFailProtection (On = 1; Off = 0)
Failures - RapidFailProtectionMaxCrashes
Time Period (in minutes) - RapidFailProtectionInterval
Worker process must startup within (time in seconds) - StartupTimeLimit
Worker process must shutdown within (time in seconds) - ShutdownTimeLimit

Identity:

Predefined - AppPoolIdentityType (Local System = 0; Local Server = 1; Network Service = 2)
Configurable - AppPoolIdentityType (3)
Username - WAMUserName
Password - WAMUserPass

HTH

Chris

Author

Commented:
Hi,
Thanks for this.
Is there any way we can grant permission to IIS_WPG group / Administrators on wwwroot folder through script?
PowerShell Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:

Certainly can. PowerShell is rather good at that :)

In the example below we create two new access rules, one for IIS_WPG allowing Read and Execute, another for Administrator allowing Full Control.

Then we grab the Access Control List from $Path, add the two new rules, and set the modified ACL back.

Chris
$Path = "C:\inetpub\wwwroot"
 
$IIS_WPG = `
  New-Object System.Security.AccessControl.FileSystemAccessRule("$($Env:ComputerName)\IIS_WPG", `
  "ReadAndExecute", @("ObjectInherit", "ContainerInherit"), "None", "Allow")
 
$Admin = `
  New-Object System.Security.AccessControl.FileSystemAccessRule("$($Env:ComputerName)\Administrator", `
    "FullControl", @("ObjectInherit", "ContainerInherit"), "None", "Allow")
 
$ACL = Get-ACL $Path
$ACL.AddAccessRule($IIS_WPG)
$ACL.AddAccessRule($Admin)
Set-ACL $Path -aclObject $ACL

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Thanks Chris

Author

Commented:
Chirs,
  Can we add memebrs to the IIS Group through powershell script?
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

IIS_WPG? Sure, with a catch...

$Group = [ADSI]"WinNT://$($Env:ComputerName)/IIS_WPG"
$Group.Add("WinNT://$($Env:ComputerName)/Username")

And the catch, it's minor:

When we get the connection to the group in this manner (WinNT://) it will expect us only to use WinNT paths for the users we add (as in the example above). If you happen to have AD behind all this you might be more familiar with "LDAP://CN=User, ...", it won't like being fed a path like that.

So, if it were a domain user the example would become:

$Group.Add("WinNT://$($Env:UserDomain)/Username")

Otherwise that's all there is to it.

Chris

Author

Commented:
Sorry to keep asking you..
How do give permission to "Authenticated Users" on wwwroot?
Is it something below?

New-Object System.Security.AccessControl.FileSystemAccessRule("$($Env:ComputerName)\Authenticated Users", `
    "FullControl", @("ObjectInherit", "ContainerInherit"), "None", "Allow")
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

No worries.

Almost, Authenticated Users is "NT AUTHORITY" rather than a computer name. It should work if you define the rule as below.

You can get a full list of the rights you can assign if you run:

[Enum]::GetNames([System.Security.AccessControl.FileSystemRights])

Just in case you wanted to use more than FullControl :)

Chris
# This is the file system rule we want to create
New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\Authenticated Users", `
    "FullControl", @("ObjectInherit", "ContainerInherit"), "None", "Allow")
 
# Using the rule
$Rule = New-Object System.Security.AccessControl.FileSystemAccessRule(` 
  "NT AUTHORITY\Authenticated Users", "FullControl", `
  @("ObjectInherit", "ContainerInherit"), "None", "Allow")
 
$ACL = Get-ACL "C:\inetpub\wwwroot"
$ACL.AddAccessRule($Rule)
Set-ACL "C:\inetpub\wwwroot" -aclObject $ACL

Open in new window

Author

Commented:
Hi Chris,
 Iam getting error while giving IIS_WPG  permission on wwwroot.


Creating Virtual Directories and Application Pool
Incomplete string token.
At C:\Vdir\VDir.ps1:196 char:106
+ $IIS_WPG =`New-Object System.Security.AccessControl.FileSystemAccessRule("$($
Env:ComputerName)\IIS_WPG", ` <<<< "ReadAndExecute", @("ObjectInherit", "Contai
nerInherit"), "None", "Allow")
write-output "Starting Powershell Script"
# this is the script for Creating Virtual Directories and Application Pool
 
 
# ****************** List of Variables *********************  
 
#Reading xml file
$xmlfile = $pwd.path + "\VDir.xml "
[xml]$File= get-content $xmlfile
# name of the Application Pool and also client directory
$AppPoolName=$File.Parameters.VDir | %{$_.AppPoolName} # need value "globearc"
$IIS_Root=$File.Parameters.VDir | %{$_.IIS_Root}  #need value "c:\Inetpub\wwwroot\"
 
# where the files are kept for WebApp
#need value c:\newweb
$LocalPathForWebApp=$File.Parameters.VDir | %{$_.LocalPathForWebApp}  	
$AspNetVersionForWebApp=2    			
 
# where the files are kept for WebServices
#need value c:\newweb
$LocalPathForWebServices=$File.Parameters.VDir | %{$_.LocalPathForWebServices}
$AspNetVersionForWebServices=2    
 
 
# ***** Create Application Pool **************
 
 
$IIsAppPool = New-Object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/AppPools")
$Child = $IIsAppPool.psbase.children.Add($AppPoolName,"IIsApplicationPool")
$Child.psbase.CommitChanges()
$child.put("PeriodicRestartMemory",1048576)
$child.put("PeriodicRestartTime",1740)
$child.put("CPUResetInterval",30)
$child.put("MaxProcesses",1)
$child.put("IdleTimeout",8640)
$Child.psbase.CommitChanges()
 
 
# ***** end **********************************
 
 
 
 
 
 
# the script to create virtual directory under IIS**********************
 
 
# create folder 'globearc' for client at c:\Inetpub\wwwroot\
 
$ClientDir=$IIS_Root+$AppPoolName
New-Item -Path $ClientDir -ItemType Directory -Force
 
 
 
# ***** the following is the list of variables *************************
 
$ApplicationName=$AppPoolName+"/WebApp"
$LocalPath=$LocalPathForWebApp
$AspNetVersion=$AspNetVersionForWebApp       # either 1 0r 2
 
# ***** end of list ****************************************************
 
 
 
 
 
$IIsAdmin = New-Object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/1/Root")
 
#Remove the existing WebApp under globearc
foreach($VD in $IIsAdmin.psbase.children)
{
	if($VD.psbase.Name -eq $AppPoolName)
	{
		foreach($VDChild in $VD.psbase.children)
		{
			if($VDChild.psbase.name -eq "WebApp")
				{
					write-output "WebApp exists"
					$VD.psbase.Invoke("Delete","IIsWebVirtualDir",$VDChild.psbase.name)
					$VD.psbase.CommitChanges()
					write-output "WebApp  deleted"	
		}		}
		
	}
}
 
 
$IIsAdmin.psbase.CommitChanges()
$virtualdir = $IIsAdmin.psbase.children.Add($ApplicationName,"IIsWebVirtualDir")
$virtualdir.psbase.CommitChanges()
 
$virtualdir.put("Path",$LocalPath)
$virtualdir.put("AppFriendlyName",$ApplicationName)
$virtualdir.put("EnableDirBrowsing",$true)
$virtualdir.put("AccessRead",$true)
$virtualdir.put("AccessExecute",$true)
$virtualdir.put("AccessWrite",$false)
$virtualdir.put("AccessScript",$true)
$virtualdir.put("Authanonymous",$false)
$virtualdir.put("AuthBasic",$false)
$virtualdir.put("AuthNTLM",$true)
$virtualdir.put("EnableDefaultDoc",$true)
$virtualdir.put("DefaultDoc","default.htm,default.aspx,default.asp,index.htm")
$virtualdir.put("AspEnableParentPaths",$true)
 
$virtualdir.put("AppPoolId",$AppPoolName) #To select the application pool from list
 
$virtualdir.psbase.CommitChanges()
$virtualdir.psbase.Invoke("AppCreate", 1)
 
if($AspNetVersion -eq 2) 
{
#c:\windows\Microsoft.NET\framework\v2.0.50727\aspnet_regiis -s w3svc/1/root/$ApplicationName
& $env:windir\Microsoft.NET\framework\v2.0.50727\aspnet_regiis -s w3svc/1/root/$ApplicationName
}
else
{
#c:\windows\Microsoft.NET\framework\v1.1.4322\aspnet_regiis -s w3svc/1/root/$ApplicationName
& $env:windir\Microsoft.NET\framework\v1.1.4322\aspnet_regiis -s w3svc/1/root/$ApplicationName
}
 
 
 
 
# second one for webservices
 
 
# ***** the following is the list of variables***************************
 
$ApplicationName=$AppPoolName+"/WebServices"
$LocalPath=$LocalPathForWebServices
$AspNetVersion=$AspNetVersionForWebServices
 
# ***** end of list *****************************************************
 
 
 
 
$IIsAdmin = New-Object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/1/Root")
 
 
#Remove the existing WebService under globearc
foreach($VD in $IIsAdmin.psbase.children)
{
	if($VD.psbase.Name -eq $AppPoolName)
	{
		foreach($VDChild in $VD.psbase.children)
		{
			if($VDChild.psbase.name -eq "WebServices")
				{
					write-output "WebServices exists"
					$VD.psbase.Invoke("Delete","IIsWebVirtualDir",$VDChild.psbase.name)
					$VD.psbase.CommitChanges()
					write-output "WebServices  deleted"	
		}		}
		
	}
}
 
$IIsAdmin.psbase.CommitChanges()
$virtualdir = $IIsAdmin.psbase.children.Add($ApplicationName,"IIsWebVirtualDir")
$virtualdir.psbase.CommitChanges()
 
$virtualdir.put("Path",$LocalPath)
$virtualdir.put("AppFriendlyName",$ApplicationName)
$virtualdir.put("EnableDirBrowsing",$true)
$virtualdir.put("AccessRead",$true)
$virtualdir.put("Authanonymous",$true)
$virtualdir.put("AccessExecute",$true)
$virtualdir.put("AccessWrite",$false)
$virtualdir.put("AccessScript",$true)
$virtualdir.put("AuthNTLM",$true)
$virtualdir.put("EnableDefaultDoc",$true)
$virtualdir.put("DefaultDoc","default.htm,default.aspx,default.asp,index.htm")
$virtualdir.put("AspEnableParentPaths",$true)
 
$virtualdir.put("AppPoolId",$AppPoolName) #To select the application pool from list
 
$virtualdir.psbase.CommitChanges()
$virtualdir.psbase.Invoke("AppCreate", 1)
 
if($AspNetVersion -eq 2) 
{
#c:\windows\Microsoft.NET\framework\v2.0.50727\aspnet_regiis -s w3svc/1/root/$ApplicationName
& $env:windir\Microsoft.NET\framework\v2.0.50727\aspnet_regiis -s w3svc/1/root/$ApplicationName
}
else
{
#c:\windows\Microsoft.NET\framework\v1.1.4322\aspnet_regiis -s w3svc/1/root/$ApplicationName
& $env:windir\Microsoft.NET\framework\v1.1.4322\aspnet_regiis -s w3svc/1/root/$ApplicationName
}
 
$Path = "C:\inetpub\wwwroot"
 
$IIS_WPG =`New-Object System.Security.AccessControl.FileSystemAccessRule("$($Env:ComputerName)\IIS_WPG", `
"ReadAndExecute", @("ObjectInherit", "ContainerInherit"), "None", "Allow")
 
 
$ACL = Get-ACL $Path
$ACL.AddAccessRule($IIS_WPG)
Set-ACL $Path -aclObject $ACL

Open in new window

Author

Commented:
never mind i got it.

Author

Commented:
Hi Chris,
iam getting error for below.

$Group = [ADSI]"WinNT://$($Env:gpri14d12121)/IIS_WPG"
$Group.Add("WinNT://$($Env:abcd)/sysibdpribuilduserd")



Exception retrieving member "Add": "Unknown error (0x80005000)"
At C:\Vdir\VDir.ps1:214 char:11
+ $Group.Add( <<<< "WinNT://$($Env:csfb)/sysibdpribuilduserd")
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

We use $Env to get the Environmental Variables on the machine. In the case of the examples above we get %ComputerName% and %UserDomain% which means we don't have to hard-code values unless we want to.

If you want to pop in the domain, or computer, name to make it static it would be:

$Group = [ADSI]"WinNT://gpri14d12121/IIS_WPG"

And so on.

Chris

Author

Commented:
Thanks Chris.  I have one more question for you.
Powershell script only.
I have one file from where iam reading version number: which is starting with 1.0.0.0
I need to increment this number by one . For example 1.0.0.1 , 1.0.0.1,..  like this . Iam able to do this till 1.0.0.10 But After that its behaving differently.
Iam attaching here  my code. After incrementing iam putting again in the file with latest version.
But after 10  its not working.
Also i need to increment last digit every day and 3 digit evry month , 2nd digit every quarter, 1st digit every year.
Is there any easy way ?


function replaceVersions([string]$assemblyFile)
{
# Get the whole line where AssemblyFileInfo exists 
#$version=(select-string -pattern AssemblyFileVersion $assemblyFile);
$version= get-content $assemblyFile | ?{$_ -match "AssemblyFileVersion"};
 
Write-output $version
$beginIndex=($version.IndexOf("(") + 1);
write-output $beginIndex
$version = $version.SubString($beginIndex, ($version.IndexOf()) - $beginIndex));
 
 
write-output "Current version is $version"
 
$currentversion=$version;
$minorVersionStartIndex = $version.LastIndexOf(.);
write-output $minorversionstartIndex
$majorVersion = $version.SubString(1, ($minorVersionStartIndex+1));
write-output "Major version is: $majorversion"
 
 
$fixversion=$version.SubString(1, ($minorVersionStartIndex));
 
$minorVersion = $version.SubString(($minorVersionStartIndex + 1), ($version.length - $minorVersionStartIndex -2));
write-output "fix version is: $fixversion"
write-output "Minor version is $minorversion"
$minorVersionInt = [Int32]$minorVersion;
$minorVersionInt++;
write-output "minor version int is $minorVersionInt"
$minorVersion =$minorVersionInt;
$finalversion=$fixVersion + $minorVersion;
write-output "new version is $finalversion"
$tempFile = $fileToFix + .temp;
get-content $fileToFix | set-content $tempFile;
$VersionOutputFile="Version.txt"
write-output $finalversion |set-content $VersionOutputFile
 
 # Set target file to writable
(Get-ChildItem $fileToFix).set_IsReadOnly( 0 );
 
get-content $tempFile | % { $_.Replace($majorversion, $finalversion) } | set-content $fileToFix;
 
}
 
 
$assemblyInfo = G:\BetaengineBuild\BetaEngine\Trunk\source\Client\BE.Client\Properties\AssemblyInfo.cs;
$fileToFix=G:\BetaengineBuild\BetaEngine\Trunk\source\Client\BE.Client\Properties\AssemblyInfo.cs;
 
replaceVersions $assemblyInfo;

Open in new window

Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

I can't help but wonder if it would be better to drop all but the major version and serialise a date instead (given the increment requirements you have). Otherwise I see problems trying to increment unless you set a base value up and compare with that before thinking about incrementing values.

Then you just have to choose what to do with the year. Either immediately increment it to match the current year (so 2009), or hard-code a starting point. The code below just preserves the major version at the moment.

For today that should give a version of 1.1.3.12 (1 major, 1st quarter, 3rd month, 12th day).

Any thoughts?

Chris
# Get current version (normally read with Get-Content)
$VersionText = "[assembly: AssemblyFileVersion(`"1.0.0.0`")]"
# Perform a Regular Expression search to return the quoted value from the string
# Void the boolean return
[Void]($VersionText -Match "`".*`"")
# Matches is a reserved variable, contains matches from a Regular Expression. Drop off quotes 
# using Replace (also regular expression, but nothing to it here)
$CurrentVersion = $Matches[0] -Replace "`""
 
# Rewrite the version based on the current date.
$NewVersion = "$($CurrentVersion.SubString(0, $CurrentVersion.IndexOf('.')))." + `
  "$([Math]::Ceiling(([DateTime]::Now).Month / 3)).$(([DateTime]::Now).Month)." + `
  "$(([DateTime]::Now).Day)"
 
Write-Host "Current Version: $CurrentVersion"
Write-Host "New version: $NewVersion"

Open in new window

Author

Commented:
Thaks Chris. One poitn here.
Last part of version.. I need to increment everytime i run . I mean suppose i run 10 times a day. I should i ncrement 1.1.3.12 to 1.1.3.22.

is it possibel?
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Sure, like this?

Chris
$VersionText = "[assembly: AssemblyFileVersion(`"1.0.0.0`")]"
 
[Void]($VersionText -Match "`".*`"")
$CurrentVersion = $Matches[0] -Replace "`""
 
$MinorVersion = $CurrentVersion.Split(".")
$MinorVersion = [Int]$MinorVersion[$MinorVersion.Count - 1]
 
$NewVersion = "$($CurrentVersion.SubString(0, $CurrentVersion.IndexOf('.')))." + `
  "$([Math]::Ceiling(([DateTime]::Now).Month / 3)).$(([DateTime]::Now).Month)." + `
  "$MinorVersion"
 
Write-Host "Current Version: $CurrentVersion"
Write-Host "New version: $NewVersion"

Open in new window

Author

Commented:
Perhaps we need to increment minor version. ??


$VersionText = "[assembly: AssemblyFileVersion(`"1.0.0.0`")]"
 
[Void]($VersionText -Match "`".*`"")
$CurrentVersion = $Matches[0] -Replace "`""
 
$MinorVersion = $CurrentVersion.Split(".")
$MinorVersion = [Int]$MinorVersion[$MinorVersion.Count - 1]

$MinorVersion=$MinorVersion +1
 
$NewVersion = "$($CurrentVersion.SubString(0, $CurrentVersion.IndexOf('.')))." + `
  "$([Math]::Ceiling(([DateTime]::Now).Month / 3)).$(([DateTime]::Now).Month)." + `
  "$MinorVersion"
 
Write-Host "Current Version: $CurrentVersion"
Write-Host "New version: $NewVersion"
 
Open in New Window
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Sorry, I totally forgot to actually increment the number! Just needs a + 1 adding as below.

Chris
$VersionText = "[assembly: AssemblyFileVersion(`"1.0.0.0`")]"
 
[Void]($VersionText -Match "`".*`"")
$CurrentVersion = $Matches[0] -Replace "`""
 
$MinorVersion = $CurrentVersion.Split(".")
$MinorVersion = [Int]$MinorVersion[$MinorVersion.Count - 1] + 1
 
$NewVersion = "$($CurrentVersion.SubString(0, $CurrentVersion.IndexOf('.')))." + `
  "$([Math]::Ceiling(([DateTime]::Now).Month / 3)).$(([DateTime]::Now).Month)." + `
  "$MinorVersion"
 
Write-Host "Current Version: $CurrentVersion"
Write-Host "New version: $NewVersion"

Open in new window

Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

lol yes, quite :) Sorry about that, got a bit distracted :)

Chris

Author

Commented:
Hi chris,
 sorry to bother y ou ,
Iam trying to give administrator ful control on one directory . But iam getting below error.

PS C:\Vdir> .\Permission.ps1
Set-Acl : Attempted to perform an unauthorized operation.
At C:\Vdir\Permission.ps1:5 char:8
+ Set-ACL  <<<< "D:\inetpub\wwwroot\GlobeArc2" -aclObject $ACL
$Rule =`New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl",@("ObjectInherit", "ContainerInherit"), "None", "Allow")`
 
$ACL = Get-ACL "D:\inetpub\wwwroot\GlobeArc2"
$ACL.AddAccessRule($Rule)
Set-ACL "D:\inetpub\wwwroot\GlobeArc2" -aclObject $ACL
 

Open in new window

Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Is it Windows 2003?

I guess you do have the rights to make the change? And does the code work through the regular shell rather than as a script?

Nothing wrong with your code in general, it executes perfectly here.

Chris

Author

Commented:
Hi Chris,
  I hope yo must be doing good.
Can you let me know how to change the settings of App pool to user different account rather then local account using PS script.

Sunil
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Should just be something like this...

Chris
$AppPoolName = "New"
 
$AppPool = [ADSI]"IIS://localhost/W3SVC/AppPools/$AppPoolName"
$AppPool.Put("AppPoolIdentityType", 3)
$AppPool.Put("WAMUserName", "SomeUser")
$AppPool.Put("WAMUserPass", "SomePassword")
$AppPool.SetInfo()

Open in new window

Author

Commented:
Thanks Chris

When iam tryin to pass parameter, its giving error saying

PS C:\Vdir> .\IdentityPool.ps1 -apppool PricingServer -userid csfb\sysibdpribuil
duserd -password inma85te
Method invocation failed because [System.String] doesn't contain a method named
 'Put'.
At C:\Vdir\IdentityPool.ps1:31 char:13
+ $AppPool.Put( <<<< "AppPoolIdentityType", 3)
Method invocation failed because [System.String] doesn't contain a method named
 'Put'.
At C:\Vdir\IdentityPool.ps1:32 char:13
+ $AppPool.Put( <<<< "WAMUserName", $userid)
Method invocation failed because [System.String] doesn't contain a method named
 'Put'.
At C:\Vdir\IdentityPool.ps1:33 char:13
+ $AppPool.Put( <<<< "WAMUserPass", $password)
Method invocation failed because [System.String] doesn't contain a method named
 'SetInfo'.
At C:\Vdir\IdentityPool.ps1:34 char:17
+ $AppPool.SetInfo( <<<< )


Below is the script.


param (
      [switch]$help,
        [string]$apppool = {},            
        [string]$userid = {},
        [string]$password = {}
       )


if ( $help ) {
      "Usage: Admin.ps1 -apppool <string> -userid <userid> -password <string>"
      exit 0
}

if ( $apppool.Length -eq 0 ) {
      "Please enter apppool  name."
      exit 1
}

if ( $userid.Length -eq 0 ) {
      "Please enter user."
      exit 1
}
if ( $password.Length -eq 0 ) {
      "Please enter password."
      exit 1
}

$AppPoolName = $apppool
 
$AppPool = [ADSI]"IIS://localhost/W3SVC/AppPools/$AppPoolName"
$AppPool.Put("AppPoolIdentityType", 3)
$AppPool.Put("WAMUserName", $userid)
$AppPool.Put("WAMUserPass", $password)
$AppPool.SetInfo()
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

You're passing AppPool as a string here:

        [string]$apppool = {},            

If you want to pass the name, make that:

        [string]$apppoolname = {},            

Because of that it thinks AppPool is a string rather than a DirectoryEntry.

Chris

Author

Commented:
But iam assigning that value in the script
$AppPoolName = $apppool



PS C:\Vdir> .\IdentityPool.ps1 -Apppool ssss -userid xxx -password aaa



$AppPoolName = $apppool
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

It just needs to use a separate variable name, its having problems reusing the parameter value (because it's hard-set as a String type).

Modified below, should work like this.

Chris
param (
      [switch]$help,
        [string]$apppool = {},            
        [string]$userid = {},
        [string]$password = {}
       )
 
 
if ( $help ) {
      "Usage: Admin.ps1 -apppool <string> -userid <userid> -password <string>"
      exit 0
}
 
if ( $apppool.Length -eq 0 ) {
      "Please enter apppool  name."
      exit 1
}
 
if ( $userid.Length -eq 0 ) {
      "Please enter user."
      exit 1
}
if ( $password.Length -eq 0 ) {
      "Please enter password."
      exit 1
}
 
$IISAppPool = [ADSI]"IIS://localhost/W3SVC/AppPools/$AppPool"
$IISAppPool.Put("AppPoolIdentityType", 3)
$IISAppPool.Put("WAMUserName", $userid)
$IISAppPool.Put("WAMUserPass", $password)
$IISAppPool.SetInfo()

Open in new window

Author

Commented:
Hi Chris,
Thanks for your help.
I need one more help.
Do you have any idea about changing windows service logon account using windows powershell script. right now we are using local account to run windows services.

Thanks

Author

Commented:
Hi Chris,
Any help?
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Sorry, forgot to pop a note up.

It should work with....

(Get-WMIObject Win32_Service -Filter "Name='TheServiceName'").Change($Null, $Null, $Null, $Null, $Null, `
  $Null, $Username, $Password, $Null, $Null, $Null)

The Change Method has rather a lot of parameters, all those $Null entries just leave the value at the current. We just change StartName and StartPassword.

You should get an object back, hopefully the Return Value will be 0, indicating success.

Chris

Author

Commented:
Thanks Chris.  I got Below message.
__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Good, that indicates success :)

If you don't want the response you can assign it to a variable or void the entire thing... one of:

$Return = (Get-WMIObject Win32_Service -Filter "Name='TheServiceName'").Change( `
  $Null, $Null, $Null, $Null, $Null, $Null, $Username, $Password, $Null, $Null, $Null)

If ($Return.ReturnValue -eq 0) {
  Write-Host "Success"
} else {
  Write-Host "Failure: $($Return.ReturnValue)"
}

Or voiding it:

[Void](Get-WMIObject Win32_Service -Filter "Name='TheServiceName'").Change( `
  $Null, $Null, $Null, $Null, $Null, $Null, $Username, $Password, $Null, $Null, $Null)

Which just drops any kind of return value.

Chris

Author

Commented:
Hi Chris,
Thanks. I was able to update the service logon account , but some how password is not updated. I had to set it up manually for Windows service Logon.
Any reason why?
param ( 
	[switch]$help,
        [string]$username = {},		
        [string]$password = {},
        [string]$servicename = {}
       )
 
 
if ( $help ) {
	"Usage: Admin.ps1 -username <string> -password <string> -servicename <string>"
	exit 0
}
 
if ( $username.Length -eq 0 ) {
	"Please enter username with domain."
	exit 1
}
 
if ( $Password.Length -eq 0 ) {
	"Please enter Password."
	exit 1
}
 
 
if ( $servicename.Length -eq 0 ) {
	"Please enter service name."
	exit 1
}
 
 
 
(Get-WMIObject Win32_Service -Filter "Name='$servicename'").Change($Null, $Null, $Null, $Null, $Null, `
  $Null, $Username, $Password, $Null, $Null, $Null)

Open in new window

Author

Commented:
Can we just start services from script itself? so that we can know if it updated password as welll?
Chris DentPowerShell Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Hey,

Sure, you'll find there's a StartService and StopService method for the WMI object:

Chris
$Service = Get-WMIObject Win32_Service -Filter "Name='TheServiceName'"
 
# Change the username and password
$Return = $Service.Change( `
  $Null, $Null, $Null, $Null, $Null, $Null, $Username, $Password, $Null, $Null, $Null)
 
# Stop the service
$Service.StopService()
 
# Start the service
$Service.StartService()

Open in new window

Author

Commented:
Chris,
it seems issue with ` in the commmand

PS C:\> .\ChangeWinService.ps1 -help
Missing ')' in method call.
At C:\ChangeWinService.ps1:35 char:27
+ $Return = $Service.Change(` <<<< $Null, $Null, $Null, $Null, $Null, $Null, $U
sername, $Password, $Null, $Null, $Null)
param ( 
	[switch]$help,
        [string]$username = {},		
        [string]$password = {},
        [string]$servicename = {}
       )
 
 
if ( $help ) {
	"Usage: Admin.ps1 -username <string> -password <string> -servicename <string>"
	exit 0
}
 
if ( $username.Length -eq 0 ) {
	"Please enter username with domain."
	exit 1
}
 
if ( $Password.Length -eq 0 ) {
	"Please enter Password."
	exit 1
}
 
 
if ( $servicename.Length -eq 0 ) {
	"Please enter service name."
	exit 1
}
 
 
$Service = Get-WMIObject Win32_Service -Filter "Name='$Servicename'"
 
$Service.StopService()
 
$Return = $Service.Change(`$Null, $Null, $Null, $Null, $Null, $Null, $Username, $Password, $Null, $Null, $Null)
 
If ($Return.ReturnValue -eq 0) {
  Write-Host "Success"
} else {
  Write-Host "Failure: $($Return.ReturnValue)"
}
 
 
$Service.StartService()
 
 
#(Get-WMIObject Win32_Service -Filter "Name='$servicename'").Change($Null, $Null, $Null, $Null, $Null, `
  $Null, $Username, $Password, $Null, $Null, $Null)

Open in new window

Author

Commented:
Hi Chris,
any update?

Author

Commented:
Chris,
Can you also help in issues with website remapping?

Idea is to repoint website to use different virtual directory via script.

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.