华域联盟 PowerShell Powershell小技巧之使用-F方法带入数据

Powershell小技巧之使用-F方法带入数据

封闭在双引号中的字符串能够直接使用变量,这是常用的手法,如代码:

$name = $host.Name 
"Your host is called $name."

可是这个技巧也有限制。如果你想要显示对象的属性而不是这个变量的本身,例如这样将会失败:

PS> "Your host is called $host.Name."
Your host is called System.Management.Automation.Internal.Host.InternalHost.Name.

这是因为PS仅能解决变量的本身(如$host),而不支持它的属性。

同时你也不能控制数字的格式,执行下面代码,结果看起来有很多位数字:

# get available space in bytes for C: drive 
$freeSpace = ([WMI]'Win32_LogicalDisk.DeviceID="C:"').FreeSpace 
 
# convert to MB 
$freeSpaceMB = $freeSpace / 1MB 
 
# output 
"Your C: drive has $freeSpaceMB MB space available."

这里有一个 -F 方法能同时解决这些问题。只需要将它放在模版文本的左边,它的值就会被正确的带入:

# insert any data into the text template 
'Your host is called {0}.' -f $host.Name 
 
# calculate free space on C: in MB 
$freeSpace = ([WMI]'Win32_LogicalDisk.DeviceID="C:"').FreeSpace 
$freeSpaceMB = $freeSpace /1MB 

# output with just ONE digit after the comma 
'Your C: drive has {0:n1} MB space available.' -f $freeSpaceMB

现在你看,使用-F让你有两个有利条件:这里带括号的占位符指出了带入参数的起始位置,同时它还接受格式。“n1”代表保留1位小数。可以改变它来满足你的需求。

支持PS所有版本

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Powershell小技巧之使用-F方法带入数据

转载请保留出处和原文链接:https://www.cnhackhy.com/14437.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部