Powershell: How to use Invoke-Command and dot sourcing at the same time?
11:46 18 Apr 2014

I have the following scripts:

.
|-- invoke-command.ps1
|-- no-dot-sourcing.ps1
`-- with-dot-sourcing.ps1

Here are their contents:

invoke-command.ps1

$scriptPath = Split-Path -Parent $PSCommandPath
Invoke-Command `
    -ComputerName "myserver" `
    -Credential "myusername" `
    -FilePath "$scriptPath\with-dot-sourcing.ps1"

no-dot-sourcing.ps1

function getMessage() {
    return "This script just shows a message - executed on $env:COMPUTERNAME"
}

Write-Host (getMessage)

with-dot-sourcing.ps1

$scriptPath = Split-Path -Parent $PSCommandPath
. "$scriptPath\no-dot-sourcing.ps1"

Problem

If I call Invoke-Command with -FilePath "$scriptPath\no-dot-sourcing.ps1" everything works perfectly well. I need to call it with-dot-sourcing.ps1 and the reason for this is that I have some common functions that I use in other scripts. So, one solution would be to include everything in just one huge script and then everything will work, but I don't find this to be a good solution.

If I run the invoke-command.ps1 script I get the following error:

Cannot bind argument to parameter 'Path' because it is an empty string.
    + CategoryInfo          : InvalidData: (:) [Split-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.SplitPathCommand
    + PSComputerName        : myserver

The term '\no-dot-sourcing.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the 
path is correct and try again.
    + CategoryInfo          : ObjectNotFound: (\no-dot-sourcing.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : myserver 

In case it matters: I use Windows 7 Ultimate SP1 on local computer and on the server I have Windows Server 2012 Datacenter.

Is there any way I can use dot sourcing and still be able to use Invoke-Command?

powershell remote-server