Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Powershell to download a script file then execute it with passing in arguments?

Tags:

powershell

I usually have this command to run some powershell script:

& ".\NuGet\NuGet Package and Publish.ps1" -Version $env:appveyor_build_version -NuGet "C:\Tools\NuGet\nuget.exe" -apiKey $env:apiKey

works fine but the script is found locally on my server.

I'm hoping to say: run this script with arguments, etc.. fine .. but the script is located as a GIST or in some GitHub public repo.

Is this possible?

like image 484
Pure.Krome Avatar asked Oct 19 '15 01:10

Pure.Krome


People also ask

How do I Run a PowerShell script from an argument?

To make sure PowerShell executes what you want, navigate in the command line to the same directory where you will save your scripts. Name the script Unnamed_Arguments_Example_1. ps1 and run it with the argument FOO. It will echo back FOO.


2 Answers

In the linux world, this is commonly referred to as 'piping to bash'

Here is an example that installs chef taken from the chef documentation

curl -L https://omnitruck.chef.io/install.sh | sudo bash

The same thing can be done with powershell

. { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install

iwr is shorthand for Invoke-WebRequest and iex is short for Invoke-Expression

Since you specifically asked about passing in arguments, here is an example with args.

. { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -channel current -project chefdk

You can look at the powershell script for a clearer understanding how it works.

Basically host your powershell script as a github gist, then in the script wrap everything in a module

new-module -name foobar -scriptblock {


  Function Foo() {

  }
  Function Bar() {

  }
  Function Install-Project() {
    param (
      [string]$project = 'chef',
      [string]$channel = 'stable'
    )
    Foo
    Bar
  }

  set-alias install -value Install-Project

  export-modulemember -function 'Foo','Bar' -alias 'install'
}

Best practices

'Piping to bash' is controversial because it is theoretically possible for attacker to intercept and replace your script with their own if you aren't careful.

  • Only install scripts you control or fully trust
  • Use permalinks or verify hashes of file you download
  • Only download from https
like image 139
spuder Avatar answered Dec 04 '22 19:12

spuder


If I understood the question correctly, this is what worked for me:

(new-object net.webclient).DownloadFile('https://gist.githubusercontent.com/AndrewSav/c4fb71ae1b379901ad90/raw/23f2d8d5fb8c9c50342ac431cc0360ce44465308/SO33205298','local.ps1')
./local.ps1 "parameter title"

Output:

Called with parameter: parameter title

This is downloading and executing this gist: https://gist.github.com/AndrewSav/c4fb71ae1b379901ad90

like image 42
Andrew Savinykh Avatar answered Dec 04 '22 20:12

Andrew Savinykh