• PowerShell脚本传递参数


    在编写PowerShell脚本的时候,可以通过给变量赋值的方法输出想要的结果,但这样的话,需要改动脚本内容。其实也可以在脚本中定义参数,然后再在执行脚本的时候对参数赋值,而无需改动脚本内容。

      在PowerShell脚本中,可以使用param()声明参数,如下:

      param($a,$b)

      write-host "Hello,$a"

      write-host "nihao,$b"

      将以上内容保存在F盘根目录下,命名为hello.ps1。

      在命令提示符下运行该脚本,并分别为参数$a和$b指定值为“Lily”和“Lucy”,方式如下:

      C:UsersAdministrator>powershell.exe F:hello.ps1 Lily Lucy

      脚本执行结果为:

      Hello,Lily

      nihao,Lucy

      如果需要改变参数位置,需要为不同的参数指定值,如将$a指定值为“Lucy”,$b指定值为“Lily”,方式如下:

      C:UsersAdministrator>powershell.exe F:hello.ps1 -b Lily -a Lucy

      脚本执行结果为:

      Hello,Lucy

      nihao,Lily

      在声明参数的时候,还可以指定参数类型,如下:

      param([string]$a,[int]$b)

      $a+$b

      在给脚本传递参数的时候,如果为$a和$b指定参数类型为string,则会报错,如下:

      C:UsersAdministrator>powershell.exe F:hello.ps1 -a LiLei -b Lin

      F:hello.ps1 : 无法处理对参数“b”的参数转换。无法将值“Lin”转换为类型“System.

      Int32”。错误:“输入字符串的格式不正确。”

      所在位置 行:1 字符: 25

      + F:hello.ps1 -a LiLei -b <<<< Lin

      + CategoryInfo : InvalidData: (:) [hello.ps1], ParameterBindin...

      mationException

      + FullyQualifiedErrorId : ParameterArgumentTransformationError,hello.ps1

      只有为其赋予int类型值才可以,如下:

      C:UsersAdministrator>powershell.exe F:hello.ps1 -a 5 -b 6

      11

     
    分类: PowerShell
  • 相关阅读:
    Git CMD
    Guava Cache相关
    137.Single Number II---位运算---《剑指offer》40
    SpringMVC数据绑定
    StringUtils工具类的使用
    sql注入
    mapper配置文件中的动态SQL
    json相关注解和序列化与反序列化
    用户模块
    横向越权与纵向越权
  • 原文地址:https://www.cnblogs.com/micro-chen/p/5900483.html
Copyright © 2020-2023  润新知