Powershell Using Scope Modifier In Invoke-Command For a VM

I'm trying to pass the value of the variable $DNSClientServerAddr inside an Invoke-Command -VMName. My option is the 'using' scope modifier. I can't seem to pass its value:

[int]$NumberOfVMs = Read-Host "NUMBER OF VMs TO BE CONFIGURED"
$VMName = Read-Host "VM NAME PREFIX                "
[int]$VMNameSuffix = Read-Host "STARTING NUMBER               "
$DNSClientServerAddr = Read-Host "DNS CLIENT SERVER IP ADDRESS  "
For ($Count = 1; $Count -le $NumberOfVMs; $Count++, $VMNameSuffix++) {
    $VMNameFull = "$VMName" + "$VMNameSuffix"
    Invoke-Command -VMName $VMNameFull -ScriptBlock {
        $Using:DNSClientServerAddr
        Write-Host $DNSClientServerAddr }
}

What I get is always blank when I test to see in Write-Host $DNSClientServerAddr. Does 'using' work with Invoke-Command to a VM in a code as straightforward as this? Or do I really have to use New-PSSession and -ArgumentList? Also, should Hyper-V be active/installed in the VMs that I'm supposed to configure?

By the way, I'm using Powershell version 5.1.

Thank you!

Upvotes: 0

Views: 156

Answers (1)

Sage Pourpre
Sage Pourpre

Reputation: 10323

$DNSClientServerAddr is not defined in your remote session. You can use a local variable through $Using directly like this:

Invoke-Command -VMName $VMNameFull -ScriptBlock {
    Write-Host $Using:DNSClientServerAddr
}

You could also assign the variable so it become native to the remote session and discard the need of using the $using scope modifier but you still have to do an initial assignment.

Invoke-Command -VMName $VMNameFull -ScriptBlock {
    $DNSClientServerAddr = $Using:DNSClientServerAddr
    Write-Host $DNSClientServerAddr
}

References

About_remote_variables

About_Using

About_scopes

Upvotes: 0

Related Questions