1

I want to run a PowerShell command if drive has X amount free storage capacity.

using following command we can get the free space information.

gwmi Win32_LogicalDisk -Filter "DeviceID='D:'" | Select-Object {$_.FreeSpace/1gb}

i tried like this

$space = gwmi Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object {$_.FreeSpace/1gb}



If ($space -gt 10) {


Copy-Item -Path "C:\1\*" -Destination "C:\2\" -recurse -Force -Verbose
   
}

Sorry I have very limited knowledge about PowerShell. i getting error objects are not the same type. I think it's because $space giving text name information before the digit.

Steven
  • 6,817
  • 1
  • 14
  • 14
Shahpari
  • 115
  • 2
  • 8
  • The linked duplicate contains more details, but in short: to simply calculate a _value_ based on a pipeline input object, use `ForEach-Object`: `Select-Object { $_.FreeSpace/1gb }` -> `ForEach-Object { $_.FreeSpace/1gb }`. – mklement0 Aug 15 '21 at 02:09

2 Answers2

2

Get-WMIObject is deprecated you should try to start migrating to the CIM cmdlets. In this case Get-CimInstance

$FreeSpace = (Get-CimInstance Win32_Volume -Filter "DriveLetter = 'C:'").FreeSpace / 1GB
If( $FreeSpace -gt 10) {
    Copy-Item -Path "C:\1\*" -Destination "C:\2\" -recurse -Force -Verbose
}

I prefer the Win32_Volume class for this task, though the above should work fine with Win32_LogicalVolume.

For more on the change from WMI to Cim, take a look at these articles:

Introduction to CIM Cmdlets

Scripting Guys CIM Vs WMI

mklement0
  • 382,024
  • 64
  • 607
  • 775
Steven
  • 6,817
  • 1
  • 14
  • 14
1

You're comparing against the object and not the free space value itself

Change If ($space -gt 10) to If ($space.'$_.FreeSpace/1gb' -gt 10) to compare against the number inside the object held in $space.