You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从不同路径的批处理文件向PowerShell脚本传递参数

实现从批处理向跨路径PowerShell脚本传递参数的方案

没问题,这就帮你搞定从批处理调用不同路径的PowerShell脚本,同时传递PS脚本的文件夹位置和用户输入的字符串参数的需求。下面是具体的代码优化和实现步骤:

1. 调整PowerShell脚本,支持接收双参数

为了让脚本逻辑更清晰、后续维护更方便,推荐用param块定义命名参数;如果习惯用位置参数也可以,两种写法都给你列出来:

写法一:命名参数(推荐)

param(
    # 接收PowerShell脚本所在的文件夹位置
    [string]$ScriptFolder,
    # 接收用户在批处理中输入的字符串参数
    [string]$UserInputParam
)

# 原有下载逻辑,可按需使用传入的参数
$url = "https://www.ons.gov.uk/generator?format=csv&uri=/economy/inflationandpriceindices/timeseries/chaw/mm23"
$output = "sample.csv"
# 也可以把用户参数融入文件名,比如:$output = "sample_$UserInputParam.csv"

$start_time = Get-Date
# 将文件保存到指定的脚本文件夹路径下
Invoke-WebRequest -Uri $url -OutFile "$ScriptFolder\$output"

Write-Output "下载完成,耗时:$((Get-Date).Subtract($start_time).Seconds) 秒"
Write-Output "接收到的用户输入参数:$UserInputParam"

写法二:位置参数(和你原代码风格一致)

$scriptFolder = $args[0]
$userInput = $args[1]

$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 "$scriptFolder\$output"
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
Write-Output "User input: $userInput"

2. 编写批处理文件,完成参数传递

批处理需要做三件事:获取用户输入、提取PS脚本的文件夹位置、调用PS脚本并传递参数。代码如下:

@echo off
setlocal enabledelayedexpansion

:: 提示用户输入需要传递的字符串参数
set /p "userInput=请输入字符串参数:"

:: 替换成你的PowerShell脚本完整路径
set "psFullPath=C:\temp\download-rpi.ps1"

:: 自动提取脚本所在的文件夹路径(%%~dpF会返回文件的驱动器+目录路径)
for %%F in ("%psFullPath%") do set "psScriptFolder=%%~dpF"

:: 调用PowerShell脚本并传递参数
:: 如果用的是命名参数的PS脚本,可改成:
:: powershell.exe -ExecutionPolicy Bypass -File "%psFullPath%" -ScriptFolder "%psScriptFolder%" -UserInputParam "%userInput%"
powershell.exe -ExecutionPolicy Bypass -File "%psFullPath%" "%psScriptFolder%" "%userInput%"

pause

关键说明

  • 批处理中的%%~dpF是特殊变量,能自动从脚本完整路径中提取目录,不用手动写死路径,更灵活;如果需要指定其他保存路径(比如你原代码里的\\drives\savehere),直接把psScriptFolder改成目标路径即可。
  • 参数外的双引号是必须的,避免路径或参数包含空格时出现解析错误。

内容的提问来源于stack exchange,提问作者KKK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:30:51