Posted On December 27, 2019

PowerShell: Nesting Functions Inside Functions

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Nesting Functions Inside Functions

Demo 1: calling a function from within another function

function A{
Param($functionToCall)
Write-Host "Calling function: $functionToCall"

# Obtain the scripts from the externally parsed function
$script=(Get-Item "function:$functionToCall").ScriptBlock

# invoking external function
[ScriptBlock]::Create($script).Invoke();

}

function B{
Write-Host "Function B has been invoked"
}

A -functionToCall B

Sample Out

PS C:\Users\JustinBieber> A -functionToCall B
Calling function: B
Function B has been invoked

Demo 2: Passing function into another function, then invoke on a remote target as a Job (to enable simultaneous executions)

function pingDomain{
ping google.com;
}

function startJobOnRemoteComputer{
param(
$remoteComputer,
$functionToCall
)

Write-Host "Executing $functionToCall on $remoteComputer";
$script=(Get-Item "function:$functionToCall").Definition

do{
$session = New-PSSession -ComputerName $remoteComputer
write-host "Connecting to remote computer $remoteComputer..."
sleep -seconds 1
if ($session){write-host "Connected."}
} until ($session.state -match "Opened")

$job=invoke-command -Session $session -AsJob -ScriptBlock{
param($functionToCall);
[ScriptBlock]::Create($functionToCall).Invoke();
} -args $script

write-host "$($job.Name) has been initiated on $remoteComputer"
return $job;
}

$job=startJobOnRemoteComputer -remoteComputer "SHERVER009" -functionToCall pingDomain

Receive-Job -Id -job.Id;

Leave a Reply

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

Related Post

PowerShell: Search for Hyper-V Guest VM That Has Not Been Registered In Cluster

# findVmHost.ps1 $vmName='TESTVM01' function findVmHost($vmName){ try{ Import-Module Hyper-V Import-Module FailoverClusters $allHyperVHosts={(Get-ClusterNode | Where { $_.State…

PowerShell: Set VM Dynamic Memory in Virtual Machine Manager

# setVmDynamicMemoryInVmm.ps1 # Optimize Dynamic RAM $minGb='16GB' $maxGb='32GB' $startupGb='2GB' $buffer=20 $memoryWeight=5000 $forcedRestart=$false $vmmServer='localhost' function getUnoptimizedMemoryVms{…

PowerShell: Get SQL Job History

$computername='sql01' function getSqlJobHistory($sqlServerName){ try{ if(!(get-module SqlServer)){ Install-Module -Name SqlServer } Import-Module -Name SqlServer $sqlServerInstance=Get-SqlInstance -ServerInstance…