PowerShell: Excute Function Remotely

$computername=$env:computerName
$adminUsername='doeMainAdmin'
$adminPassword='frackingPassword'
$adminCredential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminUsername,$(ConvertTo-securestring $adminPassword -AsPlainText -Force)

function execFunctionRemotely{
    param(
        [Parameter(Mandatory=$true)][string]$computerName,
        [Parameter(Mandatory=$true)][string]$functionName,
        [Parameter(Mandatory=$False)][string[]]$parameters=@(),
        [Parameter(Mandatory=$False)]$credential
    )
    $ErrorActionPreference = "Stop"
    #$scriptBlock=${function:$functionName} # another method to retrieve the inside codes of a provided function
    $scriptBlock=(Get-Command $functionName -CommandType Function).Definition;        
    try{
        if($credential){$session=new-pssession -ComputerName $computername -Credential $credential}
        else{$session=new-pssession -ComputerName $computername}
        write-host "connected to $computername"
        }
    catch{
        write-warning "Unable to connect to remote server.";
        return $false
        }
    
    if ($session){
        write-host 'Please wait while the program executes $functionName on $computerName...'
        $result=invoke-command -Session $session -ScriptBlock{
            param ($importedFunction,$params)
                return [ScriptBlock]::Create($importedFunction).invoke($params);
            } -args $scriptBlock,$parameters
        Remove-PSSession $session
        return $result
        }
}

# Test function: get tracert information
function getTraceRoutes([string[]]$name=('gmail.com','office365.com')){
    $name|%{pathPing $_}
}
execFunctionRemotely $computername getTraceRoutes

Leave a Reply

Your email address will not be published. Required fields are marked *