1

I am trying to cat a text file containing a PowerShell script from a .bat file into PowerShell running within the command line.

It's kind of a workaround to start a PowerShell script on startup without having permission on the system.

It works perfectly fine until I try paths with spaces. Does someone know how to make this work?

I searched and tried many solutions (see 3,4,5,6) but either this is a very specific case, or I am doing something wrong. My knowledge of scripts in general is lacking some, but I'm trying my best. Please use simple language in your answer.

  1. This works

    @echo off
    powershell "cat -raw C:\examplenospace\test.txt | invoke-expression"
    
  2. This works

    @echo off
    set "file=C:\examplenospace\test.txt"
    powershell "cat -raw %file% | invoke-expression"
    
  3. Not working

    @echo off
    set "file=C:\example with space\test.txt"
    powershell "cat -raw %file% | invoke-expression"
    
  4. This also doesn't work of course

    @echo off
    powershell "cat -raw "C:\example with space\test.txt" | invoke-expression"
    
  5. Also doesn't work

    @echo off
    powershell ""cat -raw "C:\example with space\test.txt" | invoke-expression"
    
  6. I tried many variations, nothing seems to work

    @echo off
    powershell "cat -raw \"\"C:\example with space\test.txt" | invoke-expression"
    

How can I make it work?

TommyMaes
  • 33
  • 5
  • 1
    Or...```@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath 'C:\example with space\test.txt' -Raw | Invoke-Expression"``` or even ```@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath \"C:\example with space\test.txt\" -Raw | Invoke-Expression"``` – Compo Dec 19 '22 at 12:19
  • Maybe it's time to go all powershell, without invoke-expression. – js2010 Dec 19 '22 at 13:10
  • 1
    Please, please read the following post (last one). I would read it again too - seriously. This will help you - I will guarantee it. https://stackoverflow.com/a/180749/175063 – Leptonator Dec 19 '22 at 15:07
  • 1
    `powershell "cat -raw '%file%' | invoke-expression"` or `powershell "cat -raw """"%file%"""" | invoke-expression"` – JosefZ Dec 19 '22 at 15:19
  • Thank you all for your answers, not all your answers worked for me (only Compo's did) but i learned new things from all of your comments! – TommyMaes Dec 19 '22 at 20:50

1 Answers1

0

@Compo thank your for your answer, this worked straight away, both of them!

@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath 'C:\example with space\test.txt' -Raw | Invoke-Expression"

@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath "C:\example with space\test.txt" -Raw | Invoke-Expression"

TommyMaes
  • 33
  • 5