15

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?

1
  • 2
    Look how chocolatey does it Commented May 10, 2017 at 21:50

5 Answers 5

36

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
That doesn't seem to permit additional command line arguments to be given to the remote powershell script.
And will give you this error "This script contains malicious content and has been blocked by your antivirus software."
14

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'))

2 Comments

$args + @('someargument') seems to be required, or it flattens the $args and turns it into a string
Thanks @NeilMitchell
9

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

2 Comments

This should be higher as it works in Constrained Language Mode. The other answers rely on C# APIs which are not permitted in CLM
In order for this to work in Restricted Language Mode, you need to use iex (iwr $ScriptURL | select -ExpandProperty Content) as property assessors are not allowed in that PowerShell mode
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"

Comments

0

work on PowerShell 2.0

Invoke-Expression (New-Object System.Net.WebClient).DownloadString($scriptUrl)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.