I have a question for you that is not about specific code or problem but rather about code design.
Specifically about code which must work for local computer as well as remote computer.
Here is an example template code:
function Invoke-Process
{
Param (
[Parameter(Mandatory = $true)]
[string] $Path,
[Parameter(ParameterSetName = "Domain")]
[string] $Domain,
[Parameter(ParameterSetName = "Domain")]
[PSCredential] $Credential,
[Parameter(ParameterSetName = "Session")]
[System.Management.Automation.Runspaces.PSSession] $Session,
)
# Initialize session to either localhost or remote host
$SessionParams = @{}
if ($PSCmdlet.ParameterSetName -eq "Session")
{
$SessionParams.Session = $Session
}
else
{
# ensures using loopback for localhost
if ($Domain -ne [System.Environment]::MachineName)
{
$SessionParams.ComputerName = $Domain
if ($Credential)
{
$SessionParams.Credential = $Credential
}
}
# else $SessionParams is blank which means Invoke-Commands runs against local computer
}
# This will work in all scenarios, regardless if local host or remote
Invoke-Command @SessionParams -ScriptBlock {
# Here goes lengthy code only once...
}
}
A problem I have with this template code is that when this function runs on localhost it will use loopback interface, which means additional performance overhead.
For example if the “lengthy code” portion is put outside Invoke-Command
for localhost then no loopback would be used, however this would result in code bloat:
if ($localhost)
{
# Not using Invoke-Command
# here goes lengthy code
}
else
{
Invoke-Command @SessionParams -ScriptBlock {
# Here goes lengthy code yet again...
}
}
Surely there must be a clean solution which would guarantee all 3 conditions:
- No code bloat
- No
Invoke-Command
for localhost - function works for both localhost and remote host.
What are your suggestions, how would you design such function?
EDIT:
I didn’t say but there are some other potential issues with single Invoke-Command
such as not being able to use $using:Variable
since using
is valid only in remote contexts, it would stop working when the function runs locally.