简体   繁体   English

使用PowerShell 2.0进行映射的驱动器监视

[英]Mapped drive monitoring using PowerShell 2.0

I'm writing a PowerShell 2.0 script to monitor and reconnect network drives that should be mapped. 我正在编写PowerShell 2.0脚本,以监视和重新连接应映射的网络驱动器。 It works...mostly. 主要... Once a drive is determined to be disconnected my logon script (ptt.vbs) is run and the drives are remapped. 确定驱动器已断开连接后,将运行我的登录脚本(ptt.vbs)并重新映射驱动器。 However, after that it continues to see that particular drive letter as disconnected even though it got remapped. 但是,此后,即使重新映射到特定驱动器号,它仍会看到该驱动器号已断开连接。

while($true) {
  $disconnectedDrives = @()
  $mappedDrives = 'J:', 'R:', 'S:', 'W:'
  foreach ($drive in $mappedDrives) {
    if (-Not (Test-Path $drive)) {
      $disconnectedDrives += $drive
    }
  }
  if ($disconnectedDrives) {
    Write-Host "$disconnectedDrives not mapped."
    Write-Eventlog -LogName 'Windows PowerShell' -Category 3 -source PowerShell -eventID 601 -EntryType Error -message "$disconnectedDrives OFFLINE and not available."
    \\dc1\NETLOGON\ptt.vbs
  }
  Start-Sleep 1
}

Any ideas what I'm doing wrong? 有什么想法我做错了吗?

To me the mix of VBS and Powershell is suspicious. 对我来说,VBS和Powershell的组合是可疑的。

But at least a would take a differnt way. 但是至少a会采取不同的方式。 First create a central file whch includes the network drive configuration. 首先创建一个包含网络驱动器配置的中央文件。 For example "\\dc1\\NETLOGON\\ptt.csv" can look like this ... 例如,“ \\ dc1 \\ NETLOGON \\ ptt.csv”看起来像这样...

J;\\srv1\shareA
R;\\srv1\shareB
S;\\srv2\shareA
W;\\srv2\shareB

This is the script ... 这是脚本...

$Local:LogicalDiskStatus  = New-Object -TypeName 'System.Collections.Generic.Dictionary[string,System.Management.ManagementObject]'

$Local:NetDrvConf_Path    = "\\dc1\NETLOGON\ptt.csv"
$Local:NetDrvConf_List    = @()
$Local:NetDrvConf_DrvType = [UInt32]4

$Local:WshNetworkObj      = New-Object -ComObject WScript.Network

while($true) {
    # adding the logical disk status to a list indexed by DeviceID 
    $LogicalDiskStatus.Clear()
    Get-WmiObject -Class "Win32_LogicalDisk" | ForEach-Object { $LogicalDiskStatus.Add((($_.DeviceID) -replace ":"), $_) }

    if (!($NetDrvConf_List.Count)) {
        Try {
            $NetDrvConf_List.Clear()
            $NetDrvConf_List = Import-Csv -Path $NetDrvConf_Path -Delimiter ";"         
        }
        Catch [System.Exception] {
            $Local:ErrorMsg = ("Cannot load network drive configuration file `"{0}`".  Error message: {1}" -f $NetDrvConf_Path, ($_.Exception.Message))
            Write-Host $ErrorMsg -ForegroundColor red
            Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 601 -EntryType Error -Message $ErrorMsg
        }
    }

    $NetDrvConf_List | ForEach-Object {
        $Local:Current_DriveLetter = ($_.Drive).ToUpper()
        $Local:Current_DriveID     = ("{0}:" -f $Current_DriveLetter)
        $Local:Current_UNCPath     = $_.UNCPath

        Write-Host ("Check configuration:  {0}  {1}" -f $Current_DriveID, $Current_UNCPath)

        # drive in use?
        if ( ($LogicalDiskStatus.ContainsKey($Current_DriveLetter)) ) {
            # drive is a network drive?
            if (!(($LogicalDiskStatus.$Current_DriveLetter.DriveType).Equals($NetDrvConf_DrvType))) {
                $Local:ErrorMsg = ("Drive `"{0}`" is already in use, but not as a network drive!  The current drive type is `"{1}`" not `"4`"." -f $Current_DriveID, ($LogicalDiskStatus.$Current_DriveLetter.DriveType) )
                Write-Host $ErrorMsg -ForegroundColor red
                Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 602 -EntryType Error -Message $ErrorMsg
            # drive is NOT to the expected UNC path?
            } elseif (!(($LogicalDiskStatus.$Current_DriveLetter.ProviderName).Equals($Current_UNCPath))) {
                Try {
                    Write-Host ("Network drive `"{0}`" unexpectedly connected to `"{1}`".  Trying to disconnect." -f $Current_DriveID, ($LogicalDiskStatus.$Current_DriveLetter.ProviderName)) -ForegroundColor yellow
                    $WshNetworkObj.RemoveNetworkDrive($Current_DriveID, $true, $true)
                    Write-Host ("=> successfully disconnected.") -ForegroundColor green
                }
                Catch [System.Exception] {
                    $Local:ErrorMsg = ("Error disconnecting `"{0}`".  Connected to `"{1}`".  Error message: {2}" -f $Current_DriveID, $Current_UNCPath, ($_.Exception.InnerException) )
                    Write-Host $ErrorMsg -ForegroundColor red
                    Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 603 -EntryType Error -Message $ErrorMsg
                }
            } else {
                Write-Host "=> correct connected" -ForegroundColor green
            }
        }

        # drive is unused?
        if (!(((Get-PSProvider -PSProvider FileSystem).Drives.Name).Contains($Current_DriveLetter))) {
            Try {
                Write-Host ("Connecting network drive `"{0}`" to `"{1}`"." -f $Current_DriveID, $Current_UNCPath) -ForegroundColor yellow
                $WshNetworkObj.MapNetworkDrive($Current_DriveID, $Current_UNCPath, $true)
                Write-Host ("=> successfully connected.") -ForegroundColor green
            }
            Catch [System.Exception] {
                $Local:ErrorMsg = ("Error connecting `"{0}`" to `"{1}`". Error message: {2}" -f $Current_UNCPath, $Current_DriveID, ($_.Exception.InnerException) )
                Write-Host $ErrorMsg -ForegroundColor red
                Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 604 -EntryType Error -Message $ErrorMsg
            }
        }
    }

    Start-Sleep -Seconds 1
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM