Search code examples
powershelluser-interfacesearchlistboxnetwork-printers

Running an IF when variable begins with PR


I'm on my first steps with Powershell and I'd like to go into it more.

I'm writing a script that allows the user to connect a network printer to their PC by choosing it from a ListBox.

I have two types of printers. PR stands for printer and SC stands for scanner.

When choosing a PR device, it shows a specific window. Unfortunately the script doesn't understand that by PR* I mean all printers starting with these two letters.

This is my code:

$x = $listBox.SelectedItem
if ($x -eq "PR*"){
    $windowDR.ShowDialog()}

I appreciate every type of help!


Solution

  • You need to use the -like operator to do what you seek.

    $x = $listBox.SelectedItem
    if ($x -like "PR*"){
        $windowDR.ShowDialog()}
    

    Matching Operators

    The like operators (-like and -notlike) find elements that match or do not match a specified pattern using wildcard expressions.

    The syntax is:

    <string[]> -like <wildcard-expression>
    <string[]> -notlike <wildcard-expression>
    

    ...

    -like

    Description: Match using the wildcard character (*).

    Reference: MSDocs - About Comparison operators