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?
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.
Answers. Just run Enter-PSSession -ComputerName localhost. If it enters the remote session, PS remoting is enabled.
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.
Get-Host
returns, amongst other information a Name
:
PS> (Get-Host).Name ConsoleHost PS> (Invoke-Command -ComputerName dev2 -Script {Get-Host}).Name ServerRemoteHost
if ($PSSenderInfo) {
"Running remote"
}
else {
"Running local"
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With