我很难在 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 to \\$k\share"
}
catch [System.Exception]{
continue
}
}
如果脚本无法通过计算机进行身份验证,我希望脚本以静默方式继续,但我收到以下错误
net : System error 1326 has occurred.
At 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
The user name or password is incorrect.
net : The network connection could not be found.
At D:\Script\log_into.ps1:27 char:17
+ net use \\$k\share /delete > null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The network con...d not be found.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
最佳答案
使用 PowerShell cmdlet 映射驱动器,以便您可以正确捕获任何异常。
这仅适用于 PowerShell 3.0 及更高版本,因为旧版本中的 -Credential
参数存在错误(它根本不起作用)。如果您需要 v2 兼容性,请发表评论,我会更新。
$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 to \\$k\share"
}
catch [System.Exception]{
continue
}
}
关于powershell - 在powershell中捕获网络使用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25366740/