2

在开发团队中,我希望开发人员在本地或我们的测试平台远程执行相同的测试脚本。

这是我想用作每个脚本的前提

# Test local/remote execution by reading C:\ directory
param(
    [switch] $verbose,
    [switch] $remote,
    [string] $ip,
    [string] $user,
    [string] $password
    #Add here script specific parameters
)

Write-Host "Command invokation incoming parameter count : " $psboundparameters.count

if ($remote) {
    $Params = @{}
    $RemoteParams = @{}
    $pass = ConvertTo-SecureString -String $password -AsPlainText -Force 

    $Params.Credential = new-object -TypeName System.management.automation.PSCredential -argumentlist $user, $pass
    $Params.ComputerName = $ip
    $Params.FilePath = $MyInvocation.MyCommand.Name
    $null = $psboundparameters.Remove('remote')
    $null = $psboundparameters.Remove('ip')
    $null = $psboundparameters.Remove('user')
    $null = $psboundparameters.Remove('password')

    foreach($psbp in $PSBoundParameters.GetEnumerator())
    {
        $RemoteParams.$($psbp.Key)=$psbp.Value
    }
    Write-Host $RemoteParams
    Invoke-Command @Params @Using:RemoteParams
    Exit 
}

Write-Host "Command execution incoming parameters count : "    $psboundparameters.count

# Here goes the test 
Get-ChildItem C:\

但是,当我执行此操作时,出现以下错误:

Invoke-Command : A positional parameter cannot be found that accepts argument '$null'.

似乎@Using:RemoteParams不是这样做的正确方法,但我在这里很迷茫。提前致谢

4

1 回答 1

1

这是我对能够使用命名参数进行本地和远程执行的问题的看法:

$IP = '192.168.0.1'
$User = 'Test User'
$Password = 'P@ssW0rd!' 

$params = @{
IP = $IP
User = $User
Password = $Password
}

$command = 'new-something'

$ScriptBlock = [Scriptblock]::Create("$command $(&{$args} @Params)")

从参数哈希表开始,使用局部变量,然后使用:

[Scriptblock]::Create("$command $(&{$args} @Params)")

创建命令的脚本块,其中包含内联参数和已扩展的值。现在该脚本块已准备好在本地运行(通过调用&或点源),或远程使用Invoke-Command.

$ScriptBlock
new-something -IP: 192.168.0.1 -User: Test User -Password: P@ssW0rd!

没有范围界定$Using:-argumentlist要求。

编辑:这是一个使用脚本而不是单个命令的示例:

$path = 'c:\windows'
$filter = '*.xml'

$Params = 
@{
   Path = $path
   Filter = $filter
  }

$command = @'
{
  Param (
    [String]$path,
    [String]$Filter
   )

 Get-childitem -Path $path -Filter $filter
}
'@

$ScriptBlock = [Scriptblock]::Create(".$command $(&{$args} @Params)")

要在本地运行它:

 Invoke-Command $ScriptBlock

要不就:

 .$ScriptBlock

要远程运行它:

 Invoke-Command -Scriptblock $ScriptBlock -ComputerName Server1
于 2015-10-08T17:38:27.767 回答