Come passare un argomento a uno script PowerShell?

C'è uno script PowerShell chiamato itunesForward.ps1 che fa avanzare velocemente iTunes di 30 secondi:

$iTunes = New-Object -ComObject iTunes.Application

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

Viene eseguito con il comando della linea di prompt:

powershell.exe itunesForward.ps1

È possibile passare un argomento dalla linea di comando e farlo applicare nello script invece del valore hardcoded di 30 secondi?

Soluzione

Testato come funzionante:

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
}

Chiamalo con

powershell.exe -file itunesForward.ps1 -step 15
Commentari (13)

Puoi usare anche la variabile $args (che è come i parametri di posizione):

$step=$args[0]

$iTunes = New-Object -ComObject iTunes.Application

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

allora può essere chiamato come:

powershell.exe -file itunersforward.ps1 15
Commentari (4)

lascia che Powershell analizzi e decida il tipo di dati
Internamente usa un 'Variant' per questo...
e generalmente fa un buon lavoro...

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

o se hai bisogno di passare più parametri

param( $x1, $x2 )
$iTunes = New-Object -ComObject iTunes.Application
if ( $iTunes.playerstate -eq 1 ) 
    { 
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1 
    $iTunes.  = $x2
    }
Commentari (0)