KKK
KKK

Reputation: 47

Passing parameters to powershell script from batch file

I am calling a powershell script from a batch file, both in different locations.

I would like to pass the folder location for the powershell script file as well as the parameter, a user entered string in the batch file, from that batch file.

powershell script:

$url = "https://www.ons.gov.uk/generator?format=csv&uri=/economy/inflationandpriceindices/timeseries/chaw/mm23"
$output="sample.csv"
$start_time = Get-Date
$arg1=$args[0]
Invoke-WebRequest -Uri $url -OutFile $arg1\$output
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

My Batch file :

powershell.exe -ExecutionPolicy Bypass -file C:\temp\download-rpi.ps1 "\\drives\savehere"

Upvotes: 2

Views: 8269

Answers (2)

user7818749
user7818749

Reputation:

You could have done all of this in a single language instead of using both Powershell and batch, but regardless, here is what you want

@echo off
if "%1"=="" (
    set /p "pspath=Enter the path to Powershell: "
    ) else set "pspath=%1"
if "%2"=="" (
    set /p "sharepath=Enter the share parameter: "
    ) else set "sharepath=%2"
    powershell.exe -ExecutionPolicy Bypass -file "%pspath% "%sharepath%"

How it works:

you can either double click the file which will then prompt for the powershell path and sharepath

OR

run from cmdline and enter the variables after the batch command, which will use %1 %2 to set the variables. Examples:

  1. Double Clicking batch:
Enter the path to Powershell: C:\Some Path\
Enter The share parameter: \\some\share

Result

powershell.exe -ExecutionPolicy Bypass -file "C:\Some Path\" "\\some\share"
  1. Running from cmd.exe prompt
C:\> BatchFileName.cmd "C:\Some Path\" "\\some\share"

Result

powershell.exe -ExecutionPolicy Bypass -file "C:\Some Path\" "\\some\share"

Upvotes: 3

G42
G42

Reputation: 10019

In PowerShell, this is done using parameters:

param(
    [string]$Path
)

$url        = "https://www.ons.gov.uk/generator?format=csv&uri=/economy/inflationandpriceindices/timeseries/chaw/mm23"
$output     = "sample.csv"
$start_time = Get-Date

Invoke-WebRequest -Uri $url -OutFile $Path\$output

Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

An alternative is to use the automatic variable $MYINVOCATION to get similar behaviour to an $args array but I would not recommend that as you have no way of knowing what unbound parameters will be provided.

$url        = "https://www.ons.gov.uk/generator?format=csv&uri=/economy/inflationandpriceindices/timeseries/chaw/mm23"
$output     = "sample.csv"
$start_time = Get-Date
$Path       = $MYINVOCATION.UnboundArguments

Invoke-WebRequest -Uri $url -OutFile $Path\$output

Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

Upvotes: 1

Related Questions