A runtime logic error occurs when commands execute without an obvious error but produce an unintended result because a variable or property differs from the programmer’s assumption. section 23.1 section 23.4
Debug a logic error by comparing expected values and behavior with what the script actually produces:
- Run individual commands at the console when possible, rather than assuming their output or properties. section 23.4
- Inspect the variables and properties involved in the decision, especially immediately before conditional logic. section 23.4 section 23.4.1
- Set a breakpoint, step through the relevant lines, and observe where actual behavior diverges from expectations. section 23.4.1 section 23.6
A mismatched DriveType value
A disk-information function tests whether $disk.DriveType equals 'fixed'. Debugging reveals that the property contains 3 instead, so the condition takes the wrong branch and assigns 'N/A' rather than free-space data. section 23.4 section 23.4.1
Listing 23.1 A buggy script for you to consider
function Get-DiskInfo {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,
ValueFromPipeline=$True)]
[string[]]$ComputerName
)
BEGIN {
Set-StrictMode -Version 2.0
}
PROCESS {
ForEach ($comp in $ComputerName) {
$params = @{'ComputerName' = $comp
'ClassName' = 'Win32_LogicalDisk'}
$disks = Get-CimInstance @params
ForEach ($disk in $disks) {
$props = @{'ComputerName' = $comp
'Size' = $disk.size
'DriveType' = $disk.drivetype}
if ($disk.drivetype -eq 'fixed') {
$props.Add('FreeSpace',$disk.FreeSpace)
} else {
$props.Add('FreeSpace','N/A')
}
New-Object -TypeName PSObject -Property $props
} #foreach disk
} #foreach computer
} #PROCESS
END {}
}
Get-DiskInfo -ComputerName localhost
Inspect the buggy Get-DiskInfo function to follow a concrete logic-error investigation involving parameters, CIM results, properties, and conditional behavior. section 23.4


