13

I want to write a PowerShell script that runs a PowerShell script stored at a URL, passing both custom arguments and forwarding any arguments that are given to this PowerShell. Concretely, I can do:

$VAR=Invoke-WebRequest http://example.com/powershell.ps1
$TEMP=New-TemporaryFile
$FILE=$TEMP.FullName + ".ps1"
$VAR.Content | Out-File $FILE
& $FILE somearguments $args

I'd ideally like to do that without using a temporary file, however powershell -content - doesn't seem to allow also passing arguments. Is there any way to avoid the temporary file?

Neil Mitchell
  • 9,090
  • 1
  • 27
  • 85

4 Answers4

32

Stolen straight from chocolatey's site. I use this more often than i should

iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

source

Daniel Agans
  • 657
  • 1
  • 6
  • 14
  • 1
    This is what I use, easiest and most direct way.... the `DownloadString()` method pulls the raw contents, then `iex` (`Invoke-Expression`) runs the string that's pulled – scrthq May 11 '17 at 04:45
  • 7
    That doesn't seem to permit additional command line arguments to be given to the remote powershell script. – Neil Mitchell May 12 '17 at 11:08
  • And will give you this error "This script contains malicious content and has been blocked by your antivirus software." – Max Barrass Mar 13 '21 at 12:29
13

You can convert content to script block and then invoke it as command with arguments

$Script = Invoke-WebRequest 'http://example.com/powershell.ps1'
$ScriptBlock = [Scriptblock]::Create($Script.Content)
Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList ($args + @('someargument'))
Neil Mitchell
  • 9,090
  • 1
  • 27
  • 85
Igor
  • 1,349
  • 12
  • 25
5

Automatic download and start remote PowerShell script w/0 save (on the fly):

iex (iwr $ScriptURL).Content

WTF:

enter image description here

alias iex,iwr

More help:

Get-Help Invoke-Expression
Get-Help Invoke-WebRequest
SynCap
  • 6,244
  • 2
  • 18
  • 27
3

This one-liner will download and source the file from a URL

. ([Scriptblock]::Create((([System.Text.Encoding]::ASCII).getString((Invoke-WebRequest -Uri "${FUNCTIONS_URI}").Content))))

example $FUNCTIONS_URI = "https://github.com/aem-design/aemdesign-docker/releases/latest/download/functions.ps1"

Max Barrass
  • 2,776
  • 1
  • 19
  • 10