Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and accessing an array value in Powershell [duplicate]

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
like image 670
julian bechtold Avatar asked Aug 17 '26 08:08

julian bechtold


1 Answers

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.

like image 50
colsw Avatar answered Aug 20 '26 01:08

colsw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!