Question:
I encountered a challenge that I failed to resolve the way I wanted it to do.
I got a file that contains a powershell script, but that file does not have the extension assigned to powershell. The question is: How can I execute a powershell in a script file with the wrong file extension (or none)?
Invoke-Expression
does not seem to work because it always executes the default action assigned to the file type. If I give that cmdlet a *.txt
file the editor pops open.
I know that I can resolve that by renaming the script file or naming it properly in the first place. This is what I ended up doing.
Still I wonder if it is possible to execute a file as a script with the wrong file extension without modifying, renaming or coping the file. And if it is not working… why is that?
Answer:
Powershell is designed such that executing or dot sourcing a file requires a .ps1
extension, and Powershell.exe will refuse to run any file that doesn’t have that extension.
One way to invoke Powershell code from a non-ps1 file is to launch Powershell.exe using STDIN, and pipe your script to it. This requires a new shell, so is not very good for launching scripts from within an existing scripting environment.
1 2 |
Powershell.exe - < thescript.txt |
Another way is to create a temporary .ps1
file and execute that. This has the advantage of using the current scripting environment, but requires a temporary file.
1 2 3 4 |
Copy-Item -Path '.\thescript.txt' -Dest '.\temp.ps1' . .\temp.ps1 del .\temp.ps1 |
In my opinion, the file extension restriction is silly, but that’s how it was designed. Apocryphally, this is for security reasons, but I can find no citation to back it up.