Make Local Function accessible to remote machine when using Invoke-Command

How can we make a Local Function accessible to a remote machine when using Invoke-Command? I have invested hours trying to Google and use solutions others have suggested with no luck. Simply does not work for me.

Example of what I am trying to do:

$LogDef = function Log {

[CmdletBinding()]
param (
[Parameter(Mandatory= $true)][string]$str
)

$str = “[$(Get-Date -Format “MM/dd/yyyy hh:mm:ss”)] $str”
Write-Host “Logged: $str”
Write-Output $str

}

$HelperScriptBlock = {
Param( $LogDef )

. ([Scriptblock]::Create($LogDef))

Log “Current computer name is $env:COMPUTERNAME”
}

Invoke-Command -ComputerName $computername -ArgumentList $LogDef -ScriptBlock $HelperScriptBlock

https://www.powershellgallery.com/packages/AZSBTools/

help Export-SessionCommand -Full

NAME
    Export-SessionCommand
    
SYNOPSIS
    Function to export one or more session commands
    
    
SYNTAX
    Export-SessionCommand [-Command] <String[]> [[-ModuleName] <String>] [-Session] <PSSession> [<CommonParameters>]
    
    
DESCRIPTION
    Function to export one or more session commands
    This function takes one or more Powershell script functions/commands from current session
    and exports them to a remote PS session
    This function will ignore and not export binary functions
    Exported functions will persist on the remote computer for the user profile used with the PS remote session
    

PARAMETERS
    -Command <String[]>
        This is one or more script commands available in the current PS session
        For example Update-SmbMultichannelConnection cmdlet/function of the SmbShare PS module
        To see available script commands, you can use:
          Get-Command | ? { $_.CommandType -eq 'function' }
        
        Required?                    true
        Position?                    1
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -ModuleName <String>
        This is the name of the module that this function will create on the remote computer
        under the user profile of the remote PS session
        This will over-write prior existing module with the same name
        
        Required?                    false
        Position?                    2
        Default value                SBjr
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -Session <PSSession>
        PSSession object usually obtained by using New-PSSession cmdlet.
        
        Required?                    true
        Position?                    3
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see 
        about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216). 
    
INPUTS
    
OUTPUTS
    The function returns a list of successfully exported commands/functions, or $false if it fails
    Example:
      CommandType Name                ModuleName
      ----------- ----                ----------
      Function    Get-BitLockerStatus SBjr      
      Function    Get-SBDisk          SBjr
    
    
NOTES
    
    
        Function by Sam Boutros
        v0.1 - 12 July 2018
    
    -------------------------- EXAMPLE 1 --------------------------
    
    PS C:\>Export-SessionCommand get-saervice,get-sbdisk,bla,get-bitlockerstatus,get-service -Session $Session -Verbose
    
    
    
    
    
    
    
RELATED LINKS
    https://superwidgets.wordpress.com/category/powershell/

so your code would look like:

Install-Module AZSBTools -Force

function Log {

    [CmdletBinding()]
    param ([Parameter(Mandatory= $true)][string]$str )

    $str = "[$(Get-Date -Format "MM/dd/yyyy hh:mm:ss")] $str"
    Write-Host "Logged: $str"
    Write-Output $str

}

$Session = New-PSSession -ComputerName $computername
Export-SessionCommand Log -Session $Session 

BTW, the same PS module has a Write-Log function that may do what you need from the Log function…

This is a well documented thing for remote variables and functions, a quick web search using your post use case ‘powershell local function remote’ would provide lots of articles and examples.

http://duffney.io/RunLocalFunctionsRemotely https://mikefrobbins.com/2014/03/27/run-a-local-powershell-function-against-a-remote-computer-with-powershell-remoting

See the help files on scope.

# get function / cmdlet details
(Get-Command -Name About_Scope).Parameters
Get-help -Name About_Scope -Full
Get-help -Name About_Scope -Online
Get-help -Name About_Scope -Examples

Specifically …

Example 5: Using a Local Variable in a Remote Command
   To indicate that a variable in a remote command was created in the 
   local session, use the Using scope modifier. By default, Windows
   PowerShell assumes that the variables in remote commands were created
   in the remote session.

   The syntax is:
       $Using:&lt;VariableName&gt;       

   For example, the following commands create a $Cred variable in the
   local session and then use the $Cred variable in a remote command: 
$Cred = Get-Credential
Invoke-Command $s {Remove-Item .\Test*.ps1 -Credential $Using:Cred}
The Using scope was introduced in Windows PowerShell 3.0.

In Windows PowerShell 2.0, to indicate that a variable was created in
the local session, use the following command format.

$Cred = Get-Credential
Invoke-Command $s {param($c) Remove-Item .\Test*.ps1 -Credential $c} -ArgumentList $Cred 

Thank you all for your help and suggestions. I will try all of them out and see if I have better success.

I Googled and found a number of suggestions, yet like I said in my post, it simply was not working for me. Not sure if I was missing something or overlooking something.

I will post an update once I try what was suggested and if I find what I may have been doing wrong.