2011-01-19 32 views
7

我想在PowerShell中寫出當前進程ID。此作品:在PowerShell中連接字符串和表達式結果

$processId = $([System.Diagnostics.Process]::GetCurrentProcess()).Id 
Write-Output "My process ID is $processId" 

但是,如果可能,我想在一行中完成。用$([System.Diagnostics.Process]::GetCurrentProcess()).Id代替變量似乎沒有評估表達式。

回答

12
'My process id is {0}' -f [System.Diagnostics.Process]::GetCurrentProcess().Id 

如果我們使用自動變量:

'My process id is {0}' -f $pid 
7
Write-Output "My process ID is $([System.Diagnostics.Process]::GetCurrentProcess().Id)" 

基本上你只需要標識後,移動右括號。

+0

啊,謝謝你,那是有效的! – EMP 2011-01-19 23:30:29

8

這可能是一點點簡單:

$pid 

"My process id is $pid" 

有關自動變量的詳細信息執行:

man about_automatic_variables 
+0

+1雖然我的問題主要是關於字符串連接,但這也很有幫助。 – EMP 2011-01-20 02:30:34

+1

是的,因爲你想要在字符串中使用`subexpression operator`,例如「blah $(.. expression ..)yada」。 PowerShell將評估`$()`(即子表達式)內部的表達式,並將結果呈現爲一個字符串並在該位置插入該字符串。 – 2011-01-20 05:04:24

相關問題