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
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow thank you very much for the fast information. Do you have any source for this information? On google I only found $variablename[$i]
@julianbechtold this isn't to do with variables as such, this is to do with using variables inside strings, take a look here you might find some of the info useful.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.