PowerShell远程执行脚本是如何引用外部参数

来源:互联网 发布:道家经典软件 编辑:程序博客网 时间:2024/06/05 07:50

最近在写Jenkins job,其中我想用PowerShell远程执行一段脚本,并且在这段脚本中使用外部变量,是了很多方法都不行,后来参考一下两篇文章终于解决了:

http://ss64.com/ps/invoke-command.html

http://blog.csdn.net/itanders/article/details/9073351


下面来讲讲我的方法:

首先有一个外部变量,该变量是在执行远程脚本之前初始化的:

$variables = Get-Content -Path Bundles.txt$variables

然后启动一个远程会话:

$user = $env:USER_NAME$password = $env:PASSWORDEnable-PSRemoting -Force$secPassword = ConvertTo-SecureString $password -AsPlainText –Force$mycreds = New-Object system.Management.Automation.PSCredential($user, $secPassword)$s = New-PSSession -computerName $DestinationServer -credential $mycreds

最后在远程机器上执行代码:

Invoke-Command -Session $s -ArgumentList $variables -Scriptblock {    param($variables)$DeployedBundles = ""    if($variables -ne $null -and $variables.Length -gt 0){        $DeployedBundles = $variables.Split("=")[1].Split(",")    }   #Other codes...}


看到了吗? 关键点在于Invoke-Command命令引用了一个参数 -ArgumentList,同时在ScriptBlock里面使用param调用该参数?


哈哈,就这么简单问题解决了。。。

0 0