Posted On March 29, 2019

PowerShell: Passing Local Functions to Remote WinRM Sessions

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Passing Local Functions to Remote WinRM Sessions
# Dynamic Credential Method 1
$who = whoami
	if ($who.substring($who.length-2, 2) -eq "-a"){$username=$who;}
    else {$username=$who+"-admin";}
#$password = Read-Host -Prompt "Input the password for account $username" -AsSecureString
$password=convertto-securestring "PASSWORD" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password	#To be Invoked with switch -Credential
$elevate = New-PSSession -ComputerName localhost -Credential $cred	#$To be Invoked with switch -Session

# Local function
function localFunc ($x, $y)
{
    ping google.com
}

Invoke-Command -Session $elevate -ScriptBlock { 
    param( $x, $y, $importedFunc)

    # Import the function from the variable inside parameters
    [ScriptBlock]::Create($importedFunc).Invoke($x,$y)

} -ArgumentList $xVariable, $yVariable, ${function:localFunc}

Leave a Reply

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

Related Post

PowerShell: Windows Session Memory Usage Watcher

# windowsSessionWatcher.ps1 $serverNames=@( 'IRV-RDS01.domain1.net', 'LAX-RDS02.domain2.com ) $thresholdMemoryUsagePercent=30 $thresholdMemoryGb=20 $domainCreds=@( @{domain='domain1.ad';username='domain1\sysadmin';password=$env:pass1} @{domain='domain2.com';username='domain2\sysadmin';password=$env:pass2} ) # Email relay…

PowerShell: Move Files Into Zip

# moveFilesToZip.ps1 # Version 0.02 # This little function is to automate the process of…

Manual Sync for Office 365 Azure-AD Integration

1. Perform Prerequisites:* a. Install Dot Net Framework 4.5 )* b. Install Windows Management Framework…