[玩转系统] 周五的格式化乐趣
作者:精品下载站 日期: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
- 上一篇:[玩转系统] PowerShell 提醒作业
- 下一篇:[玩转系统] 抓取系统内部
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag