Hyper-v 3.0 PowerShell–Automated Virtual Hard Disk Renaming | Quisitive
Hyper-v 3.0 PowerShell–Automated Virtual Hard Disk Renaming
April 27, 2012
Matthew Dowst
Use this script to help with keeping your Hyper-V servers free of unneeded ISO files.

I have created a script to help with keeping your Hyper-V servers free of unneeded ISO files. This script will create a list of all ISO files in a folder and its subfolders. Then, it will compare the list to the ISO files which are attached to a VM. After this, it will display all of ISO files that are not attached to a VM.

To run the script you need to save it as a PS1 and change the $folder variable to the folder you want to search.


$folder = <span class="str">&quot;D:\Virtual Machines&quot;</span>
 
<span class="rem">#Find ISO files</span>
$Disk = Get-ChildItem $folder –Recurse -Include *.iso `
    | ForEach-Object -Process {$_.FullName}
<span class="rem">#Find attached ISO files</span>
$computer = gc env:computername
$vm = Get-VM -ComputerName $computer
Foreach ($vm <span class="kwrd">in</span> $vm) 
    { 
        $ISO = Get-VMDvdDrive $vm
        $Path = $ISO.Path
        If ($path <span class="preproc">-ne</span> $NULL)
        {
        $Disk = $Disk.Replace($Path, <span class="str">&quot;&quot;</span>)
        }
    }
<span class="rem">#Display unattached ISO file</span>
$Disk

This script was written and tested using Windows Server 2012 RTM (Build 9200).