please help me write the below function better.
Context: This script/function lives on my local machine. I want to pass variables to the function, then pass them into an invoke-command script block to be run on a remote machine.
This code works, but i don’t feel like its good practice, or the best way of doing it, as i have to pass my params around multiple times, and it all just feels a bit clunky…
In addition i would like to get results back from the remote machine, so that i can run additional commands back in my local session, but using variables created from the remote session. I know i can do something like $results = invoke-command, but is that the best, and will that work when its already inside another function…
function Create-NewVM
{
param($param1, $param2, $param3, $param4)
$ScriptBlock =
{
param ($param1, $param2, $param3, $param4)
# do a bunch of stuff on my remote machine
$var = xyz
$htmlBlock = @"
Whether i do $var or $($var) here, either way, when i try to expand it later, it is empty. What am i doing wrong?
"@
# I try to now expand $htmlBlock in a Send-MailMessage command, but $var is blank, empty.. ??
Send-Mail-Message -body $htmlBlock...
}
$s = New-PSSession hypervhost.fqdn
Invoke-Command -Session $s -ScriptBlock $ScriptBlock -ArgumentList $param1, $param2, $param3, $param4
}
Create-NewVM -computername "vm01" $param1 $param2 $param3 $param4
I know there are a few issues i have raised here, so please feel free to ignore some, i mainly want to see if there is a better structure/method/layout to writing this as a whole. If you can answer the knitty gritty details about $htmlBlock and returning variables back to my local session, that is just a bonus, however i can work that out myself later, once i get the main design of the code looking better.
thank you for any of your help.