Powershell 将所有公共变量传递给invoke命令

Powershell 将所有公共变量传递给invoke命令,powershell,invoke-command,Powershell,Invoke Command,最近,我一直在下载我觉得有用的powershell函数和脚本,并将它们包装到invoke命令中,使它们在我的网络中更有用。有一件事我还没有弄清楚,那就是如何从[cmdletBinding()]接受公共参数,并将它们全部传递到invoke命令中。我知道如何传递个人偏好变量,但不知道它们的全部。有公共变量集合吗?下面是一些powershell摘录以帮助说明 ScriptBlock = { #How do I pass the whole of the common variables?

最近,我一直在下载我觉得有用的powershell函数和脚本,并将它们包装到invoke命令中,使它们在我的网络中更有用。有一件事我还没有弄清楚,那就是如何从[cmdletBinding()]接受公共参数,并将它们全部传递到invoke命令中。我知道如何传递个人偏好变量,但不知道它们的全部。有公共变量集合吗?下面是一些powershell摘录以帮助说明

ScriptBlock =
{   #How do I pass the whole of the common variables?
    $ErrorActionPreference=$using:ErrorActionPreference
    $InformationPreference=$Using:InformationPreference
    $VerbosePreference=$Using:VerbosePreference...

Process
{
    Write-Verbose "Processing"
    $computername=$name
    #Used $Name as a parameter originally to be compatible with the get-adcomputer cmdlet
    If ($Credential) {Invoke-Command -ComputerName $computername -Credential $Credential -ScriptBlock $ScriptBlock}
    Else {Invoke-Command -ComputerName $computername -ScriptBlock $ScriptBlock}
    #You will need to be running Powershell with the proper Admin privileges if you don't specify a credential
} #End Process
  END{

您可以从$PSBoundParameters哈希表中获得它

$VerbosePreference=$PSBoundParameters['Verbose']
$ErrorActionPreference=$PSBoundParameters['ErrorAction']
编辑:

您还可以将这些标准参数添加到cmdlet中

Invoke-Command -scriptblock $scriptblock @PSBoundParameters

第一种选择并不比我现在所做的更好,第二种选择更接近我想要的。然而,当我使用它的时候,它就错在我身上了。我认为只有当我的参数都符合invoke命令的期望时,这才有效。我说得对吗?是的,那是真的。您还可以构造一个自定义哈希表来存储您的变量,并将它们显示在您需要的任何位置。您可以使用
[System.Management.Automation.Cmdlet]:CommonParameters以编程方式构建它,它工作了!对我的脚本稍加修改,我就完成了。你现在让我的剧本如此性感。她将是所有其他剧本羡慕的对象。太棒了!如果对你有用的话,请别忘了标记我的答案。