The only place I see that you use division is after the Get-SupportedPartitionSize cmdlet. The variable $size, however, shouldn't be an array.
I've added error handling to your script, and replaced the multiple "Substring" operation with a regex (it makes what you're trying to do less difficult to figure out!). I've also redirected the error stream from the Invoke-Command so it will be returned. The results of the Invoke-Command are placed into the variable $result. You should verify at the completion of the Invoke-Command that no error objects are present in that variable.
$hdLetter = "D:"
$server = "XXXX"
$user = Read-Host "Enter domain\user name"
$pass = Read-Host -AsSecureString -Prompt "Enter password"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $pass
$guestLogicalDiskNumberPartition = "Disk #1, Partition #0"
$result = Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {
if ($diskNumber = $Using:guestLogicalDiskNumberPartition -match "^Disk #([0-9]+?),"){
$disknumber = $matches[1]
Try{
Update-Disk -Number $diskNumber -ErrorAction Stop
}
Catch{
Throw $_ # just return the error object
}
$timeOut = 0
# aspetta che la configurazione sia ok
do {
Try{
$size = Get-PartitionSupportedSize -DriveLetter $Using:hdLetter -ErrorAction STOP
if ($size -is [array]){
Throw "Get-PartitionSupportedSize returned multiple results!"
}
if (($size.SizeMax) -is [array]){
Throw ("Logical Disk $($Using:hdletter) has multiple partitions!")
}
$sizeGB = [math]::Round($size.SizeMax / 1024 / 1024 / 1024)
}
Catch{
Throw $_ # just return the error object
}
Write-Host "." -NoNewline
$timeOut += 300
Start-Sleep -Milliseconds 300
} until ($sizeGB -eq $Using:capacityGB -or $timeOut -gt 20000) # NOTE: $capacityGB isn't defined!
Try{
Resize-Partition -DriveLetter $Using:hdLetter -Size $size.SizeMax -ErrorAction Stop
}
Catch{
Throw $_ # just return the error object
}
Write-Host "!"
Write-Host "Disco espanso a: $sizeGB GB" -ForegroundColor Green
"Disco espanso a: $sizeGB GB"
}
else{
Write-Host "Failed to find the disk number in $($Using:guestLogicalDiskNumberPartition)"
"Failed to find the disk number in $($Using:guestLogicalDiskNumberPartition)"
}
} 2>&1 # redirect the error stream so Invoke-Command returns not just stuff that works!
$result