Use a PowerShell Script as a Startup Task
Updated: November 13, 2013
You can use PowerShell scripts to perform startup tasks for your Web roles and worker roles. PowerShell scripts can provide significant power and flexibility for startup tasks.
PowerShell scripts can't be called directly from the ServiceDefinition.csdef file, but they can be invoked from within a startup batch file.
PowerShell, by default, will not run an unsigned script. Unless you sign your scripts (by default, they are unsigned), you will need to configure PowerShell to run unsigned PowerShell scripts. To run unsigned PowerShell scripts, the ExecutionPolicy must be set to Unrestricted. There are different methods of setting ExecutionPolicy based on the version of PowerShell you use.
The version of PowerShell available to your role is based on the osFamily setting in your ServiceConfiguration.csdef file:
osFamily="1" which is substantially compatible with Windows Server 2008 SP2, contains PowerShell version 1.0. This is the default.
osFamily="2" which is substantially compatible with Windows Server 2008 R2, contains PowerShell version 2.0.
If you know the PowerShell version you are using on your role, you can invoke your PowerShell script with an ExecutionPolicy of Unrestricted by using the parameter for that specific version of PowerShell.
If you aren't sure of the version of PowerShell you will be using, or if you want to make your startup batch file independent of the version of PowerShell, you can add logic to your startup batch file to allow you to execute your PowerShell script with an ExecutionPolicy of Unrestricted regardless of the PowerShell version.
Running PowerShell 2.0 with the -Version 2.0 parameter will execute the PowerShell script as a version 2.0 script. However, running PowerShell 1.0 with -Version 2.0 will result in an error, and PowerShell will exit with an errorlevel of -393216. When this errorlevel is detected, the PowerShell 1.0 syntax can be used to execute the PowerShell script.
The following is an example of how to invoke a PowerShell script with an execution policy of Unrestricted, regardless of the version of PowerShell:
REM Attempt to set the execution policy by using PowerShell version 2.0 syntax. PowerShell -Version 2.0 -ExecutionPolicy Unrestricted .\startup.ps1 >> "%TEMP%\StartupLog.txt" 2>&1 IF %ERRORLEVEL% EQU -393216 ( REM PowerShell version 2.0 isn't available. Set the execution policy by using the PowerShell version 1.0 calling method. PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "%TEMP%\StartupLog.txt" 2>&1 PowerShell .\startup.ps1 >> "%TEMP%\StartupLog.txt" 2>&1 ) REM If an error occurred, return the errorlevel. EXIT /B %errorlevel%