Posted On June 15, 2020

PowerShell: Excute Function Remotely

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

JavaScript: Wikipedia Viewer

Demo: Wikipedia Viewer HTML Code: <body><div class="container"> <h1>Wikipedia Search</h1> <p>A Free Code Camp Intermediate Project</p><br/>…

Kubernetes: Cert-Manager x509 ECDSA verification failure

Symptoms Error from server (InternalError): error when creating "kimconnect-cert.yaml": Internal error occurred: failed calling webhook…

PowerShell: Audit Failed Logins of A User

$username='rambo' function auditLockouts($userName,$domainController,$refreshMinutes=1){ function getLockouts($domainControler){ # Requirement: # Domain Controllers Audit Group Policy has been…