Search code examples
powershellremotinginvoke-command

PowerShell Invoke-Command on an advanced function


I have an advanced function Copy-FilesHC that is available in a module file. This function copies some files from the Source to the Destination folder and generates some output for in a log file.

The function works fine locally:

Copy-FilesHC -Source $Src -Destination $Des *>> $Log

It also works on a remote machine:

# For remote use we need to make it available first
Import-Module (Get-Command Copy-FilesHC).ModuleName

Invoke-Command -Credential $Cred -ComputerName $Host -ScriptBlock ${Function:Copy-FilesHC} -ArgumentList $LocalSrc, $LocalDes

However, I can't seem to figure out how I can have it pass the output to a log file like in the first command. When I try the following, it fails:

Invoke-Command -Credential $Cred -ComputerName $Host -ScriptBlock ${Function:Copy-FilesHC *>> $Log} -ArgumentList $LocalSrc, $LocalDes

Invoke-Command : Cannot validate argument on parameter 'ScriptBlock'. The argument is null. Provide a vali
d value for the argument, and then try running the command again.

As indicated here I thought the $ sign for the ScriptBlock was incorrect. But this way I don't need to put my advanced function in a ScriptBlock to copy it over as it now happens automatically while it's only available within the module. So I just need to find out how to capture the output in the log file.

Thank you for your help.


Solution

  • Found the solution just a few minutes ago:

    # For remote use we need to make it available first
    Import-Module (Get-Command Copy-FilesHC).ModuleName
    
    Invoke-Command -Credential $Cred -ComputerName $Host -ScriptBlock ${Function:Copy-FilesHC} -ArgumentList $LocalSrc, $LocalDes *>> $Log