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

Aer*_*ght 1 variables powershell 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*aul 8

要么在脚本块的开头声明参数:

   {  
        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
    }
Run Code Online (Sandbox Code Playgroud)

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

#first passed parameter
$args[0]
#second passed parameter
$args[1]
....
Run Code Online (Sandbox Code Playgroud)

文档:MSDN

  • 只要确保你在 `param()` 中的变量与你通过 `-ArgumentList` 传入的变量相匹配。当我的 $computer 一直显示为我的用户 ID 时,我了解到这是一种艰难的方式,哈哈 (2认同)

Moe*_*ald 8

或者,您可以使用$Using:范围.请参见此链接下的示例5 .

例:

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

随着$Using:你并不需要的-ArgumentList参数和param在脚本块的块.