Milton T. Machado S
Milton T. Machado S

Reputation: 181

Print a variable on Powershell

I need print on Powershell a line comand through a variable , I called $em_result, for example, em_result=20, Thanks.

$em_result = ´gc C:\Users\mtmachadost\Desktop\Test\logError.txt | ?{$_ -match 'cajica11'} | %{($_ -split "\s+")[3]} |  Measure -Sum | Select -Exp Sum'´
Write-Host"$em_result"

Upvotes: 0

Views: 17529

Answers (3)

Matt
Matt

Reputation: 46730

While I am not sure of the motivation for what you are trying to accomplish it sounds like you are trying to save the command $em_result so that you can run when you want. So that way, you are not saving the point in time result but rather every time you call it the result will be from that time.

Like Tony Hinkle answered you need to save the command as a string. However there is more to escape than just the quotes. The pipeline variable $_ would also come into play. As it stands a simple here-string would make it so you don't have to worry about escaping anything.

$em_result = @'
gc 'C:\Users\mtmachadost\Desktop\Test\logError.txt' | ?{$_ -match 'cajica11'} | %{($_ -split "\s+")[3]} |  Measure -Sum | Select -Exp Sum
'@

Now you could call this string and get the results

Write-Host "`$em_result = $(Invoke-Expression $em_result)"

I guess you were trying to use the backtick pair like and escape quote pair which made me think this is what you wanted. Backtick will only escape the one following character. Invoke-Expression will execute the string we pass it as code.

Upvotes: 1

user4003407
user4003407

Reputation: 22132

If you want to save command line to variable, I would recommend to save it as ScriptBlock rather as String:

$em_result = {gc C:\Users\mtmachadost\Desktop\Test\logError.txt | ?{$_ -match 'cajica11'} | %{($_ -split "\s+")[3]} |  Measure -Sum | Select -Exp Sum'}
Write-Host "`$em_result = $(&$em_result)"

This way you:

  1. does not have to escape things.
  2. can convert it to string.
  3. can invoke it by invoke operator (& or .).
  4. have syntax highlighting when you edit it in ISE.
  5. any syntax errors get caught when it parsed, not when it executed.
  6. ScriptBlock linked to its file and line, so you can set breakpoints in it.

Upvotes: 2

Tony Hinkle
Tony Hinkle

Reputation: 4742

When assigning it, you need to specify that it is a string, or else Powershell will try to execute it. You also need to delimit it with double quotations, and escape the double quotation marks and dollar signs in the command with a backtick so that they are considered part of the string, not a delimiter to end the string.

$em_result = [string]"gc C:\Users\mtmachadost\Desktop\Test\logError.txt | ?{`$_ -match 'cajica11'} | %{(`$_ -split `"\s+`")[3]} |  Measure -Sum | Select -Exp Sum'"

Upvotes: 0

Related Questions