powershell - How do I pass variables with the Invoke-Command cmdlet? -
i have event-logs servers , don't want read in credentials each server found.
i've tried pass variables using argumentlist parameter doesn't work.
this 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 use variables in invoke-command scriptblock?
either declare parameters @ beginning of 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 acces arguments using $args
variable:
#first passed parameter $args[0] #second passed parameter $args[1] ....
documentation: msdn
Comments
Post a Comment