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

$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所有版本

点赞(119)

评论列表共有 0 条评论

立即
投稿
返回
顶部