gpt4 book ai didi

powershell - Azure Powershell如何通过Runbook获取VM的运行服务?

转载 作者:行者123 更新时间:2023-12-03 03:06:55 24 4
gpt4 key购买 nike

我正在尝试编写一个 Azure Powershell Runbook 来启动 VM,然后检查 VM 上的 Windows 服务是否正在运行并启动它。

我可以启动虚拟机,但枚举服务不起作用。我是 Azure Runbooks 的新手,所以我可能做错了什么。我将下面的代码限制为仅 Get-Service 位,而不是 VM 启动。

# Returns strings with status messages
[OutputType([String])]

param (
[Parameter(Mandatory=$false)]
[String] $AzureConnectionAssetName = "AzureRunAsConnection",

[Parameter(Mandatory=$false)]
[String] $ResourceGroupName = ""
)

try {
# Connect to Azure using service principal auth
$ServicePrincipalConnection = Get-AutomationConnection -Name $AzureConnectionAssetName

Write-Output "Logging in to Azure..."

$Null = Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $ServicePrincipalConnection.TenantId `
-ApplicationId $ServicePrincipalConnection.ApplicationId `
-CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
}
catch {
if(!$ServicePrincipalConnection) {
throw "Connection $AzureConnectionAssetName not found."
}
else {
throw $_.Exception
}
}

# If there is a specific resource group, then get all VMs in the resource group,
# otherwise get all VMs in the subscription.
if ($ResourceGroupName) {
$VMs = Get-AzureRmVM -ResourceGroupName $ResourceGroupName
}
else {
$VMs = Get-AzureRmVM
}

# Try and enumerate the VM's services
foreach ($VM in $VMs) {
Write-Output "Listing all services..."
Write-Output ("VM: {0}" -f $VM.Name)
$VM | Get-Service | Format-Table -AutoSize

Write-Output "Listing alternative method..."
Get-Service -ComputerName $VM.Name | Format-Table -AutoSize
Write-Output "Finished listing..."
}

输出是这样的:

Logging in to Azure...

Listing all services...

VM: demo-0

Listing alternative method...

Finished listing...

最佳答案

嗯,首先,启动VM是异步的,所以你需要等待VM实际启动,而Get-Service无论如何也不起作用,因为无法从一个虚拟机,您需要针对该虚拟机进行身份验证,因此可以是用户 PSsessions 或调用命令,类似的东西。只需了解如何使用 powershell 远程访问服务器或如何向远程 PC 发出 powershell 命令即可。这个案例没什么不同。它与 Azure 自动化的工作原理无关。

关于powershell - Azure Powershell如何通过Runbook获取VM的运行服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43724096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com