If the PowerShell script needs to be executed at the start of the cloud service program, we need to embed the script in the program and write a cmd to execute the script, as follows:
1. Writing a test PowerShell script: Detecting DNS every 10 minutes
$TimeStart= get-Date$TimeEnd=$timeStart. AddMinutes (1440)$name="cnppmedia.blob.core.chinacloudapi.cn."$result="D:\nslookuplog.txt"Write-host"Start time: $TimeStart"Write-host"End time: $TimeEnd" Do { $TimeNow= get-Dateif($TimeNow -ge $TimeEnd) {Write-host"It ' s time to finish." } Else{try {Write-host"===========nslookup====current Time: $ (get-date) =============="Invoke-command-scriptblock{Write-output"===========test at Azure ====current time: $ (get-date) =============="| Out-file-filepath$result-append-Force } Invoke-command-scriptblock{nslookup$name| Out-file-filepath$result-append-Force }} Catch {}} Start-sleep-seconds 600 } Until($TimeNow -ge $TimeEnd)
2. Write a cmd file to execute the script:
" Set-executionpolicy Unrestricted " echo Start test Dnspowershell. \TESTDNS.PS1 if %errorlevel% neq 0/b 0
3. Embed the 2 files in the program and set the Copy always property:
4. Modify the Csdef file to add startup task startup
<?xml version="1.0"encoding="Utf-8"? ><servicedefinition name="testdnswithsdk26"xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"schemaversion="2015-04.2.6"> <webrole name="WebRole1"Vmsize="Small"> <Startup> <task commandline="Testdns.cmd"executioncontext="elevated"Tasktype="background"/> </Startup> <Sites> <site name="Web"> <Bindings> <binding name="Endpoint1"Endpointname="Endpoint1"/> </Bindings> </Site> </Sites> <ConfigurationSettings> <setting Name ="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"/> </ConfigurationSettings> <Endpoints> <inputendpoint name="Endpoint1"Protocol="http"port=" the"/> </Endpoints> </WebRole></ServiceDefinition>
The task type needs to be set to backgroundbecause the PowerShell script that is being tested is executed continuously for a period of time, otherwise the deployment cannot be completed
The Cloud service program executes PowerShell scripts when it is started