Using Local Functions in a Scriptblock with Existing Code
When you are wanting to run code remotely, it’s common to do this via the use of Invoke-Command (though other options exist, such as through Start-Job for example). The biggest downfall to date i’ve found with remoting is the lack of an option to combine the use of your local functions within a ScriptBlock that has other code in it. As an example, the following is not possible:
function Add ($param1, $param2) { $param1 + $param2 } function Multiply($param1,$param2) { $param1 * $param2 } Invoke-Command -ComputerName $env:COMPUTERNAME -ScriptBlock { $addResult = Add $args[0] $args[1] $multiplyResult = Multiply $args[0] $args[1] Write-Output "The result of the addition was : $addResult" Write-Output "The result of the multiplication was : $multiplyResult" } -ArgumentList 3, 2 However, there is a way to achieve this type of operation, and make as many local functions as you want available to be used and combined with other code in your ScriptBlock. You can find the full article at powershell.amsterdam.
Related Articles
ICYMI: PowerShell Week of 02-April-2021
Topics include help sections, Approved Verbs, Identity Management and more…
ICYMI: PowerShell Week of 22-November-2019
Topics include Group-Object, Power Platform, Preview 6 and more.
The Ternary Cometh
Developers are likely to be familiar with ternary conditional operators as they’re legal in many languages (Ruby, Python, C++, etc). They’re also often used in coding interviews to test an applicant as they can be a familiar source of code errors. While some developers couldn’t care less about ternary operators, there’s been a cult following waiting for them to show up in Powershell. That day is almost upon us. Any Powershell developer can easily be forgiven for scratching their heads and wondering what a ternary is.