您现在的位置是:网站首页> 编程资料编程资料
Powershell小技巧之使用-F方法带入数据_PowerShell_
2023-05-26
366人已围观
简介 Powershell小技巧之使用-F方法带入数据_PowerShell_
封闭在双引号中的字符串能够直接使用变量,这是常用的手法,如代码:
$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小技巧之播放WAV声音_PowerShell_
- Powershell小技巧之使用Jint引擎在PowerShell中执行Javascript函数_PowerShell_
- Powershell小技巧之使用WMI查询插上的U盘_PowerShell_
- Powershell小技巧之使用WMI测试服务响应_PowerShell_
- Powershell小技巧之系统运行时间_PowerShell_
- Windows Powershell 执行文件和脚本_PowerShell_
- Windows Powershell 通过函数扩展别名_PowerShell_
- Windows Powershell 别名_PowerShell_
- Powershell小技巧之编辑Hosts文件_PowerShell_
- Powershell小技巧之记录脚本的操作_PowerShell_
