0

Let's execute a PS script that is stored in a file that does not have .ps1 extension:

Invoke-Command -ScriptBlock ([ScriptBlock]::Create((Get-Content path\script.txt)))

How can I store full STDOUT and STDERR outputs into one or two variable(s), with no output to screen?

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • 1
    The same way you would in most scripting languages, redirection. Add `$var =` to the start of your line and `*>&1` to the end. – Maximilian Burszley Aug 18 '23 at 17:07
  • Aside, why are you using `Invoke-Command` ? either `&` or `.` or even `.Invoke()` is enough to execute a scriptblock. – Santiago Squarzon Aug 18 '23 at 17:14
  • @SantiagoSquarzon I think PowerShell has a limitation that file _must_ end in `.ps1` still. – Maximilian Burszley Aug 18 '23 at 17:15
  • 3
    My security side is internally screaming 'malicious intent!' from reading this. Hiding the fact that something's a script, and hiding any output from it seems pretty dubious to me. – TheMadTechnician Aug 18 '23 at 17:16
  • @MaximilianBurszley That would apply if you were trying to invoke the path like `& 'path\to\script.txt'` but op is already reading the file as plain text and creating a new scriptblock out of it so essentially `& ([scriptblock]::Create((Get-Content ....))` is what I meant. Also `Invoke-Expression` is another possibility. In any case this has been answered many times before just that OP didn't care to search what's already there. – Santiago Squarzon Aug 18 '23 at 17:19
  • @MaximilianBurszley - Where exactly I need to add `*>&1` - could you please post full line? – Ωmega Aug 18 '23 at 17:19
  • @SantiagoSquarzon - I do care and I read many posts, sir. – Ωmega Aug 18 '23 at 17:20
  • First google search for a SO answer leads me to this link: https://stackoverflow.com/a/8938256/15339544 which has the answer you're looking for but instead of redirecting to a file you would assign to a variable – Santiago Squarzon Aug 18 '23 at 17:22
  • @SantiagoSquarzon - My script is in `txt` file and that makes my case different – Ωmega Aug 18 '23 at 17:23

0 Answers0