据我了解,根据您的情况,您正在尝试查找虚拟机的创建日期。有问题的虚拟机是“经典”虚拟机,这意味着它们部署到云服务容器中,而不是通过 Azure 资源管理器创建的。一些 VM 已经创建,一些将由您的脚本创建。一些云服务容器也已经存在了一段时间,有些可能更新。
我无法找到通过服务管理 API 检索 VM 创建日期的方法;但是,如果我们能够到达实际的虚拟机,那么我们还有更多工作要做。下面的脚本假定虚拟机创建日期与虚拟机上的操作系统安装日期相同(我认为这应该是一个很好的指标,我验证它不是源图像的日期,而是虚拟机创建)。为此,您需要在虚拟机上启用 PowerShell 远程端点,在创建虚拟机时默认启用该端点,并且您必须在本地管理员权限下运行该脚本,因为它会与证书存储区混淆。
$remoteCreds = Get-Credential
$maxVMAgeInDays = 30
#Classic VMs
Get-AzureVM | ForEach-Object {
#Need to ensure we have the self-signed VM certificate installed to authenticate and secure the connection.
$winRmCertThumbprint = $_.Vm.DefaultWinRmCertificateThumbprint
$certPath = "Cert:\LocalMachine\Root\$winRmCertThumbprint"
if (!(Test-Path -Path $certPath)){
#Cert for VM isn't found, importing.
$winRmCert = Get-AzureCertificate -ServiceName $_.ServiceName -Thumbprint $winRmCertThumbprint -ThumbprintAlgorithm sha1
$certTempFile = [IO.Path]::GetTempFileName()
$winRmCert.Data | Out-File $certTempFile
# Target The Cert That Needs To Be Imported
$CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certTempFile
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store "Root", "LocalMachine"
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($CertToImport)
$store.Close()
"Imported cert: $certPath"
#clean up temp file
Remove-Item $certTempFile
}
#Retrieve the powerShell Remote port for this machine.
$remoteUri = Get-AzureWinRMUri -ServiceName $_.ServiceName -Name $_.Name
$osInstallDate = Invoke-Command -ConnectionUri $remoteUri -Credential $remoteCreds -ScriptBlock { ([WMI]'').ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).InstallDate) }
$vmAgeInDays = (New-TimeSpan -Start $osInstallDate -End (Get-Date)).Days
if ($vmAgeInDays -gt $maxVMAgeInDays) {
"$($_.Name) VM in $($_.ServiceName) cloud service is older than $maxVMAgeInDays ... you can remove it."
#Add your code to remove the VM
} else {
"$($_.Name) VM in $($_.ServiceName) cloud service is only $($vmAgeInDays) old."
#Do soemthing else or just remove the else.
}
}
脚本假定您已经执行了 Add-AzureAccount 并选择了要使用的订阅。它将提示您输入 VM 的凭据,此特定脚本假定您拥有一个已设置为适用于每个 VM 的凭据。这可以是您在创建 VM 时提供的凭据,也可以是您之后添加到每个 VM 的正确权限的凭据。既然您说您通过脚本创建了 100 台虚拟机,我的猜测是它们都将拥有相同的管理员凭据。对于您现有的虚拟机,您可能必须手动向它们添加帐户(这可能会很痛苦,具体取决于您拥有的虚拟机数量)。
脚本循环遍历每个 VM 并检查是否在本地计算机上加载了 WinRM 证书。如果没有,它会将其拉下并安装。这是保护远程 PowerShell 会话所必需的。我从Michael Washam's script on TechNet 获取了代码。
在我们知道我们拥有保护连接的证书后,他们执行远程 PowerShell 命令来检索操作系统安装日期(我在 ScioSoft blog 上找到的提示)。最后,它会根据该日期检查 VM 的年龄,然后可以执行您希望它执行的任何操作。在您的情况下,您可以将其删除。如果你真的想清理这些东西,你需要确保在删除 VM 时还清理底层磁盘等。
最后,为了改进我为您删除的任何 VM 建议的脚本,您可以然后通过指纹删除证书来清理您的证书存储。
这适用于经典虚拟机,听起来就像您拥有的那样。有人已经为您提供了一种通过标记处理基于 ARM 的虚拟机的方法,这样就无需实际处理远程命令。