I would like to run a few lines of code on a remote machine, so I have to use the "Invoke-command" cmdlet to achieve that. The script I want to run is rather long (not just a simple command, but a few loops, conditionals, etc.), so it is not possible to just copy the codes in-line. So can anyone teach me the syntax for doing that?
for example: I have the following code:
Function createDict(){
$Dict = @{}
$Variables = Get-Content .\Variables.ini.
foreach ($str in $Variables){
if ($str -eq ""){
continue
}
if ($str.StartsWith("[") -or $str.StartsWith("#")){
continue
} else {
$Pair = $str.Split('=')
$Dict.Add($Pair[0], $Pair[1])
}
}
return $Dict
}
Import-Module virtualmachinemanager
stop-VM NHQA-W8-64b-Q13
start-VM NHQA-W8-64b-Q13
You dont need to try to understand the above code, I just want to show you what kind of things that I am trying to execute on the remote machine here. Thank you very much in advance!
You have a couple of options, probably more:
Make your functions/cmdlets available as a script and dot-source them on the remote session:
. \\path\to\cmdlets.ps1
Another option you have is that a script block in PowerShell is an object, and as such can be assigned to a variable and re-used that way. Consider the following trivial example:
$files = { -not $_.PSIsContainer }
$folders = { $_.PSIsContainer }
dir | ? $files
dir | ? $folders
I hope these ideas help. I am sorry I don't have a more direct answer. Maybe if you could provide some examples of what you have tried and what errors you are experiencing it would help to give a more direct, better answer.