3

I am trying to create a PowerShelll script, that first checks on a list of printers if they are already mapped. If a printer of the list is not mapped it will map the printer.

Checking for a printer alone is working fine. When I created an array and a for loop it stopped working since the printer names are wrong.

It seems that I fail to access the single items of the array.

This is my current code snippet:

[string[]] $printernames = "Buero Drucker","hase"
for($i = 0; $i -lt $printernames.Length; $i++)
{
    $printerexists = [Boolean](Get-WmiObject win32_printer -Filter "Name = $printernames[$i]")
    Write-Host "Printer $printernames[$i] exists: $printerexists"
}

Now when calling $printernames[0], I would expect to get the following:

"Buero Drucker"

Instead I receive the following:

"Buero Drucker hase[0]"

It seems like the variable is not truly an array but I cannot tell why.

===== edit =====

The for-loop works fine and iterates 2 times. Therefore I expect the array creation to be correct but the accessing of the variable to be wrong

I checked the variable $i already. The Console output is the following:

Printer Buero Drucker hase[0] exists:  False
Printer Buero Drucker hase[1] exists:  False
Clijsters
  • 4,031
  • 1
  • 27
  • 37
julian bechtold
  • 1,875
  • 2
  • 19
  • 49

1 Answers1

2

Expanding variables in brackets is a bit annoying, you'd run into the same problem trying

$Var = "Something"
"$Var.Property"

it will return "Something.Property"

you want to use this :

 "Name = $($printernames[$i])"

Wrap anything you need to expand inside $() and it will work as expected, currently powershell only matches up to the end of a var name, and ignores any . or [ etc.

colsw
  • 3,216
  • 1
  • 14
  • 28
  • Wow thank you very much for the fast information. Do you have any source for this information? On google I only found $variablename[$i] – julian bechtold Dec 27 '17 at 09:58
  • @julianbechtold this isn't to do with variables as such, this is to do with using variables inside strings, take a look [here](https://kevinmarquette.github.io/2017-01-13-powershell-variable-substitution-in-strings/) you might find some of the info useful. – colsw Dec 27 '17 at 10:16
  • Just to be clear $printernames[$i] is an ***expression*** not a variable. So the $()'s performs what is sometimes calle *expression squeezing* and causes the expression to be evaluated inside the ()'s then expanded as a variable. – EBGreen Dec 27 '17 at 13:52