Escapaing double-quotes problem in mixed batch/powershell script running
-
27-09-2019 - |
Question
Here's what I'm trying to do:
@ECHO OFF
CALL powershell -ExecutionPolicy RemoteSigned -Command "$sh = new-object -com 'Shell.Application'; $sh.ShellExecute('powershell', '-NoExit -Command "$path = """HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}""";echo $path"', '', 'runas')"
PAUSE
Basically, I want to have a batch file that I can double-click, which will run a powershell script that calls another powershell script but asks for admin privileges and runs that command as admin.
I'm having problems though, with the double-quotes I think... I've tried many things but can't seem to fix it, here's the powershell error message:
Bad numeric constant: 4D.
At line:1 char:57
+ $path = HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D <<<< 36E972-E325-11C
E-BFC1-08002BE10318};echo $path
+ CategoryInfo : ParserError: (4D:String) [], ParentContainsError
RecordException
+ FullyQualifiedErrorId : BadNumericConstant
PS C:\Windows\system32>
Solution
I would use the built-in command Start-Process rather than creating a shell object e.g.:
CALL powershell -ExecutionPolicy RemoteSigned -NoProfile -Command "& {Start-Process PowerShell -Verb runas -Arg '-NoExit -Command & {$path=''foo'';$path}'}"
For anything of significance the quoting is going to be annoying. Can you put the final script in a file and execute the script file using the -File parameter on PowerShell.exe?
OTHER TIPS
I solved it, here's the long batch one-liner for my real problem, so people can see a real example:
CALL powershell -ExecutionPolicy RemoteSigned -Command "$sh = new-object -com 'Shell.Application'; $sh.ShellExecute('powershell', '-NoExit -Command ""$path = ''HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}''; Get-Childitem $path -ErrorAction SilentlyContinue | Where { (Get-ItemProperty $_.PSPath DriverDesc) -Match ''VMnet'' } | Foreach { New-ItemProperty -ErrorAction SilentlyContinue $_.PSPath -Name ''*NdisDeviceType'' -Value ''1'' -PropertyType DWord }; netsh interface set interface name=''VMware Network Adapter VMnet1'' admin=DISABLED; netsh interface set interface name=''VMware Network Adapter VMnet1'' admin=ENABLED; netsh interface set interface name=''VMware Network Adapter VMnet8'' admin=DISABLED; netsh interface set interface name=''VMware Network Adapter VMnet8'' admin=ENABLED""', '', 'runas')"
P.S: In case anyone's wondering what it's for... I run this every time I install/update VMware Workstation to hide the virtual network adapters from appearing on the Network and Sharing Center in Windows Vista/7.