[英]Concatenate two strings to form an existing variable
I have a folder with multiple PDFs I need to print to different printers.我有一个包含多个 PDF 的文件夹,我需要打印到不同的打印机。 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.我为每台共享打印机创建了变量,并且根据 PDF 的前 2 个字母,打印将 go 打印到匹配的打印机。
I'm having trouble concatenating 2 strings to form an existing variable to use it later in the printing call.我在连接 2 个字符串以形成现有变量以便稍后在打印调用中使用它时遇到问题。
This is what I have now (all PDFs in the dir starts with 01 for now):这就是我现在所拥有的(目录中的所有 PDF 都以 01 开头):
# 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.所以基本上我需要调用一个基于 2 个字符串的现有变量。 Probably this could be achieved with a Switch but that will be too extensive.可能这可以通过 Switch 实现,但这将过于广泛。
concatenating 2 strings to form an existing variable连接 2 个字符串以形成现有变量
That won't work in PowerShell, variable tokens are always treated literally.这在 PowerShell 中不起作用,变量标记总是按字面意思处理。
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:尽管语言语法不支持变量变量名称,但您可以使用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: ...或通过查询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:)虽然存在这些替代方案,但我强烈建议不要在脚本中使用它们 - 它们速度慢,使代码更难以阅读,而且我认为我从未遇到过使用哈希表或数组最终并不容易:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.