封閉在雙引號中的字符串能夠直接使用變量,這是常用的手法,如代碼:
$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),而不支持它的屬性。
同時你也不能控制數字的格式,執(zhí)行下面代碼,結果看起來有很多位數字:
# 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讓你有兩個有利條件:這里帶括號的占位符指出了帶入參數的起始位置,同時它還接受格式?!皀1”代表保留1位小數??梢愿淖兯鼇頋M足你的需求。
支持PS所有版本