zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Python中的编码
    编译gcc
    内存的非法读写操作的检查
    Git合并特定commits 到另一个分支
    局部静态变量是如何做到只初始化一次的?
    how-to-redirect-cin-and-cout-to-files
    Time series database
    Linux System Calls Hooking Method Summary
    tomcat 创建虚拟主机
    oracle查锁表SQL
  • 原文地址:https://www.cnblogs.com/dreamer-fish/p/3681063.html
Copyright © 2011-2022 走看看