1

I created this script to create multiple VM's remotely on the Hyper-V server, however, it doesn't seem to create the VM's. I can create one directly on the Hyper-V server using the given parameters while using Enter-PSSession, but not via invoke-command? (there are no error messages, it just prints a blank line and goes back to the prompt)

[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][int]$newvmcount #require number of temp vm's to create
)
Invoke-Command -ScriptBlock {foreach ($vmnumber in $newvmcount){New-VM -Name "Windows10TMP$vmnumber" -BootDevice NetworkAdapter -Generation 2 -SwitchName LAN -MemoryStartupBytes 1gb -NewVHDPath "F:\hypervvirtualmachines\Windows10TMP$vmnumber.vhdx" -NewVHDSizeBytes 127gb -verbose}} -ComputerName hypervserver -ArgumentList $newvmcount
Davidw
  • 1,222
  • 3
  • 14
  • 25
  • try passing $newvmcount into the invoke with the arguments parameter. Inside the script block you'll need a new param declaration as well. seems redundant i know but it's how it works. If that works I'll type up a formal answer. – Colyn1337 Nov 29 '18 at 23:37

2 Answers2

3

You can apply the $using scope modifier. It would look like this$using:newvmcount which let's you use the variable defined outside of the invoke-command

SteamerJ
  • 403
  • 2
  • 7
2

Apply How to pass arguments for remote commands:

Either declare the parameter(s) at the beginning of your scriptblock:

Invoke-Command -ScriptBlock {
  param($newvmcount)
  foreach ($vmnumber in $newvmcount) {
      New-VM -Name "Windows10TMP$vmnumber" `
        -BootDevice NetworkAdapter -Generation 2 `
        -SwitchName LAN -MemoryStartupBytes 1gb `
        -NewVHDPath "F:\hypervvirtualmachines\Windows10TMP$vmnumber.vhdx" `
        -NewVHDSizeBytes 127gb -verbose
  }
} -ComputerName hypervserver -ArgumentList $newvmcount

or access argument(s) using the automatic variable $args.

BTW, I can't understand the foreach loop as [int]$newvmcount does not seem to be a collection…

JosefZ
  • 1,564
  • 1
  • 10
  • 18
  • 1
    dude... as you can see I'm already waiting for feedback from OP as to if this is the solution. – Colyn1337 Nov 29 '18 at 23:51
  • I changed the loop to a for loop, based on your feedback about the loop, however, I went with SteamerJ's solution, as it was a bit simpler, and I believe I've used "$using:" in the past. – Davidw Nov 30 '18 at 07:26
  • 1
    both solutions work, it just depends on what you like. @JosefZ solution is a bit more readable in terms of you understand where the scope is coming from, whereas $using requires understanding of how that scope modifier works which someone not familiar with powershell will have to infer from it 'just working.' I was in this same situation literally a few days ago when I learned about this. I had trouble with this method and ended up learning about $using. – SteamerJ Nov 30 '18 at 13:56