So I'm trying to figure out a way to script a compacting process for VHDX files using PowerShell. My problem in my script is trying to get the vhdx file (stored in a local drive) to mount, run the optimize command, then unmount the vhdx file. The script would then repeat this process for each vhdx file in the directory. Below is the script I have so far but PowerShell errors and states that the path for the mount command can't find the specified file. Any help would be greatly appreciated.
Script:
$UPDLocation = 'F:\TEST'
$vhds = gci $UPDLocation | Where-Object {($_.Name -like "*.vhdx") -and ($_.name -notlike "*template*")}
foreach($vhd in $vhds)
{
Mount-DiskImage -ImagePath "$_.FullName"
Optimize-VHD -path "$_.FullName" -Mode Full
Dismount-DiskImage -ImagePath "$_.FullName"
}