How to check if a Powershell script is running remotely

我只是一个虾纸丫 提交于 2019-11-29 10:54:55

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"
    }
Rob

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!