PowerShell スクリプトに引数を渡すにはどうすればいいですか? 質問する

PowerShell スクリプトに引数を渡すにはどうすればいいですか? 質問する

itunesForward.ps1iTunes を 30 秒早送りするPowerShell スクリプトがあります:

$iTunes = New-Object -ComObject iTunes.Application

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

これはプロンプト ライン コマンドで実行されます。

powershell.exe itunesForward.ps1

ハードコードされた 30 秒の値の代わりに、コマンドラインから引数を渡してスクリプトに適用することは可能ですか?

ベストアンサー1

動作テスト済み:

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

$iTunes = New-Object -ComObject iTunes.Application

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

それを呼ぶ

powershell.exe -file itunesForward.ps1 -step 15

複数のパラメータ構文 (コメントはオプションですが、許可されています):

<#
    Script description.

    Some notes.
#>
param (
    # height of largest column without top bar
    [int]$h = 4000,
    
    # name of the output image
    [string]$image = 'out.png'
)

そして、いくつかの例高度なパラメータ例:必須

<#
    Script description.

    Some notes.
#>
param (
    # height of largest column without top bar
    [Parameter(Mandatory=$true)]
    [int]$h,
    
    # name of the output image
    [string]$image = 'out.png'
)

Write-Host "$image $h"

デフォルト値は必須パラメータでは機能しません。boolean=$true型の詳細パラメータの場合は省略できます[Parameter(Mandatory)]

おすすめ記事