How to check if a Powershell script is running rem

2019-01-19 20:14发布

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?

5条回答
欢心
2楼-- · 2019-01-19 20:56

I think it's possible in your script test if

$myinvocation.mycommand.path -eq $null

then if is true is running remotely via Invoke-command.

I have not test it accurately but I think it can work.

查看更多
够拽才男人
3楼-- · 2019-01-19 20:58

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
查看更多
Lonely孤独者°
4楼-- · 2019-01-19 21:03
    if ($PSSenderInfo) {
        "Running remote"
    }
    else {
        "Running local"
    }
查看更多
成全新的幸福
5楼-- · 2019-01-19 21:10

Get-Host returns, amongst other information a Name:

PS> (Get-Host).Name
ConsoleHost
PS> (Invoke-Command -ComputerName dev2 -Script {Get-Host}).Name
ServerRemoteHost
查看更多
闹够了就滚
6楼-- · 2019-01-19 21:12

you can check computername in $MyInvocation :

PS>Invoke-Command -ComputerName smacnt01 -ScriptBlock {$MyInvocation}

PSComputerName   : smacnt01
RunspaceId       : 333f5333-0ca5-4461-8f38-cb086fbd1ea4
MyCommand        : $MyInvocation
BoundParameters  : {}
UnboundArguments : {}
ScriptLineNumber : 0
OffsetInLine     : 0
HistoryId        : -1
ScriptName       :
Line             :
PositionMessage  :
InvocationName   :
PipelineLength   : 1
PipelinePosition : 1
ExpectingInput   : False
CommandOrigin    : Runspace
查看更多
登录 后发表回答