Error : Cannot convert value “C” to type “System.Int32”. Error: “Input string was not in a correct
format.”
At G:\SqlScript\powershell\Untitled5.ps1:6 char:9
I recommend formatting your code by enclosing it using pre /pre. I wasn’t able to replicate your error, however, you are referencing your variables incorrectly. This is the adjusted version:
As BenT said, it looks like you aren’t referencing your variables correctly. Specifically, in the division on line 6, $CDrive probably should be $CDriveSize.
Here’s an adjusted version that doesn’t change your process but makes it a little cleaner and more flexible:
## input variables
$drive = 'C:'
$computer = "localhost"
## get drive information
$AllDrives = Get-WmiObject win32_logicaldisk -ComputerName "$computer"
$SelectedDrive = $AllDrives | Where-Object DeviceId -In("$drive")
$SelectedDriveData = $SelectedDrive | Select-object DeviceId,@{n="Size";e={[math]::Round($_.Size/1GB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
## calculate free space percentage
$SelectedDriveSize = $SelectedDriveData.Size
$SelectedDriveFreeSpace = $SelectedDriveData.FreeSpace
$SelectedDriveFreePercent = [Math]::Round(($SelectedDriveFreeSpace / $SelectedDriveSize) * 100)
## show the result
$SelectedDriveFreePercent
You can do all of these calculations within calculated expressions without breaking things into separate variables. Additionally, you can use string format to make it a percentage: