当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 周五的格式化乐趣

作者:精品下载站 日期:2024-12-14 07:42:37 浏览:14 分类:玩电脑

周五的格式化乐趣


PowerShell 非常擅长从网络中的计算机系统检索各种信息。通常,数据的格式很难让人一目了然。例如,当您看到像 1202716672 这样的值时,它的单位是 MB 还是 GB?如果您需要将该值视为 KB 该怎么办?我不了解你,但我不擅长在脑海中即时进行这些转换。相反,我们经常使用这样的命令。

PS C:\> get-ciminstance win32_computersystem | select Name,Number*,@{Name="MemGB";Expression={$_.totalphysicalmemory/1gb -as [int]}},Manufacturer


Name                      : WIN81-ENT-01
NumberOfLogicalProcessors : 4
NumberOfProcessors        : 1
MemGB                     : 8
Manufacturer              : LENOVO

这比查看值 8589934592 容易得多。在计算百分比时,同样的情况也适用。我们再次回到使用带有 Select-Object 的自定义哈希表。当然,您可以加倍努力,创建自定义格式和类型扩展。但有时,至少就我自己而言,你想要介于两者之间的东西。所以我创建了两个函数Format-Value和Format-Percent并将它们打包为一个模块。

Function Format-Percent {

<#
.Synopsis
Calculate a percent
.Description
This command calculates a percentage of a value from a total, with the formula (value/total)*100. The default is to return a value to 2 decimal places but you can configure that with -Decimal. There is also an option to format the percentage as a string which will include the % symbol.
.Parameter Value
The numerator value. The parameter has aliases of X and Numerator.
.Parameter Total
The denominator value. The parameter has aliases of Y and Denominator.
.Parameter Decimal
The number of decimal places to return between 0 and 15.
.Parameter String
Format the percentage as a string which will include the % symbol. This is done using the -f operator.
.Example
PS C:\> Format-Percent 1234 5000
24.68
.Example
PS C:\> get-ciminstance win32_operatingsystem -computer chi-dc04 | select PSComputername,TotalVisibleMemorySize,@{Name="PctFreeMem";Expression={ Format-Percent $_.FreePhysicalMemory $_.TotalVisibleMemorySize  }}

PSComputerName             TotalVisibleMemorySize           PctFreeMem
--------------             ----------------------           ----------
chi-dc04                                  1738292                23.92
.Example
PS C:\> get-ciminstance win32_operatingsystem -computer chi-dc04 | select PSComputername,TotalVisibleMemorySize,@{Name="PctFreeMem";Expression={ Format-Percent $_.FreePhysicalMemory $_.TotalVisibleMemorySize -asString  }}
PSComputerName             TotalVisibleMemorySize           PctFreeMem
--------------             ----------------------           ----------
chi-dc04                                  1738292           23.92%


.Notes
Last Updated: May 30, 2014
Version     : 1.0

#>

[cmdletbinding(DefaultParameterSetName="None")]
Param(
[Parameter(Position=0,Mandatory,HelpMessage="What is the value?")]
[ValidateNotNullorEmpty()]
[Alias("X","Numerator")]
$Value,
[Parameter(Position=1,Mandatory,HelpMessage="What is the total value?")]
[ValidateNotNullorEmpty()]
[Alias("Y","Denominator")]
$Total,
[ValidateNotNullorEmpty()]
[ValidateRange(0,15)]
[int]$Decimal=2,
[Parameter(ParameterSetName="String")]
[Switch]$AsString
)

Write-Verbose "Calculating percentage from $Value/$Total to $decimal places"
$result = $Value/$Total

if ($AsString) {
    Write-Verbose "Writing string result"
    $pctstring = "{0:p$Decimal}" -f $result
    #remove the space before the % symbol
    $pctstring.Replace(" ","")

}
else {
    Write-Verbose "Writing numeric result"
    [math]::Round( ($result*100),$Decimal)
}

} #end function


Function Format-Value {

<#
.Synopsis
Format a numeric value
.Description
This command will format a given numeric value. By default it will treat the number as an integer. Or you can specify a certain number of decimal places. The command will also allow you to format the value in KB, MB, etc. Or you can let the command autodetect the value and divide by an appropriate value.
.Parameter Unit
The unit of measurement for your value. Valid choices are "KB","MB","GB","TB", and "PB". If you don't specify a unit, the value will remain as is, although you can still specify the number of decimal places.
.Parameter Decimal
The number of decimal places to return between 0 and 15.

.Example
PS C:\> Get-CimInstance -class win32_logicaldisk -filter "DriveType=3" | Select DeviceID,@{Name="SizeGB";Expression={$_.size | format-value -unit GB}},@{Name="FreeGB";Expression={$_.freespace | format-value -unit GB -decimal 2}}

DeviceID                            SizeGB                                      FreeGB
--------                            ------                                      ------
C:                                     200                                      124.97
D:                                     437                                       29.01
E:                                      25                                        9.67
.Example
PS C:\> (get-process chrome | measure ws -sum ).sum | format-value -Autodetect -verbose -Decimal 4
VERBOSE: Formatting 1180504064
VERBOSE: Using Autodetect
VERBOSE: ..as GB
VERBOSE: Reformatting 1.09943008422852
VERBOSE: ..to 4 decimal places
1.0994
.Notes
Last Updated: 5/29/2014
Version     : 1.0


#>

[cmdletbinding(DefaultParameterSetName="Default")]
Param(
[Parameter(Position=1,Mandatory,ValueFromPipeline)]
[ValidateNotNullorEmpty()]
$InputObject,
[Parameter(Position=0,ParameterSetName="Default")]
[ValidateSet("KB","MB","GB","TB","PB")]
[string]$Unit,
[ValidateRange(0,15)]
[int]$Decimal,
[Parameter(ParameterSetName="Auto")]
[switch]$Autodetect
)

Process {
    Write-Verbose "Formatting $Inputobject"
    if ($PSCmdlet.ParameterSetName -EQ "Default") {
    Write-Verbose "..as $Unit"
    Switch ($Unit) {
     "KB" { $value =  $Inputobject / 1KB ; break }
     "MB" { $value =  $Inputobject / 1MB ; break }
     "GB" { $value =  $Inputobject / 1GB ; break }
     "TB" { $value =  $Inputobject / 1TB ; break }
     "PB" { $value =  $Inputobject / 1PB ; break }
     default { 
      #just use the raw value
      $value = $Inputobject 
      }
    } #switch
    }
    else {
      Write-Verbose "Using Autodetect"
      
      if ($InputObject -ge 1PB) {
        Write-Verbose "..as PB"
        $value =  $Inputobject / 1PB
      }
      elseif ($InputObject -ge 1TB) {
        Write-Verbose "..as TB"
        $value =  $Inputobject / 1TB
      }
      elseif ($InputObject -ge 1GB) {
        Write-Verbose "..as GB"
        $value =  $Inputobject / 1GB
      }
      elseif ($InputObject -ge 1MB) {
        Write-Verbose "..as MB"
        $value =  $Inputobject / 1MB
      }
      elseif ($InputObject -ge 1KB) {
        Write-Verbose "..as KB"
        $value =  $Inputobject / 1KB
      }
      else { 
        Write-Verbose "..as bytes"
        $value = $InputObject
      }

    }
    Write-Verbose "Reformatting $value"
    if ($decimal) {
        Write-Verbose "..to $decimal decimal places"
        [math]::Round($value,$decimal)
    }
    else {
        Write-verbose "..as [int]"
        $value -as [int]
    }
} #process
} 

Set-Alias -Name fv -Value Format-Value
Set-Alias -Name fp -value Format-Percent

Export-ModuleMember -Function * -Alias *

Format-Value 将采用任何值,并默认将其舍入为整数。或者,您可以指定将值格式化为特定的测量单位,例如 GB 或 MB。您甚至可以指定小数位数。或者,您可以使用 -AutoDetect 参数,该函数将对您的值的“大小”做出最佳猜测。如果您想知道它检测到的单位,请使用 -Verbose。

我对百分比做了类似的事情。您所要做的就是指定一个值和总计,函数会完成其余的工作。同样,您可以指定小数位数。默认情况下,该函数会向管道写入一个数值,我发现如果您想排序,这会更容易。但您也可以指定获取字符串形式的百分比,这将使用 -f 运算符。该字符串将包含% 符号。我采取了额外的步骤来删除值和符号之间的空格。

有了这个函数,我的 PowerShell 表达式变得更容易编写了。

Get-CimInstance -class win32_logicaldisk -filter "DriveType=3" |
Select DeviceID,
@{Name="SizeGB";Expression={$_.size | fv -unit GB}},
@{Name="FreeGB";Expression={$_.freespace | fv -unit GB -decimal 2}},
@{Name="PctFree";Expression={fp -x $_.freespace -y $_.size}}

在代码示例中,我使用了函数和参数别名。但我喜欢这个结果。

[玩转系统] 周五的格式化乐趣

下载 FormatFunctions.zip 将其解压到您的模块目录中,然后就可以开始了。我已将最低 PowerShell 版本设置为 3.0,尽管我认为没有什么会阻止这些命令在 v2 上运行。但无论如何我还是想带你去至少 3。

我希望您能让我知道您的想法以及您希望添加到模块中的其他类型的数据格式。

注意:更新已发布在 http://bit.ly/1PzSnJa

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯