[英]How do I restart a windows service on an Azure VM remotely from my office desktop using powershell?
[英]How to remotely start service on Azure VM with powershell 5.1
如何在 Azure 虚拟机上远程启动服务? 没有 Powershell 被“以管理员身份运行”似乎是不可能的。 有没有办法以管理员身份启动?
(我会传入 Get-Credential 参数,但不幸的是,5.1 版本的 Set-Service 命令不接受它作为参数,就像它在 Powershell 7.x 版本中那样,我现在仅限于 5.1。)
我的凭据在 VM 上确实具有管理员级别的权限,但我似乎无法找到通过命令传递该凭据的方法。
我正在像这样触发调用,其中 $action 是“停止”或“开始”:
$runCommand = Invoke-AzVMRunCommand `
-ResourceGroupName $rg `
-VMName $vm `
-CommandId 'RunPowerShellScript' `
-ScriptPath $scriptPath `
-Parameter @{action = $action}
链接脚本将执行如下操作:
$serviceNames = @("service1, service2")
foreach($serviceName in $serviceNames){
$service = Get-Service -Name $serviceName
if($service){
if($action -ieq "start"){
Set-Service -InputObject $service -Status "Running"
}
}
else{
Write-Output "Service $serviceName not found!"
}
}
确保您必须使用已使用 VM 配置的本地管理员密码进行连接。
如果您无法连接 VM,则需要根据MS-DOC重置本地管理员密码/远程桌面服务配置。 我们可以重置Azure 门户/VM 访问扩展和 PowerShell 。
如果您想从本地连接 Azure VM,则必须使用相应的 Azure 订阅登录。 使用Set-AzVMAccessExtension重置本地管理员帐户密码。 VM 有一个访问代理。 使用您之前使用的同一 VM Access Agent。
将用户添加到您的 VM
$Uname = "<UserName>"
$password = "<Password>"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-LocalUser $Uname -Password $securePassword -FullName $Uname -Description "test admin account"
Add-LocalGroupMember -Group "Administrators" -Member $Uname
重置本地管理员密码
$vm = Get-AzVM -ResourceGroupName "<ResourceGroup Name>" -Name "<Resource name>"
$Uname = "<UserName>"
$password = "<Password>"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials= New-Object System.Management.Automation.PSCredential ($Uname, $securePassword)
Set-AzVMAccessExtension -Credential $credentials -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -Location $vm.Location -Name VMAccessAgent -TypeHandlerVersion "2.0"
Connect-AzAccount
$vm = Get-AzVM -Name "<your vm name>" -ResourceGroupName "<your vm resource group>"
$runCommand = Invoke-AzVMRunCommand `
-ResourceGroupName $rg `
-VMName $vm `
-CommandId 'RunPowerShellScript' `
-ScriptPath $scriptPath `
-Parameter @{action = $action}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.