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

PowerShell: Restore SQL Database from Full and/or Differential Backups

$databaseName='BALOO_MSCRM' $newDatabaseName='BALOO_MSCRM' $dbData='mscrm' # set this value to $null for autogen defaults $dbLog='mscrm_log' # set…

PowerShell: Get Terminal Service (Remote Desktop Service) Licenses Report

# rdsLicenseReport.ps1 $knownRdsComputers=$null # Options: (a) 'SERVER1','SERVER100' (b) Get-Content Path\To\RDServers.txt function getTsLicenses{ param( $knownRdsComputers, $domain=$env:userdnsdomain…

PowerShell: Update Local Windows Using COM Objects – Legacy Compatible

Although this function requires 'interactive' or console sessions, it can be trigged by Windows Scheduled…