代码之家  ›  专栏  ›  技术社区  ›  Pavel Mi

如何使用Invoke命令传递多个参数

  •  1
  • Pavel Mi  · 技术社区  · 7 年前

    我想在我的桌面上创建一些快捷方式,它可以在本地工作。但是,当我在远程PC上尝试时,第一个目标只有一个快捷方式( path1 ),脚本忽略 path2 变量

    $Servers = Get-Content D:\1.txt
    
    function add-sc {
        param ([string[]]$Targets) 
        BEGIN {}
        PROCESS {
            foreach ($a in $Targets) {
                $WshShell = New-Object -comObject WScript.Shell
                $b = $a.Substring($a.length - 5)
                $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\$b.lnk")
                $Shortcut.TargetPath = $a
                $Shortcut.Save()
            }
        }
        END {}
    }
    
    foreach ($server in $Servers) {
        Invoke-Command -ComputerName $server -ScriptBlock ${function:add-sc} -Args "path1", "path2"
    }
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   Ansgar Wiechers    7 年前

    首先,应该在scriptblock中定义函数。我不确定PowerShell v5+,但在PowerShell v4和更早版本中,有一个命令

    Invoke-Command -Computer bar -Scriptblock {function:foo}
    

    将引发错误,因为在scriptblock中无法识别该函数。

    此外,您还需要将参数实际传递给正在调用的函数。基本上有两种方法可以解决这个问题:

    • 通过将参数传递给函数 automatic variable $args :

      Invoke-Command -Computer $server -ScriptBlock {
          function add-sc {
              Param([string[]]$Targets)
              Process {
                  ...
              }
          }
          add-sc $args
      } -ArgumentList 'path1', 'path2'
      
    • 将参数作为单个数组传递给scriptblock,然后 splat 他们在功能上:

      Invoke-Command -Computer $server -ScriptBlock {
          function add-sc {
              Param([string[]]$Targets)
              Process {
                  ...
              }
          }
          add-sc @args
      } -ArgumentList @('path1', 'path2')
      

    这两种方法的区别在于,前者接受所有参数并将其作为单个数组传递给函数,而后者接受所有参数并将其作为单个参数传递给函数。因此,在后一种情况下,需要将参数作为单个数组传递给scriptblock。

    在您的场景中,这两种方法是等效的,但如果您的函数需要数组之外的第二个参数,则需要第二种方法,并将参数作为 -ArgumentList @('a','b'), 'c'

        2
  •  0
  •   kim    7 年前

    您还可以使用 -ArgumentList 参数,或很快 -args ,将多个参数发送到脚本块。您只需要在脚本块内部处理它们。

    看看这个简短的例子

    Invoke-Command -ArgumentList "Application",10 -ScriptBlock {
        param([string]$log,[int]$lines)
        Get-EventLog $log -Newest $lines
    }
    

    此处-ArgumentList包含两个参数

    • 字符串“Application”和
    • 整数10

    它们作为参数发送到scriptblock,因此在它的开头定义。

    现在,您可以在scriptblock中像普通参数一样访问它们:

    • $log
    • $lines
        3
  •  0
  •   henrycarteruk    7 年前

    我觉得你的语法和代码很好,你确定 path2 远程计算机上是否存在?如果目标无效,则无法创建快捷方式。