Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Powershell script is running remotely

I have a script that can be run either locally or remotely (via WinRM), however I would like it to behave slightly differently when run on a remote machine. I realise that I can pass in a switch to the script to identify whether it is running locally or remotely, but I want to know if it is possible for the script itself to detect whether it is running remotely?

like image 460
Paul Bevis Avatar asked Nov 15 '12 09:11

Paul Bevis


People also ask

How do you check if a service is running on a remote computer PowerShell?

Use PowerShell to Check Service Status on a Remote Computer You can use the Get-Service cmdlet to get the status of services not only on the local but also on remote computers. To do this, use the –ComputerName parameter. You can use the NetBIOS, FQDN name, or an IP address as a computer name.

How do I check PS remoting status?

Answers. Just run Enter-PSSession -ComputerName localhost. If it enters the remote session, PS remoting is enabled.

How do I run a PowerShell script on a remote computer?

To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command cmdlet. The script must be on or accessible to your local computer. The results are returned to your local computer.


3 Answers

Get-Host returns, amongst other information a Name:

PS> (Get-Host).Name
ConsoleHost
PS> (Invoke-Command -ComputerName dev2 -Script {Get-Host}).Name
ServerRemoteHost
like image 88
Richard Avatar answered Oct 11 '22 09:10

Richard


    if ($PSSenderInfo) {
        "Running remote"
    }
    else {
        "Running local"
    }
like image 26
Allan Avatar answered Oct 11 '22 11:10

Allan


Checking whether $profile is defined works for me. I don't know how reliable this is, but various sources suggest that no profile is loaded in the remote session. I couldn't check the computername, as I don't have any way of knowing in advance which machine is local and which is remote.

$RunningLocally = $profile -ne $null
like image 21
Rob Avatar answered Oct 11 '22 10:10

Rob