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

Basic CSS: Use Clockwise Notation to Specify the Margin of an Element

<style>.injected-text {margin-bottom: -25px;text-align: center;}.box {border-style: solid;border-color: black;border-width: 5px;text-align: center;}.yellow-box {background-color: yellow;padding: 20px 40px 20px 40px;}.red-box…

Common JavaScript Techniques

Common JavaScript Techniques:1. Demonstate your understanding of they keyword typeofconsole.log(typeof typeof 1);// this follows the…

Listing SMB Shares on a Windows Machine

Option 1: PS C:\Windows\system32> get-WmiObject -class Win32_Share Name Path Description ---- ---- ----------- ADMIN$ C:\Windows…