How to pass an argument to a PowerShell script?

2019-01-04 05:23发布

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

$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?

4条回答
你好瞎i
2楼-- · 2019-01-04 05:41

Create a powershell script with the following code in the file.

param([string]$path)
Get-ChildItem $path | Where-Object {$_.LinkType -eq 'SymbolicLink'} | select name, target

This creates a script with a path parameter. It will list all symboliclinks within the path provided as well as the specified target of the symbolic link.

查看更多
我命由我不由天
3楼-- · 2019-01-04 05:44

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
查看更多
叛逆
4楼-- · 2019-01-04 05:53

let Powershell analyze and decide the data type
Internally uses a 'Variant' for this...
and generally does a good job...

param( $x )
$iTunes = New-Object -ComObject iTunes.Application
if ( $iTunes.playerstate -eq 1 ) 
    { $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x }

or if you need to pass multiple parameters

param( $x1, $x2 )
$iTunes = New-Object -ComObject iTunes.Application
if ( $iTunes.playerstate -eq 1 ) 
    { 
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1 
    $iTunes.<AnyProperty>  = $x2
    }
查看更多
Rolldiameter
5楼-- · 2019-01-04 05:57

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

$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
查看更多
登录 后发表回答