7

I want to write out the current process ID in PowerShell. This works:

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

However, I want to do it in one line, if possible. Substituting the $([System.Diagnostics.Process]::GetCurrentProcess()).Id for the variable doesn't seem to evaluate the expression.

3 Answers 3

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

And if we use automatic variables:

'My process id is {0}' -f $pid
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I like that - easy string formatting. I'm changing my accepted answer to this one.
9

This might be a tad simpler:

$pid

or

"My process id is $pid"

For more info about automatic variables execute:

man about_automatic_variables

2 Comments

+1 Although my question was mainly about string concatenation this is very helpful to know, too.
Yeah for that you want to use the subexpression operator inside the string e.g. "blah $(..expression..) yada". PowerShell will evaluate the expression inside the $() (ie subexpression) and render the results to a string and insert that string at that location.
8
Write-Output "My process ID is $([System.Diagnostics.Process]::GetCurrentProcess().Id)"

Basically you just needed to move the closing parenthesis after the Id.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.