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

我有一个简单的脚本:

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

将这些参数接收到变量并将这些变量放入不同功能的主要任务。

bill58702738 回答:如何在Powershell脚本中使用关键字参数?

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

# Untitled2.ps1

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

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

getops -server $server -name $name -user $user -password $password -url $url -acl $acl

然后您可以通过以下方式调用脚本

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

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

param
(
  [ValidateNotNullOrEmpty()]
  [string]$server,[string]$acl

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

然后运行脚本

.\Untitled2.ps1 -server my\sqlexpress -name my -user my_user -password my_password -url 192.168.0.1 -acl 192.168.0.1:5000
本文链接:https://www.f2er.com/3062623.html

大家都在问