如何将参数传递给 PowerShell 脚本? [英] How can I pass an argument to a PowerShell script?

查看:48
本文介绍了如何将参数传递给 PowerShell 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$iTunes = New-Object -ComObject iTunes.Application如果 ($iTunes.playerstate -eq 1){$iTunes.PlayerPosition = $iTunes.PlayerPosition + 30}

使用提示行命令执行:

powershell.exe itunesForward.ps1

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

解决方案

经测试有效:

#必须是脚本中的第一条语句(不包括注释)参数([Int32]$step=30)$iTunes = 新对象 -ComObject iTunes.Application如果 ($iTunes.playerstate -eq 1){$iTunes.PlayerPosition = $iTunes.PlayerPosition + $step}

调用它

powershell.exe -file itunesForward.ps1 -step 15

多参数语法(注释是可选的,但允许):

<预><代码><#脚本说明.一些笔记.#>参数 (# 没有顶栏的最大列的高度[int]$h = 4000,# 输出图像的名称[string]$image = 'out.png')

还有一些例子 高级参数,例如强制性:

<预><代码><#脚本说明.一些笔记.#>参数 (# 没有顶栏的最大列的高度[参数(强制=$true)][int]$h,# 输出图像的名称[string]$image = 'out.png')写主机$image $h"

默认值不适用于强制参数.对于布尔类型 [Parameter(Mandatory)] 的高级参数,您可以省略 =$true.

There's a PowerShell script named itunesForward.ps1 that makes 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 a 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 the hardcoded 30 seconds value?

解决方案

Tested as working:

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

$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

Multiple parameters syntax (comments are optional, but allowed):

<#
    Script description.

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

And some example for advanced parameters, e.g. Mandatory:

<#
    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"

A default value will not work with a mandatory parameter. You can omit the =$true for advanced parameters of type boolean [Parameter(Mandatory)].

这篇关于如何将参数传递给 PowerShell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆