Azure VM OS构建-Powershell

时间:2018-08-06 18:45:40

标签: azure powershell azure-powershell

我试图创建一个powershell命令来遍历我所有的Azure订阅并获取VM的操作系统内部版本号

param(
    # Specify the location of the audit file
    $csvFilePath = "C:\agentAudit.csv"
)
cls

$ErrorActionPreference = 'Stop'
Write-Host "Validating Azure Accounts..."
try{
    $subscriptionList = Get-AzureRmSubscription | Sort SubscriptionName
}
catch {
    Write-Host "Reauthenticating..."
    Login-AzureRmAccount | Out-Null
    $subscriptionList = Get-AzureRmSubscription | Sort SubscriptionName
}
if (Test-Path $csvFilePath) {
    Remove-Item -Path $csvFilePath
}
foreach($subscription in $subscriptionList) {
    Select-AzureRmSubscription -SubscriptionId $subscription.SubscriptionId | Out-Null
    Write-Output "`n Working on subscription: $($subscription.SubscriptionName) `n"
    $vms = Get-AzureRmVM -WarningAction Ignore
    foreach ($vm in $vms) {
    $VMs = Get-AzureRmVM 
    $vmlist = @() 
    $VMs | ForEach-Object {  
        $VMObj = New-Object -TypeName PSObject 
        $VMObj | Add-Member -MemberType Noteproperty -Name "VM Name" -Value $_.Name 
        $VMObj | Add-Member -MemberType Noteproperty -Name "OS type" -Value $_.StorageProfile.ImageReference.Sku
        $VMObj | Add-Member -MemberType Noteproperty -Name "OS Offer" -Value $_.StorageProfile.ImageReference.Offer
        $VMObj | Add-Member -MemberType Noteproperty -Name "OS Publisher" -Value $_.StorageProfile.ImageReference.Publisher
        $VMObj | Add-Member -MemberType Noteproperty -Name "OS Version" -Value $_.StorageProfile.ImageReference.Version
    $vmlist += $VMObj 
} 
$vmlist  
}
}

我对Powershell还是陌生的,仍然在学习理解和编写PS

2 个答案:

答案 0 :(得分:0)

很久以前,我创建了一个用于生成Azure清单的脚本。也许这可以帮助您。您只需要稍微调整一下

Add-AzureRmAccount
$SubscriptionNames = "Prototypes","Development"
foreach($SubscriptionName in $SubscriptionNames)
{
    try
    {
        Select-AzureRmSubscription -SubscriptionName $SubscriptionName
        $VMinventory = Get-AzurermVM -ErrorAction Stop
        $OutputPath = "C:\VMInventoryRM-" + $SubscriptionName + ".csv"
        $report=@()
        foreach ($vm in $VMinventory)
            {   

                     $VMinfo = " " | select Powerstate, Location, VMSize
                     # Display
                     write-host($vm.Name)
                     $vmStatus = $null
                     $Location = $null
                     $VMSize = $null


                     $vmStatus = (get-azurermvm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Status).Statuses[1].Code
                     $Location = $vm.Location
                     $VMSize = $vm.HardwareProfile.VmSize

                     $VMinfo.Powerstate = $vmStatus
                     $VMinfo.Location = $Location
                     $VMinfo.VMSize = $VMSize

                     $Report += $VMinfo 
                     $i++                 

               }

        $Report | export-csv $OutputPath -NoTypeInformation
    }
    catch
    {}
}

答案 1 :(得分:0)

我在下面的Technet文章中找到了答案

function Get-WindowsVersion {
    <#
.SYNOPSIS
    List Windows Version from computer. Compatible with PSVersion 3 or higher.
.DESCRIPTION
    List Windows Version from computer. Compatible with PSVersion 3 or higher.
.PARAMETER ComputerName
    Name of server to list Windows Version from remote computer.
.PARAMETER SearchBase
    AD-SearchBase of server to list Windows Version from remote computer.
.PARAMETER History
    List History Windows Version from computer.
.PARAMETER Force
    Disable the built-in Format-Table and Sort-Object.
.NOTES
    Name: Get-WindowsVersion.psm1
    Author: Johannes Sebald
    Version: 1.2.5
    DateCreated: 2016-09-13
    DateEdit: 2018-07-11
.LINK
    https://www.dertechblog.de
.EXAMPLE
    Get-WindowsVersion
    List Windows Version on local computer with built-in Format-Table and Sort-Object.
.EXAMPLE
    Get-WindowsVersion -ComputerName pc1
    List Windows Version on remote computer with built-in Format-Table and Sort-Object.
.EXAMPLE
    Get-WindowsVersion -ComputerName pc1,pc2
    List Windows Version on multiple remote computer with built-in Format-Table and Sort-Object.
.EXAMPLE
    Get-WindowsVersion -SearchBase "OU=Computers,DC=comodo,DC=com" with built-in Format-Table and Sort-Object.
    List Windows Version on Active Directory SearchBase computer.
.EXAMPLE
    Get-WindowsVersion -ComputerName pc1,pc2 -Force
    List Windows Version on multiple remote computer and disable the built-in Format-Table and Sort-Object.
.EXAMPLE
    Get-WindowsVersion -History with built-in Format-Table and Sort-Object.
    List History Windows Version on local computer.
.EXAMPLE
    Get-WindowsVersion -ComputerName pc1,pc2 -History
    List History Windows Version on multiple remote computer with built-in Format-Table and Sort-Object.
.EXAMPLE
    Get-WindowsVersion -ComputerName pc1,pc2 -History -Force
    List History Windows Version on multiple remote computer and disable built-in Format-Table and Sort-Object.
#>
    [cmdletbinding()]
    param (
        [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$ComputerName = "localhost",
        [string]$SearchBase,
        [switch]$History,
        [switch]$Force
    )
    if ($($PsVersionTable.PSVersion.Major) -gt "2") {
        # SearchBase
        if ($SearchBase) {
            if (Get-Command Get-AD* -ErrorAction SilentlyContinue) {
                if (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$SearchBase'" -ErrorAction SilentlyContinue) {
                    $Table = Get-ADComputer -SearchBase $SearchBase -Filter *
                    $ComputerName = $Table.Name
                }
                else {Write-Warning "No SearchBase found"}
            }
            else {Write-Warning "No AD Cmdlet found"}
        }
        # Loop 1
        $Tmp = New-TemporaryFile
        foreach ($Computer in $ComputerName) {
            if (Test-Connection -ComputerName $Computer -Count 1 -ErrorAction SilentlyContinue) {
                try {
                    $WmiObj = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer
                }
                catch {
                    Write-Warning "$Computer no wmi access"
                }
                if ($WmiObj) {
                    # Variables
                    $WmiClass = [WmiClass]"\\$Computer\root\default:stdRegProv"
                    $HKLM = 2147483650
                    $Reg1 = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
                    $Reg2 = "SYSTEM\Setup"
                    if ($History) {$KeyArr = ($WmiClass.EnumKey($HKLM, $Reg2)).snames -like "Source*"} else {$KeyArr = $Reg1}
                    # Loop 2
                    foreach ($Key in $KeyArr) {
                        if ($History) {$Reg = "$Reg2\$Key"} else {$Reg = $Key}
                        $Major = $WmiClass.GetDWordValue($HKLM, $Reg, "CurrentMajorVersionNumber").UValue
                        $Minor = $WmiClass.GetDWordValue($HKLM, $Reg, "CurrentMinorVersionNumber").UValue
                        $Build = $WmiClass.GetStringValue($HKLM, $Reg, "CurrentBuildNumber").sValue
                        $UBR = $WmiClass.GetDWordValue($HKLM, $Reg, "UBR").UValue
                        $ReleaseId = $WmiClass.GetStringValue($HKLM, $Reg, "ReleaseId").sValue
                        $ProductName = $WmiClass.GetStringValue($HKLM, $Reg, "ProductName").sValue
                        $ProductId = $WmiClass.GetStringValue($HKLM, $Reg, "ProductId").sValue
                        $InstallTime1 = $WmiClass.GetQWordValue($HKLM, $Reg, "InstallTime").UValue
                        $InstallTime2 = ([datetime]::FromFileTime($InstallTime1))
                        # Variables Windows 6.x
                        if ($Major.Length -le 0) {$Major = $WmiClass.GetStringValue($HKLM, $Reg, "CurrentVersion").sValue}
                        if ($ReleaseId.Length -le 0) {$ReleaseId = $WmiClass.GetStringValue($HKLM, $Reg, "CSDVersion").sValue}
                        if ($InstallTime1.Length -le 0) {$InstallTime2 = ([WMI]"").ConvertToDateTime($WmiObj.InstallDate)}
                        # Add Points
                        if (-not($Major.Length -le 0)) {$Major = "$Major."}
                        if (-not($Minor.Length -le 0)) {$Minor = "$Minor."}
                        if (-not($UBR.Length -le 0)) {$UBR = ".$UBR"}
                        # Output
                        $Output = New-Object -TypeName PSobject
                        $Output | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.toUpper()
                        $Output | Add-Member -MemberType NoteProperty -Name ProductName -Value $ProductName
                        $Output | Add-Member -MemberType NoteProperty -Name WindowsVersion -Value $ReleaseId
                        $Output | Add-Member -MemberType NoteProperty -Name WindowsBuild -Value "$Major$Minor$Build$UBR"
                        $Output | Add-Member -MemberType NoteProperty -Name ProductId -Value $ProductId
                        $Output | Add-Member -MemberType NoteProperty -Name InstallTime -Value $InstallTime2
                        $Output | Export-Csv -Path $Tmp -Append
                    }
                }
            }
            else {Write-Warning "$Computer not reachable"}
        }
        # Output
        if ($Force) {Import-Csv -Path $Tmp} else {Import-Csv -Path $Tmp | Sort-Object -Property ComputerName, WindowsVersion | Format-Table -AutoSize}
    }
    else {Write-Warning "PSVersion to low"}
}

https://gallery.technet.microsoft.com/scriptcenter/Get-WindowsVersion-can-0726c5d4#

谢谢约翰内斯·塞巴尔德()