Page 1 of 1

Proxy Function: Get-ChildItem (File Size In Human Readable Format)

Posted: 2021-Jul-25, 10:11 am
by MigrationUser
21 Nov 2011 07:45
jumper


hi

Code: Select all

Function Get-ChildItem {
<#

.ForwardHelpTargetName Get-ChildItem
.ForwardHelpCategory Cmdlet

#>

[CmdletBinding(DefaultParameterSetName='Items', SupportsTransactions=$true)]
param(
    [Parameter(ParameterSetName='Items', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [System.String[]]
    ${Path},

    [Parameter(ParameterSetName='LiteralItems', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)]
    [Alias('PSPath')]
    [System.String[]]
    ${LiteralPath},

    [Parameter(Position=1)]
    [System.String]
    ${Filter},

    [System.String[]]
    ${Include},

    [System.String[]]
    ${Exclude},
    
    [System.String]
    ${Pattern},

    [Switch]
    ${Recurse},

    [Switch]
    ${FileSizeInHumanReadableFormat},

    [Switch]
    ${Force},

    [Switch]
    ${Name})

begin
{
    try {
        $outBuffer = $null
        if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
        {
            $PSBoundParameters['OutBuffer'] = 1
        }
        $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\Get-ChildItem', [System.Management.Automation.CommandTypes]::Cmdlet)
        $cmd = ""
        if($FileSizeInHumanReadableFormat) {
          $PSBoundParameters.Remove('FileSizeInHumanReadableFormat') | Out-Null
          $cmd = @"
            | ForEach-Object {
                `$_length=Switch(`$_.length) {
                  { `$_ -lt 1kb } 
                           {  '{0}B' -f (`$_) ;break }
                  { `$_ -lt 1MB }
                           {  '{0}KB' -f ([math]::round(`$(`$_/ 1kb)), 2) ;break }
                  { `$_ -lt 1gb }
                            { '{0}MB' -f ([math]::round(`$(`$_/ 1mb), 2)) ;break }
                  defaut { 
                            {  '{0}GB' -f ([math]::round(`$(`$_/ 1gb), 2)) ;break }
                   }
                }
                if(`$_.PSISContainer) { `$_length=`$null }
                New-Object PSObject -Property @{
                  Mode = `$_.Mode
                  LastWriteTime = `$_.LastWriteTime
                  Length = `$_length
                  Name = `$_.Name
                }
            }         
"@
        }
        if($PSBoundParameters['Pattern']) {
          if($Filter -or $Include) {
           throw "les paramètres Pattern et Filter/Include sont mutuellemnt exculsive"
          } else {
          $PSBoundParameters.Remove('Pattern') | Out-Null
          $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where { $_.Name -imatch "$Pattern"  } }
          }
        } else {
          $scriptCmd = {& $wrappedCmd @PSBoundParameters } 
        }
        $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
                $scriptCmd.ToString() + $cmd
            )
        $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
        $steppablePipeline.Begin($PSCmdlet)
    } catch {
        throw
    }
}

process
{
    try {
        $steppablePipeline.Process($_)
    } catch {
        throw
    }
}

end
{
    try {
        $steppablePipeline.End()
    } catch {
        throw
    }
}

}
Usage:

Code: Select all

Get-ChildItem  -Path $env:windir -Pattern "^\d{2}" -FileSizeInHumanReadableFormat

Get-ChildItem -path $env:windir -filter *.txt -FileSizeInHumanReadableFormat
for more details:

https://walid-toumi.blogspot.com/2011/1 ... viale.html

----------------------------

#2 21 Nov 2011 19:35
Simon Sheppard


Re: Proxy Function: Get-ChildItem

Heres a google translation of the original web page:
Get-ChildItem a bit more friendly:)
Hi, I do not know if anyone else had the idea to add these features to the cmdlet "Get-ChildItem 'and I did not also test to see if Powershell vNext implements the one of these features ... then I thought why wait?! I have everything I need to configure my 'cmdlets' .... then the first thing that occurred to love me is to add two new parameters: 'FileSizeInHumanReadableFormat' and 'pattern' is the first implementation of a switch '-lh' command lunix 'ls' which means "Display File Size in Human Readable Format" and the other setting to go one step beyond the simple wildcards used by "filter" and "include" ... 'Pattern' will allow us to use RegExp in our recheche:) you can see the new parameters of the 'Get-ChildItem' by writing this:

Code: Select all

     Get-Command Get-ChildItem -TotalCount 1 -Syntax  
in fact the mechanism of execution of the commands in "Windows Powershell"

Code: Select all

      Precedence help
will allow us to execute our function before the cmdlet "Get-Childtem '

It's a nice idea, I'm tempted to try and pull out the code for 'FileSizeInHumanReadableFormat' and make a more generic 'BinarySizeInHumanReadableFormat' so you could pipe values from GCI or Measure-item or sort-item or whatever.

----------------------------

#3 23 Nov 2011 11:05
jumper


Re: Proxy Function: Get-ChildItem

hi Simon,

maybe this:

Code: Select all

Function Get-ChildItem {
<#

.ForwardHelpTargetName Get-ChildItem
.ForwardHelpCategory Cmdlet

#>

[CmdletBinding(DefaultParameterSetName='Items', SupportsTransactions=$true)]
param(
    [Parameter(ParameterSetName='Items', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [System.String[]]
    ${Path},

    [Parameter(ParameterSetName='LiteralItems', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)]
    [Alias('PSPath')]
    [System.String[]]
    ${LiteralPath},

    [Parameter(Position=1)]
    [System.String]
    ${Filter},

    [System.String[]]
    ${Include},

    [System.String[]]
    ${Exclude},
    
    [System.String]
    ${Pattern},

    [Switch]
    ${Recurse},

    [Switch]
    ${BinarySizeInHumanReadableFormat},

    [Switch]
    ${Force},

    [Switch]
    ${Name})

begin
{
    try {
        $outBuffer = $null
        if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
        {
            $PSBoundParameters['OutBuffer'] = 1
        }
        $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\Get-ChildItem', [System.Management.Automation.CommandTypes]::Cmdlet)
        $cmd = ""
        if($BinarySizeInHumanReadableFormat) {
          $PSBoundParameters.Remove('BinarySizeInHumanReadableFormat') | Out-Null
          $cmd = @"
            | ForEach-Object {
                 `$_length=Switch(`$_.length) {
                  { `$_ -lt 1kb } 
                           {  '{0}B' -f (`$_) ;break }
                  { `$_ -lt 1MB }
                           {  '{0}KB' -f ([math]::round(`$(`$_/ 1kb)), 2) ;break }
                  { `$_ -lt 1gb }
                            { '{0}MB' -f ([math]::round(`$(`$_/ 1mb), 2)) ;break }
                  defaut { 
                            {  '{0}GB' -f ([math]::round(`$(`$_/ 1gb), 2)) ;break }
                   }
                }
                if(`$_.PSISContainer) { `$_length=`$null }
                 `$_ | Add-Member noteproperty size `$_.length -Pass |  
                    Add-Member noteproperty length `$_length -PassThru -Force              
            }         
"@
        }
        if($PSBoundParameters['Pattern']) {
          if($Filter -or $Include) {
           throw "les paramètres Pattern et Filter/Include sont mutuellemnt exculsive"
          } else {
          $PSBoundParameters.Remove('Pattern') | Out-Null
          $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where { $_.Name -imatch "$Pattern"  } }
          }
        } else {
          $scriptCmd = {& $wrappedCmd @PSBoundParameters } 
        }
        $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
                $scriptCmd.ToString() + $cmd
            )
        $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
        $steppablePipeline.Begin($PSCmdlet)
    } catch {
        throw
    }
}

process
{
    try {
        $steppablePipeline.Process($_)
    } catch {
        throw
    }
}

end
{
    try {
        $steppablePipeline.End()
    } catch {
        throw
    }
}

}
example:
PS D:\Documents and Settings\walid2mi> Get-ChildItem -Pattern "\."


Répertoire : D:\Documents and Settings\walid2mi


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 21/11/2010 11:28 6 k.txt
-a--- 04/11/2010 10:49 1362 t.txt
-a--- 05/11/2010 06:14 3070 w.txt


PS D:\Documents and Settings\walid2mi> Get-ChildItem -Pattern "\." -BinarySize


Répertoire : D:\Documents and Settings\walid2mi


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 21/11/2010 11:28 6B k.txt
-a--- 04/11/2010 10:49 1KB t.txt
-a--- 05/11/2010 06:14 3KB w.txt


PS D:\Documents and Settings\walid2mi> Get-ChildItem -Pattern "\." -BinarySize | sort -Descending size


Répertoire : D:\Documents and Settings\walid2mi


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 05/11/2010 06:14 3KB w.txt
-a--- 04/11/2010 10:49 1KB t.txt
-a--- 21/11/2010 11:28 6B k.txt