How to Defrag Drives using Powershell in Windows Server 2012
Defrag Drives with Optimize-Volume
The new cmdlet we will use is called Optimize-Volume. It is part of the Storage module which utilizes the new CIM infrastructure. You can use this cmdlet to analyze and defrag all types of volumes.
We’ll focus on logical drives like C:.
How to Run an Analysis
To run an analysis all you need to do is run a command like this:
1
|
PS C:\> Optimize-Volume G –Analyze
|
But for some reason unknown to me, the cmdlet doesn’t write any sort of result to the pipeline! Instead you have to use the –Verbose parameter.
1
|
PS C:\> Optimize-Volume G –Analyze -verbose
|
You should get something like Figure 2:
So you can get the information you need, but it takes an extra step. If you want to save the results, you’ll need to redirect the verbose output.
1
|
PS C:\> Optimize-Volume G –Analyze –verbose 4>c:\work\GDrive.txt
|
On the positive side, you can specify a remote computer using –CIMSession. The remote computer must be running Windows Server 2012 or Windows 8.
1
|
PS C:\> Optimize-Volume C –Analyze –Cimsession CHI-DC03 –verbose 4>c:\work\dc03-c.txt
|
You can either specify a computer name, as I’ve done here, or an existing CIM session object. This makes it (sort of) easy to analyze the same drive across multiple computers.
How to Defrag a Drive
When the time comes to perform the defrag, we can use the same cmdlet, but without the –Analyze parameter.
1
|
PS C:\> Optimize-Volume d -Verbose -CimSession novo8
|
Again, I used –Verbose so I can see what happened in Figure 3.
Optimize-Volume will automatically perform additional operations such as trimming, depending on the drive type. So for an SSD drive the cmdlet should automatically retrim, but you can specify –Retrim if you want.