One feature Azure offers for getting your boxes configured is the notion of startup tasks – I won’t go into too much detail here as there is lots available online e.g. https://msdn.microsoft.com/en-us/library/azure/hh180155.aspx
As part of setting these up I thought I’d share a few tips / gotchas that caught me out when running powershell from the cmd tasks.
My solution setup was:
- Site root
- StartupScripts
- Script.cmd
- Script.ps1
- StartupScripts
So then I’d reference in the task:
<Task commandLine=”StartupScripts\script.cmd” executionContext=”elevated” taskType=”simple” />
Nothing rocket science so far! So, why didn’t the script work? I could jump on the box and run the cmd and it would be fine.
How to debug the process?
I found the most useful way was to add markers from the cmd and the ps1. The cmd file looked like:
1 2 3 4 5 |
md c:\test echo "Running" > "c:\test\log.txt" powershell -command "Set-ExecutionPolicy Unrestricted" 2>> "c:\test\log.txt" powershell .\startupScripts\script.ps1 %~dp0 2>> "c:\test\log.txt" EXIT /B 0 |
Note, the .\startupScripts part of the ps1 path is v important!
Then the powershell:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
$tempFolder = "c:\test" $logFile = "ps_log.txt" $siterootFolder = "\sitesroot\0\" If (!(Test-Path "e:\")) { $siterootFolder = "f:" + $siterootFolder } else { $siterootFolder = "e:" + $siterootFolder } function Write-Log { param( [string] $text ) Write-Host $text; $path = [System.IO.Path]::Combine("$tempFolder\$logFile") $fs = New-Object IO.FileStream($path, [System.IO.FileMode]::Append, [System.IO.FileAccess]::Write, [IO.FileShare]::Read) $sw = New-Object System.IO.StreamWriter($fs) $sw.WriteLine($text) $sw.Dispose() $fs.Dispose() } Write-Log "Output folder is $siterootFolder" |
Note, if you try to write to log.txt you will get process locked exceptions as the cmd holds locks on the file.
There are all sorts of techniques for writing to a file, this example uses a StreamWriter. Hit up google for different examples.