使用 powershell 处理网络使用错误消息 [英] handling net use error messages with powershell

查看:61
本文介绍了使用 powershell 处理网络使用错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的 net use 命令来映射网络驱动器

I'm using a simple net use command to map a network drive

net use \\$HOSTIP $PASSWD /user:$UNAME

我必须使用 net use 而不是 New-PSDrive,因为脚本在多个实例中运行超过 400 台机器,而且不可行.我想过滤错误信息然后 net use return like

i must use net use instead of of New-PSDrive because the scripts runs for more then 400 machines in multiple instances and just wouldn't be doable. I want to filter the error message then net use return like

System error 64 has occurred.

System error 67 has occurred.

我该怎么做?

推荐答案

您可以执行以下操作:

#set process startup info (redirect stderr)
$pinfo = new-object System.Diagnostics.ProcessStartInfo
$pinfo.Filename = "net.exe"
$pinfo.UseShellExecute = $false
$pinfo.Arguments = @("use","\\$($HOSTIP)","$($PASSWD)","/user:$($UNAME)")
$pinfo.redirectstandardError = $true
#start process and wait for it to exit
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.start() | out-null
$p.waitforexit()
#check the returncode
if($p.exitcode -ne 0){
    #rc != 0 so we grab the stderr output
    $err = $p.standardError.ReadToEnd()
    #first line of the output contains the string from your question, matching it against regex
    if($err[0] -match "System error ([0-9]*) has occurred"){
        #switching the error code
        switch($Matches[1]){
            64 {do-something64;break;}
            67 {do-something67;break;}
        }
    }
}

这应该可以解决问题,尽管我无法说明它的性能如何,但您必须尝试.如果输出可能与您在问题中发布的字符串不同,您将必须编写自己的正则表达式来处理它们.

This should do the trick, although i cant make a statement about how performant it is, you will have to try. If the output can differ from the string you posted in your question you will have to write your own regexes to handle them.

请记住,net 的输出是本地化的,因此我示例中的正则表达式在系统语言不是英语的系统上不起作用.

Keep in mind that the output from net is localized so the regex in my example will not work on systems where the system language is not english.

希望有帮助

这篇关于使用 powershell 处理网络使用错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆