How can a cmdlet determine if it is if it is being called from a job or RunSpace?

Viewed 78

I am writing some cmdlets , that need to do some extra things if they are being called from the context of a job or RunSpace ?

If these cmdlets are not running from a Job or RunSpace the progress and status is on the console. But if they are running in the context of a Job or RunSpace , that is reported through a file. Instead of asking the user to do something else, I want to auto detect this case.

1 Answers

You can base your decision on the value of $Host.Name (in PowerShell code) / the .Name property of the .Host property of the cmdlet base class, PSCmdlet (in C# code implementing a cmdlet), which is the name of the component hosting PowerShell:[1]

  • PowerShell code:
$outputToFile = $Host.Name -in 'ServerRemoteHost', 'Default Host'
  • C# code (in a class derived from PSCmdlet):
bool outputToFile = Host.Name == "ServerRemoteHost" || Host.Name == "Default Host";

[1] The automatic $Host variable reports the current PowerShell host, which is a .NET class derived from System.Management.Automation.Host.PSHost.

Related