Difference between revisions of "Powershell to emulate Unix df -k"

From MyWiki
Jump to: navigation, search
(Created page with "Reference http://binarynature.blogspot.co.uk/2010/04/powershell-version-of-df-command.html")
 
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
Reference http://binarynature.blogspot.co.uk/2010/04/powershell-version-of-df-command.html
+
Reference http://binarynature.blogspot.co.uk/2010/04/powershell-version-of-df-command.html<br>
 +
 
 +
<source lang="powershell">
 +
 
 +
function Get-DiskFree
 +
{
 +
    [CmdletBinding()]
 +
    param
 +
    (
 +
        [Parameter(Position=0,
 +
                  ValueFromPipeline=$true,
 +
                  ValueFromPipelineByPropertyName=$true)]
 +
        [Alias('hostname')]
 +
        [Alias('cn')]
 +
        [string[]]$ComputerName = $env:COMPUTERNAME,
 +
       
 +
        [Parameter(Position=1,
 +
                  Mandatory=$false)]
 +
        [Alias('runas')]
 +
        [System.Management.Automation.Credential()]$Credential =
 +
        [System.Management.Automation.PSCredential]::Empty,
 +
       
 +
        [Parameter(Position=2)]
 +
        [switch]$Format
 +
    )
 +
   
 +
    BEGIN
 +
    {
 +
        function Format-HumanReadable
 +
        {
 +
            param ($size)
 +
            switch ($size)
 +
            {
 +
                {$_ -ge 1PB}{"{0:#.#'P'}" -f ($size / 1PB); break}
 +
                {$_ -ge 1TB}{"{0:#.#'T'}" -f ($size / 1TB); break}
 +
                {$_ -ge 1GB}{"{0:#.#'G'}" -f ($size / 1GB); break}
 +
                {$_ -ge 1MB}{"{0:#.#'M'}" -f ($size / 1MB); break}
 +
                {$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break}
 +
                default {"{0}" -f ($size) + "B"}
 +
            }
 +
        }
 +
       
 +
        $wmiq = 'SELECT * FROM Win32_LogicalDisk WHERE Size != Null AND DriveType >= 2'
 +
    }
 +
   
 +
    PROCESS
 +
    {
 +
        foreach ($computer in $ComputerName)
 +
        {
 +
            try
 +
            {
 +
                if ($computer -eq $env:COMPUTERNAME)
 +
                {
 +
                    $disks = Get-WmiObject -Query $wmiq `
 +
                            -ComputerName $computer -ErrorAction Stop
 +
                }
 +
                else
 +
                {
 +
                    $disks = Get-WmiObject -Query $wmiq `
 +
                            -ComputerName $computer -Credential $Credential `
 +
                            -ErrorAction Stop
 +
                }
 +
               
 +
                if ($Format)
 +
                {
 +
                    # Create array for $disk objects and then populate
 +
                    $diskarray = @()
 +
                    $disks | ForEach-Object { $diskarray += $_ }
 +
                   
 +
                    $diskarray | Select-Object @{n='Name';e={$_.SystemName}},
 +
                        @{n='Vol';e={$_.DeviceID}},
 +
                        @{n='Size';e={Format-HumanReadable $_.Size}},
 +
                        @{n='Used';e={Format-HumanReadable `
 +
                        (($_.Size)-($_.FreeSpace))}},
 +
                        @{n='Avail';e={Format-HumanReadable $_.FreeSpace}},
 +
                        @{n='Use%';e={[int](((($_.Size)-($_.FreeSpace))`
 +
                        /($_.Size) * 100))}},
 +
                        @{n='FS';e={$_.FileSystem}},
 +
                        @{n='Type';e={$_.Description}}
 +
                }
 +
                else
 +
                {
 +
                    foreach ($disk in $disks)
 +
                    {
 +
                        $diskprops = @{'Volume'=$disk.DeviceID;
 +
                                  'Size'=$disk.Size;
 +
                                  'Used'=($disk.Size - $disk.FreeSpace);
 +
                                  'Available'=$disk.FreeSpace;
 +
                                  'FileSystem'=$disk.FileSystem;
 +
                                  'Type'=$disk.Description
 +
                                  'Computer'=$disk.SystemName;}
 +
                   
 +
                        # Create custom PS object and apply type
 +
                        $diskobj = New-Object -TypeName PSObject `
 +
                                  -Property $diskprops
 +
                        $diskobj.PSObject.TypeNames.Insert(0,'BinaryNature.DiskFree')
 +
                   
 +
                        Write-Output $diskobj
 +
                    }
 +
                }
 +
            }
 +
            catch
 +
            {
 +
                # Check for common DCOM errors and display "friendly" output
 +
                switch ($_)
 +
                {
 +
                    { $_.Exception.ErrorCode -eq 0x800706ba } `
 +
                        { $err = 'Unavailable (Host Offline or Firewall)';
 +
                            break; }
 +
                    { $_.CategoryInfo.Reason -eq 'UnauthorizedAccessException' } `
 +
                        { $err = 'Access denied (Check User Permissions)';
 +
                            break; }
 +
                    default { $err = $_.Exception.Message }
 +
                }
 +
                Write-Warning "$computer - $err"
 +
            }
 +
        }
 +
    }
 +
   
 +
    END {}
 +
}
 +
</source>
 +
Load the function using dot forward slash then the usage is as below :<br>
 +
PS> $cred = Get-Credential -Credential 'example\administrator'<br>
 +
PS> 'db01','sp01' | Get-DiskFree -Credential $cred -Format | ft -GroupBy Name -auto  <br>

Latest revision as of 08:30, 14 June 2016

Reference http://binarynature.blogspot.co.uk/2010/04/powershell-version-of-df-command.html

function Get-DiskFree
{
    [CmdletBinding()]
    param 
    (
        [Parameter(Position=0,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('hostname')]
        [Alias('cn')]
        [string[]]$ComputerName = $env:COMPUTERNAME,
 
        [Parameter(Position=1,
                   Mandatory=$false)]
        [Alias('runas')]
        [System.Management.Automation.Credential()]$Credential =
        [System.Management.Automation.PSCredential]::Empty,
 
        [Parameter(Position=2)]
        [switch]$Format
    )
 
    BEGIN
    {
        function Format-HumanReadable 
        {
            param ($size)
            switch ($size) 
            {
                {$_ -ge 1PB}{"{0:#.#'P'}" -f ($size / 1PB); break}
                {$_ -ge 1TB}{"{0:#.#'T'}" -f ($size / 1TB); break}
                {$_ -ge 1GB}{"{0:#.#'G'}" -f ($size / 1GB); break}
                {$_ -ge 1MB}{"{0:#.#'M'}" -f ($size / 1MB); break}
                {$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break}
                default {"{0}" -f ($size) + "B"}
            }
        }
 
        $wmiq = 'SELECT * FROM Win32_LogicalDisk WHERE Size != Null AND DriveType >= 2'
    }
 
    PROCESS
    {
        foreach ($computer in $ComputerName)
        {
            try
            {
                if ($computer -eq $env:COMPUTERNAME)
                {
                    $disks = Get-WmiObject -Query $wmiq `
                             -ComputerName $computer -ErrorAction Stop
                }
                else
                {
                    $disks = Get-WmiObject -Query $wmiq `
                             -ComputerName $computer -Credential $Credential `
                             -ErrorAction Stop
                }
 
                if ($Format)
                {
                    # Create array for $disk objects and then populate
                    $diskarray = @()
                    $disks | ForEach-Object { $diskarray += $_ }
 
                    $diskarray | Select-Object @{n='Name';e={$_.SystemName}}, 
                        @{n='Vol';e={$_.DeviceID}},
                        @{n='Size';e={Format-HumanReadable $_.Size}},
                        @{n='Used';e={Format-HumanReadable `
                        (($_.Size)-($_.FreeSpace))}},
                        @{n='Avail';e={Format-HumanReadable $_.FreeSpace}},
                        @{n='Use%';e={[int](((($_.Size)-($_.FreeSpace))`
                        /($_.Size) * 100))}},
                        @{n='FS';e={$_.FileSystem}},
                        @{n='Type';e={$_.Description}}
                }
                else 
                {
                    foreach ($disk in $disks)
                    {
                        $diskprops = @{'Volume'=$disk.DeviceID;
                                   'Size'=$disk.Size;
                                   'Used'=($disk.Size - $disk.FreeSpace);
                                   'Available'=$disk.FreeSpace;
                                   'FileSystem'=$disk.FileSystem;
                                   'Type'=$disk.Description
                                   'Computer'=$disk.SystemName;}
 
                        # Create custom PS object and apply type
                        $diskobj = New-Object -TypeName PSObject `
                                   -Property $diskprops
                        $diskobj.PSObject.TypeNames.Insert(0,'BinaryNature.DiskFree')
 
                        Write-Output $diskobj
                    }
                }
            }
            catch 
            {
                # Check for common DCOM errors and display "friendly" output
                switch ($_)
                {
                    { $_.Exception.ErrorCode -eq 0x800706ba } `
                        { $err = 'Unavailable (Host Offline or Firewall)'; 
                            break; }
                    { $_.CategoryInfo.Reason -eq 'UnauthorizedAccessException' } `
                        { $err = 'Access denied (Check User Permissions)'; 
                            break; }
                    default { $err = $_.Exception.Message }
                }
                Write-Warning "$computer - $err"
            } 
        }
    }
 
    END {}
}

Load the function using dot forward slash then the usage is as below :
PS> $cred = Get-Credential -Credential 'example\administrator'
PS> 'db01','sp01' | Get-DiskFree -Credential $cred -Format | ft -GroupBy Name -auto