1

I'm trying to run Invoke-Command within a PowerShell script to run scripts on remote servers. It retrieves the computer names and scripts to run from an XML file. Code sample is below. The script executes but nothing on the remote server is being run. I've tried 2 different ways to run Invoke-Command.

[string] $computer = "lumen"
[string] $scriptBlock = "cd C:\Scripts\Update-Apps; ./Update-Apps"

$session = New-PSSession -ComputerName $computer
Invoke-Command -Session $session -ScriptBlock { $scriptBlock }

#Invoke-Command -ComputerName $computer -ScriptBlock { $scriptBlock }

What am I doing wrong with Invoke-Command? Thanks!

UltraJ
  • 467
  • 1
  • 10
  • 20
  • you're passing it a string. To run "*stuff*" on a remote machine you have to specify so using `$using:scriptblock` (remote variable) or, an argument list with `$args`. – Abraham Zinala May 04 '21 at 20:55

1 Answers1

0

You are passing in a scriptblock with a string. When it will call it, it will basically have the same effect as writing $scriptBlock in your terminal. You have to actually execute the string in the scriptblock. You could use Invoke-Expression.

[string] $computer = "lumen"
[scriptblock] $scriptBlock = { "cd C:\Scripts\Update-Apps; ./Update-Apps" | Invoke-Expression }

$session = New-PSSession -ComputerName $computer
Invoke-Command -Session $session -ScriptBlock $scriptblock

Or you could write directly your command as PowerShell code in the scriptblock.

[string] $computer = "lumen"
[scriptblock] $scriptBlock = { cd C:\Scripts\Update-Apps; ./Update-Apps }

$session = New-PSSession -ComputerName $computer
Invoke-Command -Session $session -ScriptBlock $scriptblock

It doesn't have to be a string.

Vivere
  • 1,919
  • 4
  • 16
  • 35
  • 1
    The 2nd solution is much preferable, given that [`Invoke-Expression` (`iex`) should generally be avoided](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/) – mklement0 May 04 '21 at 21:16
  • You also don't even need to `cd` into it, to run the application as long as the full path is provided. – Abraham Zinala May 04 '21 at 21:21