将参数从批处理文件传递给powershell脚本

时间:2018-01-26 12:42:18

标签: powershell batch-file

我在批处理文件中调用powershell脚本,两者都在不同的位置。

我想传递powershell脚本文件的文件夹位置以及该批处理文件中用户在批处理文件中输入的字符串参数。

powershell脚本:

Activity B

我的批处理文件:

$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)"

2 个答案:

答案 0 :(得分:2)

你可以用一种语言完成所有这些,而不是同时使用Powershell和批处理,但无论如何,这就是你想要的

@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%"

工作原理:

您可以双击该文件,然后提示您输入powershell路径和共享路径

OR

从cmdline运行并在批处理命令后输入变量,这将使用%1 %2来设置变量。例子:

  
      
  1. 双击批次:
  2.   
Enter the path to Powershell: C:\Some Path\
Enter The share parameter: \\some\share

<强> 结果

powershell.exe -ExecutionPolicy Bypass -file "C:\Some Path\" "\\some\share"
  
      
  1. 从cmd.exe提示符
  2. 运行   
C:\> BatchFileName.cmd "C:\Some Path\" "\\some\share"

<强> 结果

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

答案 1 :(得分:1)

在PowerShell中,这是使用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)"

另一种方法是使用自动变量$MYINVOCATION来获得与$args数组类似的行为,但我不建议这样做,因为您无法知道将提供哪些未绑定参数。

$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)"
相关问题