How do I pass variables with the Invoke-Command cmdlet?

半腔热情 提交于 2019-12-17 02:52:06

问题


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.

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

This is my code:

$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
        }
    }
}

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


回答1:


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
    }

Or you acces your arguments using the $args variable:

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

Documentation: MSDN




回答2:


Alternatively you can use the $Using:scope. See Example 5 under this link.

Example:

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

With $Using: you don't need the -ArgumentList parameter and the param block in the scriptblock.



来源:https://stackoverflow.com/questions/36328690/how-do-i-pass-variables-with-the-invoke-command-cmdlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!