Catch net use exception in powershell -


i having difficulty catch net use exception in powershell.

foreach ($k in $file){          try{             net use \\$k\share $password /user:$username > null              copy-item d:\setup.exe \\$k\share              net use \\$k\share /delete > null              write-host "copied file \\$k\share"          }         catch [system.exception]{             continue         }  } 

if script cannot authenticate machine, want script silently continue, instead following error

net : system error 1326 has occurred. @ d:\script\log_into.ps1:25 char:17 +                 net use \\$k\share $password /user:$username > null +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + categoryinfo          : notspecified: (system error 1326 has occurred.:string) [], remoteexception     + fullyqualifiederrorid : nativecommanderror  user name or password incorrect. net : network connection not found. @ d:\script\log_into.ps1:27 char:17 +                 net use \\$k\share /delete > null +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + categoryinfo          : notspecified: (the network con...d not found.:string) [], remoteexception     + fullyqualifiederrorid : nativecommanderror 

map drive using powershell cmdlets instead can capture exceptions properly.

this work powershell 3.0 , newer, there's bug -credential parameter in older versions (it doesn't work). if need v2 compatibility, post comment & i'll update.

$userpass = convertto-securestring "password" -asplaintext -force $credential = new-object -typename system.management.automation.pscredential -argumentlist $username, $userpass  foreach ($k in $file){          try{             new-psdrive -name z -psprovider filesystem -root \\$k\share -credential $credential;             copy-item d:\setup.exe z:\             remove-psdrive -name z             write-host "copied file \\$k\share"          }         catch [system.exception]{             continue         }  } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -