如果在云服务程序启动时候,需要执行Powershell脚本,我们需要将脚本嵌入到程序中,并且编写一个cmd来执行这个脚本,具体如下:
1.编写测试的Powershell脚本:每隔10分钟 检测dns
$TimeStart = Get-Date $TimeEnd = $timeStart.addminutes(1440) $name = "cnppmedia.blob.core.chinacloudapi.cn." $result = "d: slookuplog.txt" Write-Host "Start Time: $TimeStart" write-host "End Time: $TimeEnd" Do { $TimeNow = Get-Date if ($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.编写一个cmd文件来执行这个脚本:
echo Configuring powershell permissions powershell -c "set-executionpolicy unrestricted" echo start test dns PowerShell . estdns.ps1 if %ERRORLEVEL% neq 0 goto error echo SUCCESS exit /b 0
3.将这2个文件嵌入到程序中,并且都设置"Copy always"属性:
4.修改csdef文件,添加启动任务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="80" /> </Endpoints> </WebRole> </ServiceDefinition>
因为测试的powershell脚本要连续执行一段时间,所以需要将任务类型设置为background,否则无法完成部署