【问题标题】:Passing parameters to powershell script from batch file从批处理文件将参数传递给powershell脚本
【发布时间】:2018-01-26 12:42:18
【问题描述】:

我正在从一个批处理文件中调用一个 powershell 脚本,这两个文件都在不同的位置。

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

powershell 脚本:

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

我的批处理文件:

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

【问题讨论】:

  • 为什么需要批处理文件?只需从 PowerShell 提示符运行脚本。
  • @Bill_Stewart 因为他只能从第三方软件调用批处理。
  • 也许,但问题中没有说明。
  • @Bill_Stewart 他没有,不,他只在下面的 cmets 中提到了答案。

标签: powershell batch-file


【解决方案1】:

您可以用一种语言完成所有这些操作,而不是同时使用 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 路径和共享路径

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

  1. 双击批处理:
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 提示符运行
C:\> BatchFileName.cmd "C:\Some Path\" "\\some\share"

结果

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

【讨论】:

  • 谢谢。它帮助我解决了我的问题
  • @Khushi 很高兴我能帮上忙。
【解决方案2】:

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

【讨论】:

  • @gmsoylman:谢谢。现在来到批处理文件 - 而不是传递硬编码路径(就像我在批处理文件中传递 $path 一样)如何将它们作为可以在第三方提供的参数传递?我的批处理文件也在不同的文件夹中,所以我想将 poweshell 脚本的路径作为参数
  • @Khushi 您使用批处理文件而不是纯 PowerShell 是否有原因?
  • 是的。我在不支持直接调用 powerscript 文件的第三方应用程序中调用此批处理文件。
猜你喜欢
  • 2023-01-23
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多