Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Операционные системы > Операционные системы общие вопросы
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 22.06.2012, 13:52   #1
ds.Dante
Старожил
 
Аватар для ds.Dante
 
Регистрация: 06.08.2009
Сообщений: 2,992
По умолчанию Мой первый скрипт на PowerShell

Скрипт билдит и разворачивает БД/сервис/клиент и запускает всё это для проверки. Прошу ревизии на предмет оптимальности, стиля, и т. д.

Код:
$iipDir = ".\.."
$projectDir="$iipDir\Sources"
$dbProjectDir="$iipDir\Database\IIP.DB"
$dotNetDir="$env:SystemRoot\Microsoft.NET\Framework\v4.0.30319"
$serviceName="IIP Web Service"
$logfile="IIPDeploy.log"

################# Write datetime to log and exit
function Finish([int]$code)
{
	$datetime = Get-Date -format "MMMM dd, yyyy  hh:mm:ss"
	"Finished with code $code at  $datetime" >> "$logfile"
	exit $code
}

################ Error handling
function ErrorExit([int]$code, [string]$message)
{
	if ($message -eq "")
	{
		"***** Error" >> "$logfile"
	}
	else
	{
		"***** Error: $message" >> "$logfile"
	}

	$Error[0] >> "$logfile"
	
	Finish $code
}

################ Script body start
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
	ErrorExit -message "administrator rights are required"
}
cd (Split-Path $MyInvocation.MyCommand.Path)
cls
Out-File "$logfile"
$datetime = Get-Date -format "MMMM dd, yyyy  hh:mm:ss"
"Started at  $datetime" >> "$logfile"

############### Install MSMQ service
[Reflection.Assembly]::LoadWithPartialName("System.Messaging") > $null
$queue = '.\private$\LogQueue'
$msmq = [System.Messaging.MessageQueue]
try
{
	$msmq::Exists($queue) > $null
}
catch
{
	"Installing MSMQ..." >> "$logfile"
	ocsetup.exe "MSMQ-Container;MSMQ-Server" /norestart /passive
	"MSMQ installation is done; restart computer and rerun this script"
	Finish
}

############# Create queue
if($msmq::Exists($queue))
{
	"Deleting old queue" >> "$logfile"
    $msmq::Delete($queue)
	if (!$?) { ErrorExit $lastExitCode "cannot delete old queue" }
}
"Creating queue" >> "$logfile"
$msmq::Create($queue, $true)
if (!$?) { ErrorExit $lastExitCode "cannot create queue" }

################# Stop and delete service
$service = Get-Service $serviceName -ErrorAction SilentlyContinue
if ($service -ne $null) # service exists and should be deleted
{
	if ($service.Status -eq "running")
	{
		"Stopping {0}" -f $service.DisplayName >> "$logfile"
		Stop-Service $serviceName
	}
	"Deleting {0}" -f $service.DisplayName >> "$logfile"
	sc.exe delete $serviceName >> "$logfile"
	if (!$?) { ErrorExit $lastExitCode "cannot delete service" }
}

################# Deleting databases
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") > $null
$smoServer = New-Object Microsoft.SqlServer.Management.Smo.Server(".")
if ($smoServer.Databases.Contains("Configuration"))
{
	"Deleting database Configuration" >> "$logfile"
	$smoServer.KillDatabase("Configuration")
	if (!$?) { ErrorExit $lastExitCode "cannot delete database Configuration" }
}
if ($smoServer.Databases.Contains("IIP"))
{
	"Deleting database IIP" >> "$logfile"
	$smoServer.KillDatabase("IIP")
	if (!$?) { ErrorExit $lastExitCode "cannot delete database IIP" }
}

################# Build and deploy databases and fill IIP with test data
"Building database project" >> "$logfile"
&"$dotNetDir\MSBuild.exe" "$dbProjectDir\IIP.DB.Deploy.xml" /t:DeployAll /v:minimal /nologo >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "cannot build & deploy databases" }
sqlcmd -i "$projectDir\zTest\FillIncidents.sql" >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "cannot fill database with test data" }

################# Create and fill IIPWebClient database
&"$dotNetDir\aspnet_regsql.exe" -d IIPWebClient -A m -A r -A p -E -S . >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "cannot fill database with test data" }
sqlcmd -i "$iipDir\Database\WebClientManager.sql" >> "$logfile"

################# Build IIP
&"$dotNetDir\MSBuild.exe" "$projectDir\IIP.sln" /p:Configuration="Release" /p:RunCodeAnalysis="False" /v:minimal /nologo >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "IIP build failed" }

################# Register and run service
"Install and run service" >> "$logfile"
xcopy.exe /e /i /y "$projectDir\WebService\bin\Release" "$projectDir\WebService\bin\LocalService" >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "cannot copy service files" }
$servicePath = Convert-Path "$projectDir\WebService\bin\LocalService\IIP.WebService.exe"
New-Service "$serviceName" "$servicePath" >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "cannot install service" }
Start-Service "$serviceName" >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "cannot start service" }
ds.Dante вне форума Ответить с цитированием
Старый 22.06.2012, 13:52   #2
ds.Dante
Старожил
 
Аватар для ds.Dante
 
Регистрация: 06.08.2009
Сообщений: 2,992
По умолчанию

продолжение...

Код:
################# Stopping any IIS local site
Import-Module WebAdministration
foreach ($site in Get-Website)
{
	$http = $site.bindings.collection | where {$_.protocol -eq "http"}
	if ($http.bindingInformation -eq "*:80:" -and $site.state -eq "Started")
	{
		"Stopping site {0}" -f $site.name >> "$logfile"
		$site.Stop()
		if (!$?) { ErrorExit $lastExitCode "cannot stop site {0}" -f $site.name }
	}
	Remove-Variable site  #hack for PowerGUI bug
}

################# Recreate web site IIP
# PowerShell bug: "Get-Website -name" is not working
if (Get-Website | where {$_.Name -eq "IIP"})
{
	"Removing web site IIP" >> "$logfile"
	Remove-Website "IIP"
	if (!$?) { ErrorExit $lastExitCode "cannot remove web site IIP" }
}
"Creating web site IIP" >> "$logfile"
$sitePath = Convert-Path "$projectDir\IIPWebApp"
New-Website "IIP" -physicalPath "$sitePath" -applicationPool "ASP.NET v4.0" >> "$logfile"
if (!$?) { ErrorExit $lastExitCode "cannot create web site IIP" }

start http://localhost
Finish
ds.Dante вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
скрипт для бэкапа (PowerShell) Айат Помощь студентам 0 24.02.2012 14:40
не работает скрипт на Powershell Rohan Общие вопросы .NET 0 02.08.2011 13:27
мой сайт взломали и в коды скриптов добавили вот этот скрипт. Что за скрипт? nsbox JavaScript, Ajax 9 21.01.2010 18:19