This PowerShell script defines a function Compress-VHDX that is used to compress VHDX (Virtual Hard Disk) files of Hyper-V virtual machines (VMs). The function requires administrator privileges to run, as indicated by the #Requires -RunAsAdministrator directive.
The function accepts an optional parameter $VMName, which is an array of strings representing the names of the VMs from which space of the VHDX files should be recovered.
The function first checks if the Hyper-V module is installed. If not, it installs the module using the Enable-WindowsOptionalFeature cmdlet.
Next, it validates the provided VM names. If a VM name is provided and it does not correspond to an existing VM, the function issues a warning and aborts. If a VM is currently running, the function also issues a warning and aborts, as the VM needs to be shut down before its VHDX files can be compressed.
The function then gathers all VHDX files from the specified VMs (or all VMs if no VM name is provided) that do not have a parent/snapshot. If no such VHDX files are found, the function issues a warning and aborts.
For each gathered VHDX file, the function records its current size and then attempts to compress it. The compression process involves mounting the VHDX file, optimizing it using the Optimize-VHD cmdlet, and then dismounting it. If any of these steps fail, the function issues a warning and aborts.
Finally, the function generates a report on the new sizes of the VHDX files and the amount of space recovered from each file. If no dynamic disks were found to recover space from, the function issues a warning and aborts. Otherwise, it returns the report formatted as a table.