powershell - 在powershell中捕获网络使用异常

标签 powershell exception error-handling try-catch

我很难在 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/

相关文章:

powershell - 多个powershell开关参数——可以优化吗?

node.js - 在 NodeJS 中优雅地处理子进程中的错误

java - 有异常的接口(interface)扩展无异常的接口(interface)

sql-server - 替换 SQL Server 中的单引号

php - 使用ajax更新数据库-处理错误

powershell - 是否可以创建用户定义的 PowerShell 环境?

powershell - 在其他用户的当前用户存储上安装证书

powershell - 如何在 PowerShell 中创建 Outlook 约会/ session ?

java - PHP exec() 不接受 java 类路径

python - 我收到一个IndentationError。我如何解决它?