Powershell小技巧之使用-F方法帶入數(shù)據(jù)
封閉在雙引號中的字符串能夠直接使用變量,這是常用的手法,如代碼:
$name = $host.Name "Your host is called $name."
可是這個技巧也有限制。如果你想要顯示對象的屬性而不是這個變量的本身,例如這樣將會失?。?/p>
PS> "Your host is called $host.Name." Your host is called System.Management.Automation.Internal.Host.InternalHost.Name.
這是因為PS僅能解決變量的本身(如$host),而不支持它的屬性。
同時你也不能控制數(shù)字的格式,執(zhí)行下面代碼,結果看起來有很多位數(shù)字:
# 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
現(xiàn)在你看,使用-F讓你有兩個有利條件:這里帶括號的占位符指出了帶入?yún)?shù)的起始位置,同時它還接受格式?!皀1”代表保留1位小數(shù)??梢愿淖兯鼇頋M足你的需求。
支持PS所有版本
相關文章
PowerShell中使用GetType獲取變量數(shù)據(jù)類型
這篇文章主要介紹了PowerShell中使用GetType獲取變量數(shù)據(jù)類型,本文使用實例來說明GetType的使用方法,并對返回值作了一定的解釋,需要的朋友可以參考下2014-08-08
PowerShell使用match操作符來篩選數(shù)組
本文介紹PowerShell中使用match操作符,配合正則表達式從數(shù)組中篩選出想要的內(nèi)容,需要的朋友可以參考下2016-11-11
用PowerShell刪除N天前或指定日期(前后)創(chuàng)建(或修改)的文件
這篇文章主要介紹了用PowerShell刪除N天前或指定日期(前后)創(chuàng)建(或修改)的文件,需要的朋友可以參考下2016-11-11
PowerShell中的特殊變量$null介紹和創(chuàng)建多行注釋小技巧
這篇文章主要介紹了PowerShell中的特殊變量$null介紹和創(chuàng)建多行注釋小技巧,需要的朋友可以參考下2014-08-08

