0

I have a folder with multiple PDFs I need to print to different printers. I've created variables for each shared printer and depending on the first 2 letters of the PDF the printing will go to the matching printer.

I'm having trouble concatenating 2 strings to form an existing variable to use it later in the printing call.

This is what I have now (all PDFs in the dir starts with 01 for now):

# SumatraPDF path
$SumatraExe = "C:\Users\Administrador.WIN-FPFTEJASDVR\AppData\Local\SumatraPDF\SumatraPDF.exe"
# PDFs to print path
$PDF = "C:\Program Files (x86)\CarrascocreditosPrueba2\CarrascocreditosPrueba2\DTE\BOL"

# Shared printers list
$01 = '\\192.168.1.70\epson'
$02 = '\\192.168.1.113\EPSON1050'

cd $PDF

While ($true) {
    Get-ChildItem | Where {!$_.PsIsContainer} | Select-Object Name | %{
    $Boleta = $_.Name
    $CodSucursal = $Boleta.Substring(0,2)
    $CodImpresora = '$' + $CodSucursal
    Write-Host $CodImpresora -> This shows literal $01 on PS ISE
    Write-Host $01 -> This show the shared printer path
    }
    Start-Sleep -Seconds 5
}

# Actual PDF printing...
#& $SumatraExe -print-to $CodImpresora $PDF

So basically I need to call an existing variable based on 2 strings. Probably this could be achieved with a Switch but that will be too extensive.

1 Answer 1

1

concatenating 2 strings to form an existing variable

That won't work in PowerShell, variable tokens are always treated literally.

I'd suggest you use a hashtable instead:

# Shared printers table
$Impresoras = @{
  '01' = '\\192.168.1.70\epson'
  '02' = '\\192.168.1.113\EPSON1050'
}

Then inside the loop:

$Boleta = $_.Name
$CodSucursal = $Boleta.Substring(0,2)
$Impresora = $Impresoras[$CodSucursal]

Although the language syntax don't support variable variable names, you can resolve variables by name using either the Get-Variable cmdlet:

# Returns a PSVariable object describing the variable $01
Get-Variable '01' 

# Returns the raw value currently assigned to $01
Get-Variable '01' -ValueOnly

... or by querying the Variable: PSDrive:

# Same effect as `Get-Variable 01`
Get-Item Variable:\01

While these alternatives exist, I'd strongly suggest staying clear of using them in scripts - they're slow, makes the code more complicated to read, and I don't think I've ever encountered a situation in which using a hashtable or an array wasn't ultimately easier :)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.