繁体   English   中英

使用Powershell在Azure VM上启动和停止Windows服务

[英]Start and stop windows service on a Azure VM using powershell

使用powershell,我需要执行以下步骤。
1.登录到Azure帐户。
2.从映像创建VM。
3.在该映像中,有Windows服务。因此,当我们创建VM时,该Windows服务已经在其上运行。停止该服务。
4.将一些二进制文件复制到VM的特定文件夹中。
5.再次启动服务。

在所有这些中,我能够实现1和2步。 我找不到其余步骤的任何相关过程。 以下是我用来做1和2的脚本。

Login-AzureRMAccount    

$UserName = "username@organization.com"
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)    
New-AzureRmVm `
    -ResourceGroupName "RGN" `
    -Name "VMName" `
    -ImageName "ImageName" `
    -Location "West US" `
    -Credential $psCred

因此,任何人都可以帮助我或指导我如何完成其​​余步骤。
在此先感谢您的时间。

编辑 :用于停止服务的命令是
停止服务-名称“ CPS Dev UniSimServices”-强制

但是,如果我登录到虚拟机并运行此命令,则此方法有效。 我想通过Powershell从远程计算机本身连接到新创建的VM(无需登录),然后停止该服务。 我怎样才能做到这一点?

您可以使用扩展名与VM进行交互,而无需连接它。 您可以将PowerShell命令与自定义脚本一起使用:

Set-AzureRmVMExtension -ResourceGroupName "myResourceGroupAutomate" `
    -ExtensionName "IIS" `
    -VMName "myVM" `
    -Location "EastUS" `
    -Publisher Microsoft.Compute `
    -ExtensionType CustomScriptExtension `
    -TypeHandlerVersion 1.8 `
    -SettingString '{"commandToExecute":"powershell Add-WindowsFeature Web-Server; powershell Add-Content -Path \"C:\\inetpub\\wwwroot\\Default.htm\" -Value $($env:computername)"}'

更新

如果您确实要为扩展使用自定义脚本,则可以使用以下命令:

Set-AzureRmVMCustomScriptExtension -ResourceGroupName myResourceGroup `
    -VMName myVM `
    -Location myLocation `
    -FileUri myURL `
    -Run 'myScript.ps1' `
    -Name DemoScriptExtension

有关更多详细信息,请参见Set-AzureRmVMCustomScriptExtension

要停止服务,请使用以下命令Stop-Service -Name "NameOfService" -Force ,查看Stop-Service的文档是否有任何问题。 然后通过robocopy,Copy-Item或其他任何东西以及Start-Service -Name "NameOfService"复制所需的文件。 如果您在将文件从本地或远程计算机复制到VM时遇到任何问题,只需将其发布即可。

如另一个答案中所述,您可以使用Set-AzureRmVMCustomScriptExtension ,以下示例在VM中执行一个脚本,该脚本上载到Blob存储帐户

Set-AzureRmVMCustomScriptExtension -ResourceGroupName $ResourceGroup -Location $LocationName -VMName $ServersName -Name $scriptName -StorageAccountName $NameStorageAccount -FileName $fileName -Run $fileName -ContainerName $NameCOntainerStorage -Argument "-param1 $param1" 

另一个选择是使用命令Invoke-AzureRmVMRunCommand ,例如

Invoke-AzureRmVMRunCommand -ResourceGroupName $ResourceGroup -Name $ServersName -CommandId 'RunPowerShellScript' -ScriptPath "pathToFileExecute" -Parameter @{"Param" = "$Param"}

注意:参数-ScriptPath可以是例如\\ VM \\ e $ \\ script.ps1之类的共享路径或本地路径。

最后一个选项是使用Invoke-Command ,例如:

Invoke-command -ComputerName $server -crdential $objectcredential -scriptblock {Stop-Service -Name "nameService" -force}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM