简体   繁体   中英

Execute any file as powershell script

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?

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.

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.

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.

或者,您可以使用Get-Content读取文件,然后使用Invoke-ExpressionInvoke-Command -ScriptBlock调用该文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM