如何在Powershell脚本中使用关键字参数?

问题描述 投票:0回答:2

我有一个简单的脚本:

function getops {
[CmdletBinding()]
  param
  (
    [ValidateNotNullOrEmpty()]
    [string]$server,
    [string]$name,
    [string]$user,
    [string]$password,
    [string]$url,
    [string]$acl

  )
    echo $server
    echo $name
    echo $user
    echo $password
    echo $url
    echo $acl
}

getops

但是当我尝试使用参数调用此脚本时。

.\Untitled2.ps1 -server my\sqlexpress -name my -user my_user -password my_password -url 192.168.0.1 -acl 192.168.0.1:5000

我看到空结果。

当我向脚本中的函数添加所需参数时>

function getops {
[CmdletBinding()]
  param
  (
    [ValidateNotNullOrEmpty()]
    [string]$server,
    [string]$name,
    [string]$user,
    [string]$password,
    [string]$url,
    [string]$acl

  )
    echo $server
    echo $name
    echo $user
    echo $password
    echo $url
    echo $acl
}

getops -server my\sqlexpress -name my -user my_user -password my_password -url 192.168.0.1 -acl 192.168.0.1:5000

我看到结果,我需要:

my\sqlexpress
my
my_user
my_password
192.168.0.1
192.168.0.1:5000

问题,如何通过调用带有关键字参数的脚本在powershell中获得相同的结果,如下所示:

.\Untitled2.ps1 -server my\sqlexpress -name my -user my_user -password my_password -url 192.168.0.1 -acl 192.168.0.1:5000

将这些参数转换为变量并将这些变量放入不同功能的主要任务。

我有一个简单的脚本:function getops {[CmdletBinding()] param([ValidateNotNullOrEmpty()] [string] $ server,[string] $ name,[string] $ user,[string] $ password,[string] $ ...

powershell arguments parameter-passing command-line-arguments keyword
2个回答
0
投票

在函数外定义另一个参数块,以便可以将参数传递到脚本。就您而言,您只需调用不带参数的函数即可。


0
投票

您可以通过与函数中相同的方式在脚本中使用参数用param块编写脚本

© www.soinside.com 2019 - 2024. All rights reserved.