VMware Cloud Community
newwenha
Contributor
Contributor

Script to retrieve datastore vmdk last modified date help!

My script is as shown below. I don't want to get my VM list from a text file, but rather just use all the powered off VMs in the vCenter. I have tried replacing the Get-Content -path with Get-VM whose state is powered off but that doesn't work.

add-pssnapin VMware.VimAutomation.Core

$VCenter = 'qlab-copsmgr'

$DataCenter = 'Fly-away Kit'

$OutputFile = 'VMlastUsed.csv'

$VmList = Get-Content -path "C:\Users\nha\Desktop\VMList.txt"

$ColumnName = "Name,vHD-location,LastWriteTime" | Out-File .\$OutputFile -Encoding ascii

# ----------No modify is needed in the below codes -------------

Connect-VIServer $VCenter -WarningAction SilentlyContinue

ForEach ($VM in $VmList)

{

    $vHDs = (Get-HardDisk -vm $VM | select Filename)

    ForEach ($vHD in $vHDs)

    { 

        # Remove and/or replace unwanted strings

        $vHD = $vHD -replace '\[','' -replace '\] ','\' -replace '@{Filename=','/' -replace '}','' -replace '/','\' -replace '.vmdk', '*.vmdk'

        # List the newest vmdk file in the folder

        $vHDinfo = ls vmstores:\$VCenter@443\$DataCenter$vHD | Where {$_.LastWriteTime} | select -first 1 | select FolderPath, LastWriteTime

        # Remove and/or replace unwanted strings

        $vHDinfo = $vHDinfo -replace 'FolderPath=', '' -replace '@{', '' -replace '}', '' -replace ';', ',' -replace 'LastWriteTime=', ''      

    }

    $temp = $VM + ', ' + $vHDinfo

    $temp

    echo $temp >> $OutputFile

}

0 Kudos
1 Reply
LucD
Leadership
Leadership

Try replacing line 12 with

ForEach ($VM in (Get-VM | where{$_.PowerState -eq 'PoweredOff'}))


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos