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

} -ArgumentList $xVariable, $yVariable, ${function:localFunc}
Posted on Categories Codes

Leave a Reply

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