Use a PowerShell Script as a Startup Task
Updated: May 29, 2014
You can use PowerShell scripts to perform startup tasks for instances of web roles and worker roles. Windows PowerShell scripts can provide significant power and flexibility for startup tasks.
Windows PowerShell scripts cannot be called directly from the ServiceDefinition.csdef file, but they can be invoked from within a startup batch file.
Windows PowerShell, by default, will not run an unsigned script. Unless you sign your scripts, you need to configure Windows PowerShell to run unsigned scripts. To run unsigned scripts, ExecutionPolicy must be set to Unrestricted. The ExecutionPolicy setting that you use is based on the version of Windows PowerShell.
The version of Windows PowerShell that is available to a role instance is based on the osFamily setting in the ServiceConfiguration.csdef file. For more information about operating system families and versions, see Azure Guest OS Releases and SDK Compatibility Matrix.
If you know the Windows PowerShell version that the role instance is using, you can invoke a script with an ExecutionPolicy of Unrestricted by using the parameter for that specific version of Windows PowerShell.
If you do not know the version of Windows PowerShell that is being used, you can add logic to your startup batch file that allows the script to run with an ExecutionPolicy of Unrestricted regardless of the PowerShell version.
Running Windows PowerShell 2.0 with the -Version 2.0 parameter will execute the script as a version 2.0 script. However, running Windows PowerShell 1.0 with -Version 2.0 will result in an error with an errorlevel of -393216. When this errorlevel is detected, the 1.0 syntax can be used to run the script.
The following is an example of a startup.cmd file that is used to invoke a script with an execution policy of Unrestricted, regardless of the version of Windows 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%