0

I'm creating a PowerShell script (will post the script at the end) with the goal of automating the optimization process of multiple vhdx files in a directory. To sum up the script I currently have it prompting the user for the directory location of the vhdx files and then it stores the files that are found in a single variable. From there I'm not sure how I would take each file that was found from the directory and run two commands against each file before the script moves onto the next file in the directory. The first command would be to see if the file is locked (if it is then skip if not move on to the second command). The second command would be to optimize the vhdx file. Once all files are complete it would show that the script completed and X amount of files were skipped.

My script so far:

   <# Welcome message to the script. #>
Write-Host "This script will go through the process of shrinking RDS VHDX files that have increased in size. Please follow the prompts to complete the process." -ForegroundColor Green

<# prompt for user to enter the file directory that the VHDX files live in: #>

[string]$pathname = Read-Host -Prompt 'Please enter full path directory to vhdx files.'

<# Output to user to show input was entered. #>

echo "Scanning vhdx files from $pathname."


<# Action to gather all vhdx files from the provided path: #> 
$filesFound = Get-ChildItem -Path $pathname* -Exclude UVHD-template*

Read-Host "Please review the vhdx files above. If correct press any key to continue." -ForegroundColor Green

ForEach-Object ($filesFound){

}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    `foreach( $file in $filesFound ) { Write-Host $file.FullName }` or `$filesFound | ForEach-Object { Write-Host $_.FullName }`. – zett42 Nov 16 '21 at 15:51
  • [Resize-VHD -ToMinimumSize](https://learn.microsoft.com/en-us/powershell/module/hyper-v/resize-vhd?view=windowsserver2019-ps#:~:text=%5B%5D-,Description,the%20VHDX%20object's%20MinimumSize%20property) wouldn't already do it ? `Get-ChildItem -Path $pathname* -Exclude UVHD-template* | Resize-VHD -ToMinimumSize` – Hazrelle Nov 16 '21 at 17:12
  • Sorry I will rephrase my original posting.. I'm not wanting to resize but optimize the vhdx files. I tried to | and use the optimize command but it errors out and says its not a recognized command. I think the problem is that the optimize command requires the full path to the vhdx file. My issue is trying to load all the vhdx files into a variable then pull the full path from the variable into a second variable to be used in the optimize command. Sortta like queuing all the vhdx files then run the optimize command one at a time for each vhdx file. If one is lock that it should be skipped. – Brad Imsicke Nov 16 '21 at 18:56

0 Answers0