2

This is the command that I provided to the customer before:

iex ((New-Object System.Net.WebClient).DownloadString('URL'))

It downloads PS script as a string from URL location and executes the script.

Now I need to pass parameter to this script

iex (((New-Object System.Net.WebClient).DownloadString('URL')) -Parameter 'parameter')

And it is not working because string not accepts parameters

I need to create the simple command (it is important) that will download the script from URL and accept parameters. Otherwise I would save this string to ps1 file and execute it passing the parameter

Could you please help me with that? I am new to PS

Max K.
  • 31
  • 5

1 Answers1

2

Try the following approach:

& ([scriptblock]::Create(
     (New-Object System.Net.WebClient).DownloadString('URL')
  )) 'Parameter'

Note:

  • The above runs the script text in a child scope, due to use of &, the call operator, as would happen with local invocation of a script file, whereas Invoke-Expression (iex) runs it in the current scope, i.e. as if it were called with . , the dot-sourcing operator. Change & to . if you want this behavior.

  • To download the script, you could alternatively use PowerShell's Invoke-RestMethod (irm) cmdlet: Invoke-RestMethod 'URL' or irm 'URL'

  • [scriptblock]::Create() creates a PowerShell script block, which can then be invoked with & (or .), while also accepting arguments.


As for what you tried:

Invoke-Expression (iex) - which should generally be avoided - has several drawbacks when it comes to executing a script file's content downloaded from the web:

  • It doesn't support passing arguments, as you've discovered.

  • An exit statement in the script text would cause the current PowerShell session to exit as a whole.

  • As noted, the code executes directly in the caller's scope, so that its variables, functions, ... linger in the session after execution (however, it's easy to avoid that with & { iex '...' }).

GitHub issue #5909 discusses enhancing the Invoke-Command cmdlet to robustly support download and execution of scripts directly from the web.

mklement0
  • 382,024
  • 64
  • 607
  • 775