手机
当前位置:查字典教程网 >脚本专栏 >PowerShell >Powershell小技巧之使用-F方法带入数据
Powershell小技巧之使用-F方法带入数据
摘要:封闭在双引号中的字符串能够直接使用变量,这是常用的手法,如代码:$name=$host.Name"Yourhostiscalled$name...

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

$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方法带入数据】相关文章:

PowerShell函数中使用$PSBoundParameters获取输入参数列表实例

PowerShell中计算时间差的方法

PowerShell中定义多行字符串变量的方法

PowerShell判断某天是星期几的方法

Powershell学习笔记--使用正则表达式查找文件

Powershell小技巧之使用WMI查询插上的U盘

Powershell后台作业、异步操作实例

PowerShell显示隐藏文件和系统文件的方法

PowerShell中使用GetType获取变量数据类型

Windows Powershell 自定义控制台

精品推荐
分类导航