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

Using Python to Automate Video Playing on Ubuntu

This little snippet was generated using ChatGPT with more than a little bit of prompting…

PowerShell: Overcome Issues with Error 13932 in SCVMM When Refreshing Virtual Machines

Dealing with Clusters # refreshCluster.ps1 # Function to refresh a cluster in VMM in anticipation…

PowerShell: Run PowerShell As Another User

# Set credential $adminUsername='domain\adminDude' $adminPassword='whatpassword?' $GLOBAL:adminCredential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminUsername,$(ConvertTo-securestring $adminPassword -AsPlainText -Force) # Test…