Print a variable on Powershell

Milton T. Machado S picture Milton T. Machado S · May 21, 2015 · Viewed 10.4k times · Source

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"

Answer

user4003407 picture user4003407 · May 21, 2015

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.