How to recreate web application in SharePoint by Powershell

Some times you might need to recreate a web application (probably on you development box) to do a complete deployment and don’t want to go through all the those options in Central Administration. here is the PowerShell code. Just put your specific values save it into a .ps1 file and run it whenever you want:

# First the SharePoint Snapin
$snapin = Get-PSSnapin | ? { $_.Name -like "Microsoft.SharePoint.PowerShell"; }
if ($snapin -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"         `
-Verbose:$false                         `
-ErrorAction SilentlyContinue             `
-ErrorVariable err;

if (![string]::IsNullOrEmpty($err))
{ Write-Host $err; $result = $false; }
else
{  Write-Host "SnapIn successfully added";  $result = $true;  }
}
else
{  Write-Host "SnapIn already added"; $result = $true; }

# This function first deletes the web app if it exists
# Then tries to create it again
function RecreateWebApp([string]$webAppUrl,
[string]$webAppName,
[string]$appPoolAccount,
[string]$dbName,
[string]$hostHeader,
[int]$port)
{
$exists = (Get-SPWeb $webAppUrl -ErrorAction SilentlyContinue) -ne $null;

if ($exists)
{
Remove-SPWebApplication -Identity $webAppUrl -DeleteIISSite -RemoveContentDatabases;
}
New-SPWebApplication -Name $webAppName -ApplicationPool $webAppName -ApplicationPoolAccount $appPoolAccount -DatabaseName $dbName -HostHeader $hostHeader -Port 80;
}

# Change the following to include your specific settings:
RecreateWebApp "http://www.contoso.com" "Contoso" "Admin" "Contoso_Content" "www.contoso.com" 80;
How to recreate web application in SharePoint by Powershell