Tag Archives: iis

How i automate website creation with Powershell

If you, like me, create lots and lots of websites almost every day you probably noticed that a lot of the things you do are repetitive.

I have a lot of rules that almost all my websites follow.

  • I name the pool, the site and the folder the same (like site.domain.com)
  • I always add a binding following the pattern 17000 + site id, so a site with site id 13 has a binding for localhost:17013
  • I set idle time-out to 0
  • I add a scheduled recycle at 02:00 (for load balanced environments att set it at 03:00 for the other node)
  • I always create a scheduled job to take care of log rotation

To avoid making misstakes, and to make sure it gets done the same way every time, i use this Powershell. It’s not perfect, but it works for me, and it does exactly what i need it to.

In the end of the script, where the scheduled job is created, i use a little application called LogRotate which i may publish on the internet. In the mean time, you can use it as a way to add a scheduled task.

Maybe it will work for you as well, or maybe you can pick the parts you need. Enjoy!

#
# PowerShell Script used to create new websites. Requires Eleveted PowerShell Console!
# This script: 
# 	- Creates a new Applicatiopn Pool with our preferred settings
#	- Creates a new website using that pool
#	- Create a scheduled job to manage logfiles
#
# Make sure to edit these parameters before you run the script:
# - $AppPoolName Sets the name of AppPool and WebSite
# - $AppPoolIdentityName and $AppPoolIdentityPwd to set the identity
# - $SiteDirectory is the base path to the folder holding websites
#

#########################
# Import modules needed #
#########################

Import-Module WebAdministration

######################
# Set all parameters #
######################

#AppPool parameters

$AppPoolName 			= "Test.Domain.Com"	            #Name of ApplicationPool
$AppPoolDotNetVersion 	= "v4.0"						#.NET version for pool
$UseAppPoolIdentity     = 0                             #Set to 1 to user app-pool identity instead of domain account
$AppPoolIdentityName 	= "domain\sysAccount"			#Identity to execute pool
$AppPoolIdentityPwd 	= "P@ssw0rd"					#Identity password
$AppPoolRecycleTime		= "02:00"						#Default time is 02:00, on load balanced environments, set first host to 02:00 and second to 03:00

#WebSite parameters
$SiteName 				= $AppPoolName					#WebSite name, by default the same as name of pool
$SiteDirectory 			= "C:\WebSite\WebSite\Sites\"	#Base folder, where the site should be created. Site folder is created automatically

###########################
# Create application pool #
###########################

#Create Pool and store it in $AppPool
New-WebAppPool ñName $AppPoolName
$AppPool = Get-Item IIS:\AppPools\$($AppPoolName) 

#Stop AppPool
$AppPool | Stop-WebAppPool 

#Set additional properties
#Set AppPool Identity and password
if($UseAppPoolIdentity -eq 0)
{
    $AppPool.ProcessModel.identityType = 3
    $AppPool.ProcessModel.Username = $AppPoolIdentityName 
    $AppPool.ProcessModel.Password = $AppPoolIdentityPwd
}

#Set idle time-out to zero
$AppPool.ProcessModel.IdleTimeout = "0"

#Set desired .NET version
$AppPool.ManagedRuntimeVersion = $AppPoolDotNetVersion

#Set periodic recycle schedule
Set-ItemProperty -Path IIS:\AppPools\$($AppPoolName) -Name Recycling.periodicRestart.schedule -Value @{value=$AppPoolRecycleTime}

#Save and start AppPool
$AppPool | Set-Item
$AppPool | Start-WebAppPool

#Clear periodic restart time (defaults to 1740 minutes)
Set-ItemProperty -Path IIS:\AppPools\$($AppPoolName) -Name Recycling.periodicRestart.time -Value "00:00:00"


##################
# Create website #
##################

#Create Website Directory
New-Item -ItemType directory -Path "$($SiteDirectory)$($SiteName)"

#Create Website and set default binding
New-Website -Name $SiteName -PhysicalPath "$($SiteDirectory)$($SiteName)" -ApplicationPool $AppPoolName -Port "170$($WebSite.id)" -HostHeader "" -IPAddress "*"

#Get the newly created website and store it in $WebSite
$WebSite = Get-Item IIS:\Sites\$($SiteName) 

#Set additional binding based on AppPool name
New-WebBinding -Name $SiteName -IPAddress "*" -Port 80 -HostHeader $AppPoolName.ToLower()

#Start Website
$WebSite | Start-WebSite


######################################
# Create scheduled job for LogRotate #
# This only works on Win2012         #
######################################
#Scheduled task, LogRotate
#Theese values shouldn't be neccesarry to edit. 
#Make sure LogRotate exists under Program Files and that you WebSite-folder point to the correct location.
$TaskName 				= "LogRotate W3SVC$($WebSite.id)"
$TaskDescription 		= "Archives old logfiles for site $($SiteName)"
$TaskActionCommand		= "C:\Program Files\LogRotate\LogRotator.App.exe"
$TaskArguments			= "C:\WebSite\Logs\W3SVC$($WebSite.id) C:\WebSite\Logs\Backup W3SVC$($WebSite.id) *.log 31 true"
$TaskPath				= "LogRotate"

$PsHost = host
$OsVer = [environment]::OSVersion.Version

If(($OsVer.Major -ge 6) -and ($OsVer.Minor -ge 2) -and ($PsHost.Version.Major -ge 4))
{
    Import-Module ScheduledTasks 
	$TaskAction = New-ScheduledTaskAction -Execute $TaskActionCommand -Argument $TaskArguments
	$TaskTrigger = New-ScheduledTaskTrigger -Daily -AT "05:00"
	$Task = New-ScheduledTask -Action $TaskAction -Trigger $TaskTrigger -Description $TaskDescription
	Register-ScheduledTask $TaskName -InputObject $Task -TaskPath $TaskPath
}
Else
{
	"You need a PowerShell 4 and Windows Server 2012 to create Scheduled Task!"
	"You'll need to configure LogRotate manually."
}

 

How to create Websites (and more) with PowerShell?

If you, like me, are maintaining lots of websites, you probably want to script as much as you can. It’s time consuming to change a setting for 20+ websites, and it’s also a great chance you miss something in the process.

PowerShell is really neat in these cases, and it gets better for every new release as well.

This is a script i use to do the following:

  1. Create a new application pool, with the preferred .NET version, identity and a few other settings
  2. Create a folder to hold the website
  3. Create the website
  4. Configure a scheduled task to rotate and archive log files.

This script is highly customized for my needs and my environment. As you can se there’s a lot of assumptions in the script, that you may want to change, but i may be a nice start for you!

#
# PowerShell Script used to create new websites. Requires Eleveted PowerShell Console!
# This script: 
# 	- Creates a new Applicatiopn Pool with our preferred settings
#	- Creates a new website using that pool
#	- Create a scheduled job to manage logfiles
#
# Make sure to edit these parameters before you run the script:
# - $AppPoolName Sets the name of AppPool and WebSite
# - $AppPoolIdentityName and $AppPoolIdentityPwd to set the identity
# - $SiteDirectory is the base path to the folder holding websites
#

#########################
# Import modules needed #
#########################

Import-Module WebAdministration

#####################
# Usefull Functions #
#####################

#Get the next website-id from IIS. You should override this if you use random ids, or if your sites isn't in order!
Function Get-NextSiteId {
	$MaxId = Get-Website | Measure-Object -Property ID -Maximum
	return $id.Maximum + 1	
}

######################
# Set all parameters #
######################

#AppPool parameters

$AppPoolName 			= "Test.Domain.Com"	#Name of ApplicationPool, Should be the same as the name of the website (Eg. Soot.Msb.Se)!
$AppPoolDotNetVersion 	= "v4.0"						#.NET version for pool
$AppPoolIdentityName 	= "domain\sysAccount"			#Identity to execute pool
$AppPoolIdentityPwd 	= "P@ssw0rd"					#Identity password

#WebSite parameters
$SiteName 				= $AppPoolName					#WebSite name, by default the same as name of pool
$SiteDirectory 			= "C:\WebSite\Sites\"	#Base folder, where the site should be created. Site folder is created automatically
$SiteId					= Get-NextSiteId				#Get next free ID, change this manually if needed, eg. if you are using random id.

#Scheduled task, LogRotate
#Theese values shouldn't be neccesarry to edit. 
#Make sure LogRotate exists under Program Files and that you WebSite-folder point to the correct location.
$TaskName 				= "LogRotate W3SVC$($SiteId)"
$TaskDescription 		= "Archives old logfiles for site $($SiteName)"
$TaskActionCommand		= "C:\Program Files\LogRotate\LogRotator.App.exe"
$TaskArguments			= "C:\WebSite\Logs\W3SVC$($SiteId) C:\WebSite\Logs\Backup W3SVC$($SiteId) *.log 31 true"
$TaskPath				= "LogRotate"

###########################
# Create application pool #
###########################

#Create Pool and store it in $AppPool
New-WebAppPool –Name $AppPoolName
$AppPool = Get-Item IIS:\AppPools\$($AppPoolName) 

#Stop AppPool
$AppPool | Stop-WebAppPool 

#Set additional properties
#Uncomment these three lines to user AppPoolIdentity
$AppPool.processModel.identityType = 3
$AppPool.ProcessModel.Username = $AppPoolIdentityName 
$AppPool.ProcessModel.Password = $AppPoolIdentityPwd

$AppPool.ProcessModel.IdleTimeout = "0"
$AppPool.ManagedRuntimeVersion = $AppPoolDotNetVersion

#Save and start AppPool
$AppPool | Set-Item
$AppPool | Start-WebAppPool

##################
# Create website #
##################

#Create Website Directory
New-Item -ItemType directory -Path "$($SiteDirectory)$($SiteName)"

#Create Website and store it in $WebSite
New-Website -Name $SiteName -PhysicalPath "$($SiteDirectory)$($SiteName)" -ApplicationPool $AppPoolName -Port "170$($SiteId)" -HostHeader "localhost"
$WebSite = Get-Item IIS:\Sites\$($SiteName) 

#Start Website
$WebSite | Start-WebSite

######################################
# Create scheduled job for LogRotate #
# This only works on Win2012         #
######################################

$PsHost = host
$OsVer = [environment]::OSVersion.Version

If(($OsVer.Major -ge 6) -and ($OsVer.Minor -ge 2) -and ($PsHost.Version.Major -ge 4))
{
    Import-Module ScheduledTasks 
	$TaskAction = New-ScheduledTaskAction -Execute $TaskActionCommand -Argument $TaskArguments
	$TaskTrigger = New-ScheduledTaskTrigger -Daily -AT "05:00"
	$Task = New-ScheduledTask -Action $TaskAction -Trigger $TaskTrigger -Description $TaskDescription
	Register-ScheduledTask $TaskName -InputObject $Task -TaskPath $TaskPath
}
Else
{
	"You need a PowerShell 4 and Windows Server 2012 to create Scheduled Task!"
	"You'll need to configure LogRotate manually."
}