Home
Manage Your Code
Snippet: PS Deploy Service Files Script (PowerShell)
Title: PS Deploy Service Files Script Language: PowerShell
Description: This script will stop a service, move files to a destination location, then restart the service. Good for deploying during development. Views: 98
Author: Michael Wood Date Added: 4/22/2008
Copy Code  
&{
if (-not ([appdomain]::CurrentDomain.getassemblies() |? {$_.ManifestModule -like “system.serviceprocess”})) {[void][System.Reflection.Assembly]::LoadWithPartialName(’system.serviceprocess’)}

$AppServer = "NameOfServerRunningService"
$ServiceName = "NameOfService"
#Names of files you want to move.  If you don't want to filter then remove this and the filter from the copy-item command.
$IncludeFilesToMoveFilter = "FileNames", "YouWantToMove"
$SourceDirectory = "SourceLocation"
$DestinationDirectory = "WhereAreYouDeployingTo"

Write-Output "Stopping Service ($ServiceName) on $AppServer"
#Stop the remote service
(new-Object System.ServiceProcess.ServiceController($ServiceName,$AppServer)).Stop() 
(new-Object System.ServiceProcess.ServiceController($ServiceName,$AppServer)).WaitForStatus('Stopped',(new-timespan -seconds 5)) 
Write-Output "Stopped Service ($ServiceName) on $AppServer"

#Copy the Required files.
Write-Output "Copying Files..."
copy-item  $SourceDirectory  $DestinationDirectory -include $IncludeFilesToMoveFilter -force
Write-Output "Files Deployed."

Write-Output "Restarting Service ($ServiceName) on $AppServer"
#Start the Remote Service
(new-Object System.ServiceProcess.ServiceController($ServiceName,$AppServer)).Start() 
(new-Object System.ServiceProcess.ServiceController($ServiceName,$AppServer)).WaitForStatus('Running',(new-timespan -seconds 5)) 
Write-Output "Started Service ($ServiceName) on $AppServer"

Write-Host "Press any key to continue ..."

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

}
Usage
Replace the variable values at the top with the locations and file names.  If you want to filter the files you are copying do so with the $IncludeFilesToMoveFilter string array.  otherwise you can remove the $IncludeFilesToMoveFilter and -include parameter on copy-item.

This pauses the service, copies the files and the restarts the service.  Ths script then waits for the user to press a key to end.
Notes
I set this up in a shortcut that looked like this: %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -command & 'C:\pathToScript\Deploy-Service.ps1'