How to run Invoke-Command in PowerShell Workflow?


To run Invoke-Command in PowerShell Workflow we need to use the InlineScript block because Invoke-Command is not supported directly in the workflow. The below example is without using the InlineScript block we get an error.

Example

Workflow TestInvokeCommand{
   Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
      Get-Service WINRM
   }
}

Output −

At line:2 char:5
+    Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cannot call the 'Invoke-Command' command. Other commands from this module have been packaged as workflow activities, but this
command was specifically excluded. This is likely because the command requires an interactive Windows PowerShell session, or has
behavior not suited for workflows. To run this command anyway, place it within an inline-script (InlineScript { Invoke-Command })
where it will be invoked in isolation.
   + CategoryInfo : ParserError: (:) [], ParseException
   + FullyQualifiedErrorId : CommandActivityExcluded

The above error indicates that the Invoke-Command can’t be directly used with the PowerShell and we need to use it inside the InlineScript block as shown below.

Workflow TestInvokeCommand{
   InlineScript{
      Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
         Get-Service WINRM
      }
   }
}

TestInvokeCommand

To use the outside variable in the scriptblock inside InlineScript block, we need to use $Using:VariableName. For example,

Example

Workflow TestInvokeCommand{
$server = "Labmachine2k16"
   InlineScript{
       Invoke-Command -ComputerName $using:Server -ScriptBlock{
           Get-Service WINRM
       }
   }
}

TestInvokeCommand

To store the output variable,

Output

Workflow TestInvokeCommand{
   $server = "Labmachine2k16"
   $Status =  InlineScript{
      Invoke-Command -ComputerName $using:Server -ScriptBlock{
         return( Get-Service WINRM).Status
      }
   }
   Write-Output "WinRM Status: $status"
}
 
TestInvokeCommand

Updated on: 19-Feb-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements