Search code examples
powershell

Escaping quotes inside nested powershell calls


Goal: run a single command from cmd to create a ramdisk using imdisk

Details: I have found that creating a ramdisk with imdisk requires admin privileges and the best way that I have found to open an elevated privilege window from inside cmd and then execute an imdisk command is to use powershell. I'm a powershell and python novice and am having a lot of trouble with the syntax for a command that uses nested python and powershell and has several spaces and double quotes and forward- and back-slashes. The command I want to execute is imdisk -a -s 16G -m X:\ -p "/fs:ntfs /q /y" and so far what I have come up with based on other answers (How do I run a PowerShell script as administrator using a shortcut? and https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.4) is this

powershell -Command "& {Start-Process powershell -Verb RunAs -ArgumentList \"-ExecutionPolicy Bypass -NoExit -Command imdisk -a -s 16G -m X:\ -p "/fs:ntfs /q /y"\"}"

I know there needs to be some kind of quote around the imdisk command to keep it all together, but every time I try some amount of `" or \" or \`" around it I get an error that I'm missing a terminator " somewhere. I think maybe wrapping the imdisk command in another "& {}" after the second -Command? Again, I struggle with all the quotes and escaping marks.

Can someone help me get this syntax right?


Solution

  • I suspect there are easier ways to solve this avoiding some indirection.

    However, I'm answering the question as stated because I've been in nested escaping hell a few times before.

    dos command:

    imdisk -a -s 16G -m X: -p "/fs:ntfs /q /y"
    

    powershell invoking powershell:

    Start-Process powershell -Verb RunAs -ArgumentList "-ExecutionPolicy Bypass -Command imdisk -a -s 16G -m X: -p `"/fs:ntfs /q /y`""
    

    dos command invoking powershell (invoking powershell):

    powershell -Command "& {Start-Process powershell -Verb RunAs -ArgumentList \"-ExecutionPolicy Bypass -Command imdisk -a -s 16G -m X: -p \`\"/fs:ntfs /q /y\`\" \"}"
    

    So when escaping the dos command into powershell, you have to use backtick ` to escape double quotes within the powershell string.

    Then, when escaping the whole thing for cmd.exe again, you need to escape the backtick and double quote with \.

    In a humourous meta twist, I had to search how to put a backtick in a code block while writing this.