Gazel
Gazel

Reputation: 265

How to use Powershell global variable inside CMD.EXE statement

I'm trying to automate printer installation using powershell with imbedded CMD.exe code. To optimize the code and reduce the amount of typing, I use global variables, which works fine with powershell code. However, as soon as it hits the embedded CMD.exe code with its single and double quotation marks, the global variables are not recognized anymore. I tried using single or double quotation marks, but still no luck. The problematic parameter is at Line #21, switch /r . Any ideas on how to fix it?

Note: This code is for Powershell_v2.

$h = get-content env:computername 
$global:portIP1 = "printer01"
$global:portIP2 = "printer02"


  if ($h -match 'nhi') {$global:portIP1 
$portNumber = "9100"  
$computer = $env:COMPUTERNAME 

$wmi= [wmiclass]"\\$computer\root\cimv2:win32_tcpipPrinterPort" 
#$wmi.psbase.scope.options.enablePrivileges = $true 
$newPort = $wmi.createInstance() 

$newPort.hostAddress = $global:portIP1 
$newPort.name = $global:portIP1 
$newPort.portNumber = $portNumber 
$newPort.SNMPEnabled = $True 
$newPort.Protocol = 1 
$newPort.put()

CMD /C 'printui.exe /if /b "PrinterB&W1" /f "C:\inetpub\ftproot\Prdrivers\HP Universal Print Driver\hpcu155u.inf_amd64_neutral_bcdaf832a18b6add/hpcu155u.inf" /r '$global:portIP1' /m "HP Universal Printing PCL 6"'
CMD /C 'printui.exe/y /n"PrinterB&W1', (Write-Host "match found")}

Upvotes: 1

Views: 1974

Answers (1)

mjolinor
mjolinor

Reputation: 68273

I'd use an expandable (double-quoted) here-string. Then you can put whatever kind of quotes you want, whereever you want them and they'll get parsed as literal text:

  $global:portIP1 = "printer01"
  $global:portIP2 = "printer02"

$command = @"
'printui.exe /if /b "PrinterB&W1" /f "C:\inetpub\ftproot\Prdrivers\HP Universal Print Driver\hpcu155u.inf_amd64_neutral_bcdaf832a18b6add/hpcu155u.inf" /r '$global:portIP1' /m "HP Universal Printing PCL 6"'
"@
CMD /C $command

The opening @" can be in any position, but the closing "@ must start in position 1 on the line.

See Get-Help about_quoting_rules for more information about here-strings.

Upvotes: 3

Related Questions