Removing variable in foreach loop - why?

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 7 months ago.

  • Author
    Posts
  • #5575

    by stromnessian at 2013-02-21 14:44:32

    Hi

    Apologies if I'm posting this in the wrong forum, but I'm reading through Learn PowerShell Toolmaking in a Month of Lunches and in the lab answers for chapter 7, lab B (see code), I'm wondering why the data variable is removed? Wouldn't it just be overwritten anyway?

    Many thanks

    Function Get-VolumeInfo {

    [cmdletbinding()]

    param( [string[]]$ComputerName )

    foreach ($computer in $computerName) {

    $data = Get-WmiObject -Class Win32_Volume -computername $Computer -Filter "DriveType=3"

    Foreach ($drive in $data) {

    #format size and freespace in GB to 2 decimal points
    $Size="{0:N2}" -f ($drive.capacity/1GB)
    $Freespace="{0:N2}" -f ($drive.Freespace/1GB)

    #Define a hashtable to be used for property names and values
    $hash=@{
    Computername=$drive.SystemName
    Drive=$drive.Name
    FreeSpace=$Freespace
    Size=$Size
    }

    #create a custom object from the hash table
    New-Object -TypeName PSObject -Property $hash
    } #foreach

    #clear $data for next computer
    Remove-Variable -Name data

    } #foreach computer

    }

    Get-VolumeInfo -ComputerName localhost

    by mjolinor at 2013-02-21 15:03:56

    If the get-wmiobject command fails then $data will not get set, and will be left with the value that was set by the last successful get-wmiobject.

    by MattG at 2013-02-21 15:10:44

    Also, it's worth noting that the script you posted will only work properly in PowerShell v3 because if Get-WmiObject returns an error (like if it couldn't connect to $Computer) then the `Foreach ($drive in $data)` line would try to dereference a null object and throw an exception. In my opinion, Get-WmiObject should include '-ErrorVariable' and respond accordingly if Get-WmiObject fails. PowerShell v3 handles iterating over a null value appropriately though without throwing any errors.

    by stromnessian at 2013-02-24 11:51:21

    Thanks for the replies 🙂

You must be logged in to reply to this topic.