Search code examples
powershellpowershell-remoting

Run powershell script as local script if ComputerName is localhost or '.'


I have this script that should be able to run on both remote and localhost. It accepts -ComputerName as parameter with '.' (localhost) as default.

Currently I am testing how to validate a new remote session and wrote a little cmdlet for it. Problem is, if I run this script with '.' or localhost as the ComputerName the script tries to connect to a new remote session on my computer. That will not work as I do not have PSRemoting enabled.

This is my test script:

Function Test-PsRemoting {
[CmdletBinding()]
param(
    $ComputerName = ".",
    $Credentials    
)

$ErrorActionPreference = "Stop"

Test-Connection -ComputerName $ComputerName -Count 1 | 
    Format-List -Property PSComputerName,Address,IPV4Address,IPV6Address

Test-WSMan $ComputerName

$session = New-PSSession -ComputerName $ComputerName -Credential $Credentials
Invoke-Command -ComputerName $computername { 1 }
}

All of the commands, Test-WSMan, New-PSSession and Invoke-Command will fail as they assume I want to make a remote connection

Is it possible to let Powershell run the commands in the local session if $ComputerName is '.' or localhost or do I have to handle this myself in an if/else clause ?

The script is meant to run both local and on remote machines and I do not want PSRemoting enabled to be a requirement for running the script locally


Solution

  • AFAIK there is no $localsession-variable. You could use if-tests:

    Function Test-PsRemoting {
        [CmdletBinding()]
        param(
            $ComputerName = ".",
            $Credentials    
        )
    
        $ErrorActionPreference = "Stop"
    
        $remote = $ComputerName -notmatch '\.|localhost'
        $sc = { 1 }
    
        #If remote computer, test connection create sessions
        if($remote) {
            Test-Connection -ComputerName $ComputerName -Count 1 | 
                Format-List -Property PSComputerName,Address,IPV4Address,IPV6Address
    
            Test-WSMan $ComputerName
    
            $session = New-PSSession -ComputerName $ComputerName -Credential $Credentials
        }
    
        if($remote) {
            #If remote computer
            Invoke-Command -ComputerName $computername -ScriptBlock $sc
        } else { 
            #Localhost
            Invoke-Command -ScriptBlock $sc
        }
    
    }