如何使用Invoke-Command cmdlet传递变量?

时间:2016-03-31 08:58:19

标签: powershell variables invoke-command

我必须从某些服务器获取事件日志,并且我不想读取找到的每个服务器的凭据。

我试图通过使用ArgumentList参数传递我的变量,但我不起作用。

这是我的代码:

$User = Read-Host -Prompt "Enter Username"
$Password = Read-Host -Prompt "Enter Password" -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Get-ADComputer -Filter "OperatingSystem -Like '*Server*'" | Sort-Object Name |
ForEach-Object{
    if($_.Name -like '*2008*'){
        Invoke-Command -ComputerName $_.Name -ArgumentList $User, $UnsecurePassword -ScriptBlock {  
            net use P: \\Server\dir1\dir2 /persistent:no /user:$User $UnsecurePassword
            Get-EventLog -LogName System -After (Get-Date).AddHours(-12) -EntryType Error, Warning | format-list | 
            out-file P:\EventLog_$env:COMPUTERNAME.log
            net use P: /delete /yes
        }
    }
}

如何在Invoke-Command ScriptBlock中使用变量?

2 个答案:

答案 0 :(得分:8)

或者,您可以使用$Using:范围。请参阅此link下的示例5。

示例:

$servicesToSearchFor = "*"
Invoke-Command -ComputerName $computer -Credential (Get-Credential) -ScriptBlock { Get-Service $Using:servicesToSearchFor }

使用$Using:,您不需要脚本块中的-ArgumentList参数和param块。

答案 1 :(得分:4)

您可以在scriptblock的开头声明参数:

   {  
        param($user,$unsecurepassword)
        net use P: \\Server\dir1\dir2 /persistent:no /user:$User $UnsecurePassword
        Get-EventLog -LogName System -After (Get-Date).AddHours(-12) -EntryType Error, Warning | format-list | 
        out-file P:\EventLog_$env:COMPUTERNAME.log
        net use P: /delete /yes
    }

或者您使用$args变量来访问您的参数:

#first passed parameter
$args[0]
#second passed parameter
$args[1]
....

文档:MSDN

相关问题