Powershell小技巧之使用-F方法带入数据
封闭在双引号中的字符串能够直接使用变量,这是常用的手法,如代码:
$name=$host.Name "Yourhostiscalled$name."
可是这个技巧也有限制。如果你想要显示对象的属性而不是这个变量的本身,例如这样将会失败:
PS>"Yourhostiscalled$host.Name." YourhostiscalledSystem.Management.Automation.Internal.Host.InternalHost.Name.
这是因为PS仅能解决变量的本身(如$host),而不支持它的属性。
同时你也不能控制数字的格式,执行下面代码,结果看起来有很多位数字:
#getavailablespaceinbytesforC:drive $freeSpace=([WMI]'Win32_LogicalDisk.DeviceID="C:"').FreeSpace #converttoMB $freeSpaceMB=$freeSpace/1MB #output "YourC:drivehas$freeSpaceMBMBspaceavailable."
这里有一个-F方法能同时解决这些问题。只需要将它放在模版文本的左边,它的值就会被正确的带入:
#insertanydataintothetexttemplate 'Yourhostiscalled{0}.'-f$host.Name #calculatefreespaceonC:inMB $freeSpace=([WMI]'Win32_LogicalDisk.DeviceID="C:"').FreeSpace $freeSpaceMB=$freeSpace/1MB #outputwithjustONEdigitafterthecomma 'YourC:drivehas{0:n1}MBspaceavailable.'-f$freeSpaceMB
现在你看,使用-F让你有两个有利条件:这里带括号的占位符指出了带入参数的起始位置,同时它还接受格式。“n1”代表保留1位小数。可以改变它来满足你的需求。
支持PS所有版本