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: Impersonation to Download Files Through Proxy

Initial Script to without impersonation # Change these values to reflect your desired downloads[string]$fileSource =…

Changing SMB Caching on Windows

# To turn OFF caching $rolesWithNoCaching="SHERVER01","SHERVER02" $rolesWithNoCaching | %{$shares=Get-SMBShare -scopename "$_"; foreach ($share in $shares){if(!($share.Name…

PowerShell: Grant Domain Admins Access to Directories

Snippet: # Messing around$shareDrives=@("E","F","G","I","J","N",'O','Q','R','S','T','U','V','W','Z','Y');$subdomain=(net config workstation) -match 'Workstation domain\s+\S+$' -replace '.+?(\S+)$','$1';$domainadmins="$subdomain`\Domain Admins"; $shareDrives | %{"Add-NTFSAccess…