2

I have a Powershell Gui that populates all PS1 files in a specific folder. This GUI is intended for a easy way to execute any one of those scripts in their own PS window.

Here is my issue.

Test.ps1

write-host "Hello World"
pause 

Script that works:

start powershell {& "c:\build\Test.ps1"}

Script that does not work:

$file = "test.ps1"
start powershell {& "c:\build\$file"}

I am confused why its able to open the script perfectly fine with a given file name, but anytime I throw a variable into the mix, it doesnt work.

I tried many ways including just having it Get-Content and run the script that way, but variables in the start powershell paramater seems to throw things off.

mklement0
  • 382,024
  • 64
  • 607
  • 775
DeadLink
  • 93
  • 12
  • Any particular reason for not using the `-File` parameter? – Santiago Squarzon Jan 24 '22 at 21:51
  • 2
    In short: [`Start-Process`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/start-process)'s `-ArgumentList` parameter (the 2nd positional parameter) only accepts _string(s)_, not script blocks (`{ ... }`). If you use the latter, the script block's _verbatim_ content is passed and variable references are therefore not recognized. The best approach is to use a single, expandable string (`"..."`) in which variable values can be embedded; see the linked duplicate. – mklement0 Jan 24 '22 at 22:02
  • 2
    @mklement0 Wow, that is so stupidly simple.. I guess I just over complicated the script. start powershell "c:\build\$file" works perfectly.. Guess I didnt need the { }, and I really appreciate the explanation around that. Cheers – DeadLink Jan 24 '22 at 22:19
  • 2
    Glad to hear it helped, JakeJigsaw. Note that if the resulting path had spaces, you'd need `Start-Process powershell "& \`"c:\build\$file\`""`. Or, using the `-File` parameter, as @Santiago suggests: `Start-Process powershell "-File \`"c:\build\$file\`""`. Without `-File`, `-Command` is implied, but note that in PowerShell (Core) 7+ (`pwsh.exe`) `-File` is now implied. As for when to use which parameter, see [this answer](https://stackoverflow.com/a/57443822/45375). – mklement0 Jan 24 '22 at 22:27
  • Oh Perfect, I was actually wondering why space wasnt working, but got it working with basically exactly what you wrote, but that looks a lot simpler than what i have lol. Seriously, thanks again. @mklement0 – DeadLink Jan 24 '22 at 22:51

0 Answers0