需要运行PowerShell脚本的Azure云服务启动任务

Azure Cloud Service Startup task that needs to run a PowerShell script

全部,

注意:经过一些反馈,我已经更新了问题。

感谢@jisaak到目前为止的帮助。

我需要运行PowerShell脚本,该脚本在部署Cloud Service时添加TCP绑定和其他一些内容。

这是我的云服务项目:

enter

这是我对Startup.cmd的尝试:
enter


我认为问题在于,批处理命令解释器在运行Startup.cmd时运行的工作目录与预期不符。

Startup.cmd位于\\approot\\bin\\Startup目录中,但工作目录为\\approot\\bin

因此,命令.\
oleStartup.ps1
无法在bin目录而不是bin\\Startup目录中查找RoleStartup.ps1。

我知道的解决方案是:

解决方案1:
使用..\\Startup\
oleStartup.ps1
从Startup.cmd调用RoleStartup.ps1。

替代品2:
在Startup.cmd中更改当前的工作目录,以便找到相对路径.\
oleStartup.ps1
。我通过CHDIR %~dp0(请参见此处)执行此操作,以切换到包含Startup.cmd的目录。

解决方案3:
正如Don Lockhart的答案所建议的那样,不要将Startup目录复制到输出中,而应在Visual Studio项目中将其设置为" Content"。这意味着其中的文件将存在于Azure实例的\\approot\\Startup目录中。 (然后,您将要确保Startup文件夹不能通过IIS公开访问!)。然后,将ServiceDefinition.csdef中对Startup.cmd的引用更新为..\\Startup\\Startup.cmd,并将Startup.cmd中对RoleStartup.ps1的引用更新为..\\Startup\
oleStartup.ps1
。这适用于以下事实:工作目录为bin,并使用..\\Startup始终查找相对于它的启动目录。


好,

因此,在进行了许多不同的尝试以使其工作之后,我将重新回到这一点。
我尝试使用:

  • ServiceDefinition.csdef中的启动配置
  • 我尝试在扫描Windows Azure日志的服务器上注册计划的任务,以查找[System [Provider [@ Name ='Windows Azure Runtime 2.6.0.0']和EventID = 10004]]

由于安全性或事件发生的时间以及IIS尚未完全设置,因此无济于事。

因此,我终于忍住了Bullets,并使用了我的Webrole.cs =>公共替代bool OnStart()方法:
enter

过去,我发现不将内容复制到输出目录更加容易。我有approot \\\\ bin作为工作目录。我的startUp任务元素的commandLine属性使用对.cmd文件的相对引用,如下所示:

enter

1
2
PowerShell -ExecutionPolicy Unrestricted -f ..\\StartUp\
oleStartup.ps1


您不需要在cmd中设置执行策略-只需调用脚本即可。另外,您应该使用相对路径,因为您不能依赖于存在C磁盘。

将批次更改为:

1
2
powershell -executionpolicy unrestricted -file .\
oleStartup.ps1

在Visual Studio中右键单击RoleStartup.ps1Startup.cmd,并确保将Copy to Output directory设置为copy always

如果这仍然不起作用,请在您的csdef中删除启动调用,部署服务,将rdp放入其中,然后尝试自己调用脚本以检索任何错误。

编辑:

尝试采用以下脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Import-Module WebAdministration

$site = $null

do # gets the first website until the result is not $null
{
    $site = Get-WebSite | select -first 1
    Sleep 1
}
until ($site)

# get the appcmd path
$appcmd = Join-Path ([System.Environment]::GetFolderPath('System')) 'inetsrv\\appcmd.exe'

# ensure the appcmd.exe is present
if (-not (Test-Path $appcmd))
{
    throw"appcmd.exe not found in '$appcmd'"
}

# The rest of your script ....