PowerShell函数有参数吗?

时间:2016-10-29 03:06:11

标签: powershell

我有一个我无法理解的PoSH脚本没有运行..

function Connect-AD
{
    Param($mod,$cmd)
    Write-Host "$mod $cmd"
    Write-Host "`tConnecting to AD: $DC`n"
    $ADSession = New-PSsession -ComputerName $DC -Credential $MyCredential
    Invoke-Command -Command {Import-Module ('$mod') -Cmdlet ('$cmd')} -Session $ADSession
    Import-PSSession -Session $ADSession -Module ('$mod') -Prefix r | Out-Null
}

然后我尝试用..来调用它。

Connect-AD -mod 'ActiveDirectory' -cmd 'Get-ADUser,New-ADUser'

但不管我做什么我都会继续......

  

指定的模块' $ mod'未加载,因为在任何模块目录中找不到有效的模块文件。

函数内部的Write-Host正确输出参数,因此它已经走得那么远了。但是它没有被传递到Invoke-Command或Import-PSSession?

我尝试了不同的方法来逃避参数等等。但没有运气。

我做得不好?有人能帮帮我吗?感谢。

1 个答案:

答案 0 :(得分:7)

单引号字符串不会插入变量,'$mod'是一个文字字符串" dollar m o d"。

您可能需要阅读有关将参数传递给Invoke-Command的所有类似问题,因为命令{}正在另一台计算机上运行 - 它如何知道您的计算机上的变量$mod是什么? / p>

Passing string $variable to invoke-command scriptblock parameter -name

Powershell: How to pass parameter with invoke-command and -filepath remotely?

这样的东西
Invoke-Command -Command {param($mod, $cmd) Import-Module $mod -Cmdlet $cmd} -Session $ADSession -ArgumentList $mod,$cmd

帮助链接(如果有):