如何使用 Invoke-Command cmdlet 传递变量? [英] How do I pass variables with the Invoke-Command cmdlet?

查看:55
本文介绍了如何使用 Invoke-Command cmdlet 传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to get Event-Logs from some servers and I don't want to read in the credentials for each server which is found.

我尝试使用 ArgumentList 参数传递我的变量,但我不起作用.

I've tried to pass my variables by using the ArgumentList parameter but I doesn't work.

这是我的代码:

$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 中的变量?

How can I use the variables in the Invoke-Command ScriptBlock?

推荐答案

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

Either you declare the parameters at the beginning of your 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 变量访问您的参数:

Or you acces your arguments using the $args variable:

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

文档:MSDN

这篇关于如何使用 Invoke-Command cmdlet 传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆