如何将参数传递给PowerShell脚本?

时间:2022-05-13 14:09:06

There's a PowerShell script named itunesForward.ps1 that makes the iTunes fast forward 30 seconds:

有一个名为itunesForward.ps1的PowerShell脚本使iTunes快进30秒:

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + 30
}

It is executed with prompt line command:

它使用快速行命令执行:

powershell.exe itunesForward.ps1

Is it possible to pass an argument from the command line and have it applied in the script instead of hardcoded 30 seconds value?

是否可以从命令行传递参数并将其应用于脚本而不是硬编码的30秒值?

2 个解决方案

#1


452  

Tested as working:

测试工作:

param([Int32]$step=30) #Must be the first statement in your script

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}

Call it with

叫它

powershell.exe -file itunesForward.ps1 -step 15

#2


267  

You can use also $args variable (that's like position parameters):

你也可以使用$ args变量(就像位置参数一样):

$step=$args[0]

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}

then it can be call like:

然后它可以像这样调用:

powershell.exe -file itunersforward.ps1 15

#1


452  

Tested as working:

测试工作:

param([Int32]$step=30) #Must be the first statement in your script

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}

Call it with

叫它

powershell.exe -file itunesForward.ps1 -step 15

#2


267  

You can use also $args variable (that's like position parameters):

你也可以使用$ args变量(就像位置参数一样):

$step=$args[0]

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}

then it can be call like:

然后它可以像这样调用:

powershell.exe -file itunersforward.ps1 15