add
add script
This commit is contained in:
1 parent
1c97f2d498
commit
a59992bae8
15 files changed
+1175
No files matched your search
@@ -0,0 +1,293 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
PowerShell-Nachbau des "Intune Network Drive Mapping Tool" (Weatherlights).
|
||||
|
||||
.DESCRIPTION
|
||||
Liest die Laufwerkszuordnungen aus denselben Policy-Keys wie das Original
|
||||
(HKCU\Software\Policies\weatherlights.com\NetworkDriveMapping), damit die
|
||||
bestehende ADMX-/Intune-Konfiguration weiter genutzt werden kann.
|
||||
Fallback: die Liste $FallbackMappings unten.
|
||||
|
||||
Modi:
|
||||
(ohne Parameter) Laufwerke verbinden (läuft im Benutzerkontext)
|
||||
-Install Skript nach C:\ProgramData\DriveMapping kopieren und
|
||||
Aufgabe registrieren (als SYSTEM / Admin ausführen)
|
||||
-Uninstall Aufgabe, Startmenü-Verknüpfung und Skript entfernen
|
||||
-ShowResult Wie ohne Parameter, zeigt am Ende ein Ergebnisfenster
|
||||
(wird von der Startmenü-Verknüpfung genutzt)
|
||||
|
||||
Das Skript schreibt und löscht keine Registry-Werte und fasst nur die
|
||||
konfigurierten Laufwerksbuchstaben an.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Install,
|
||||
[switch]$Uninstall,
|
||||
[switch]$ShowResult
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Einstellungen
|
||||
# ---------------------------------------------------------------------------
|
||||
$PolicyRoot = 'HKCU:\Software\Policies\weatherlights.com\NetworkDriveMapping'
|
||||
$InstallDir = Join-Path $env:ProgramData 'DriveMapping'
|
||||
$TaskName = 'Network Drive Mapping'
|
||||
$LogFile = Join-Path $env:LOCALAPPDATA 'DriveMapping\DriveMapping.log'
|
||||
# Startmenü für alle Benutzer (C:\ProgramData\Microsoft\Windows\Start Menu\Programs)
|
||||
$ShortcutPath = Join-Path ([Environment]::GetFolderPath('CommonPrograms')) 'Netzlaufwerke verbinden.lnk'
|
||||
|
||||
# Wird nur genutzt, wenn keine Policy-Keys vorhanden sind.
|
||||
# Umgebungsvariablen wie %USERNAME% werden aufgelöst.
|
||||
$FallbackMappings = @(
|
||||
# @{ Letter = 'H'; Path = '\\fileserver\home$\%USERNAME%' }
|
||||
# @{ Letter = 'S'; Path = '\\fileserver\shares' }
|
||||
)
|
||||
|
||||
$Defaults = @{
|
||||
Persistent = $false # MapPersistent
|
||||
RetryCount = 10 # Anzahl Versuche, bis der Server erreichbar ist
|
||||
RetryDelaySec = 6 # Wartezeit zwischen Versuchen
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Hilfsfunktionen
|
||||
# ---------------------------------------------------------------------------
|
||||
function Write-Log {
|
||||
param([string]$Message, [ValidateSet('INFO','WARN','ERROR')][string]$Level = 'INFO')
|
||||
$dir = Split-Path $LogFile
|
||||
if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
|
||||
if ((Test-Path $LogFile) -and (Get-Item $LogFile).Length -gt 1MB) {
|
||||
Move-Item $LogFile "$LogFile.old" -Force
|
||||
}
|
||||
"{0:yyyy-MM-dd HH:mm:ss} [{1}] {2}" -f (Get-Date), $Level, $Message | Add-Content -Path $LogFile -Encoding UTF8
|
||||
}
|
||||
|
||||
function Show-Result {
|
||||
# Nur bei manuellem Start über die Verknüpfung (-ShowResult)
|
||||
param([string]$Text, [switch]$IsError)
|
||||
if (-not $ShowResult) { return }
|
||||
$icon = if ($IsError) { 48 } else { 64 } # 48 = Warnung, 64 = Info
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
[void]$shell.Popup($Text, 30, 'Netzlaufwerke', $icon) # schließt nach 30 s von selbst
|
||||
}
|
||||
|
||||
function Get-PolicyValue {
|
||||
param([string]$Name, $Default)
|
||||
$v = (Get-ItemProperty -Path $PolicyRoot -Name $Name -ErrorAction SilentlyContinue).$Name
|
||||
if ($null -eq $v) { $Default } else { $v }
|
||||
}
|
||||
|
||||
function Get-DriveMappings {
|
||||
$list = @()
|
||||
|
||||
# Neues Format (ADMX >= 1.3.2.0): ...\Policies2\<Buchstabe> mit Path/Username/Password
|
||||
$p2 = Join-Path $PolicyRoot 'Policies2'
|
||||
if (Test-Path $p2) {
|
||||
foreach ($key in Get-ChildItem $p2) {
|
||||
$props = Get-ItemProperty $key.PSPath
|
||||
if ($props.Path) {
|
||||
$list += [pscustomobject]@{
|
||||
Letter = $key.PSChildName.TrimEnd(':').ToUpper()
|
||||
Path = $props.Path
|
||||
Username = $props.Username
|
||||
Password = $props.Password
|
||||
}
|
||||
}
|
||||
}
|
||||
return $list
|
||||
}
|
||||
|
||||
# Altes Format: ...\Policies, Werte "Buchstabe;Pfad[;User;Passwort]"
|
||||
$p1 = Join-Path $PolicyRoot 'Policies'
|
||||
if (Test-Path $p1) {
|
||||
$item = Get-Item $p1
|
||||
foreach ($name in $item.GetValueNames()) {
|
||||
$parts = ([string]$item.GetValue($name)).Split(';')
|
||||
if ($parts.Count -ge 2) {
|
||||
$list += [pscustomobject]@{
|
||||
Letter = $parts[0].TrimEnd(':').ToUpper()
|
||||
Path = $parts[1]
|
||||
Username = if ($parts.Count -ge 4) { $parts[2] } else { $null }
|
||||
Password = if ($parts.Count -ge 4) { $parts[3] } else { $null }
|
||||
}
|
||||
}
|
||||
}
|
||||
return $list
|
||||
}
|
||||
|
||||
# Fallback
|
||||
foreach ($m in $FallbackMappings) {
|
||||
$list += [pscustomobject]@{ Letter = $m.Letter.ToUpper(); Path = $m.Path; Username = $m.Username; Password = $m.Password }
|
||||
}
|
||||
return $list
|
||||
}
|
||||
|
||||
function Test-SmbReachable {
|
||||
param([string]$Server, [int]$TimeoutMs = 2000)
|
||||
$client = New-Object System.Net.Sockets.TcpClient
|
||||
try {
|
||||
$ar = $client.BeginConnect($Server, 445, $null, $null)
|
||||
if ($ar.AsyncWaitHandle.WaitOne($TimeoutMs) -and $client.Connected) { return $true }
|
||||
return $false
|
||||
} catch { return $false }
|
||||
finally { $client.Close() }
|
||||
}
|
||||
|
||||
function Get-CurrentMappings {
|
||||
# Liefert Hashtable Buchstabe -> UNC-Pfad der aktuell verbundenen Laufwerke
|
||||
$result = @{}
|
||||
$net = New-Object -ComObject WScript.Network
|
||||
$drives = $net.EnumNetworkDrives()
|
||||
for ($i = 0; $i -lt $drives.Count(); $i += 2) {
|
||||
$letter = $drives.Item($i).TrimEnd(':').ToUpper()
|
||||
if ($letter) { $result[$letter] = $drives.Item($i + 1) }
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Installation / Deinstallation (als SYSTEM bzw. Admin, z. B. Intune-Plattformskript)
|
||||
# ---------------------------------------------------------------------------
|
||||
if ($Install) {
|
||||
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
|
||||
$target = Join-Path $InstallDir 'Invoke-DriveMapping.ps1'
|
||||
Copy-Item -Path $PSCommandPath -Destination $target -Force
|
||||
|
||||
# Ohne sichtbares Fenster: conhost --headless (Win10 21H2+/Win11), sonst Fallback
|
||||
$psArgs = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$target`""
|
||||
$conhost = Join-Path $env:windir 'System32\conhost.exe'
|
||||
$action = New-ScheduledTaskAction -Execute $conhost -Argument "--headless powershell.exe $psArgs"
|
||||
|
||||
# Trigger 1: Anmeldung (jeder Benutzer)
|
||||
$tLogon = New-ScheduledTaskTrigger -AtLogOn
|
||||
$tLogon.Delay = 'PT15S'
|
||||
|
||||
# Trigger 2: Netzwerkverbindung hergestellt (NetworkProfile, Event 10000)
|
||||
$cls = Get-CimClass -Namespace Root/Microsoft/Windows/TaskScheduler -ClassName MSFT_TaskEventTrigger
|
||||
$tNet = New-CimInstance -CimClass $cls -ClientOnly
|
||||
$tNet.Enabled = $true
|
||||
$tNet.Delay = 'PT10S'
|
||||
$tNet.Subscription = '<QueryList><Query Id="0" Path="Microsoft-Windows-NetworkProfile/Operational"><Select Path="Microsoft-Windows-NetworkProfile/Operational">*[System[EventID=10000]]</Select></Query></QueryList>'
|
||||
|
||||
# Läuft im Kontext des angemeldeten Benutzers (Gruppe "Benutzer", SID-basiert = sprachunabhängig)
|
||||
$principal = New-ScheduledTaskPrincipal -GroupId 'S-1-5-32-545' -RunLevel Limited
|
||||
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
|
||||
-ExecutionTimeLimit (New-TimeSpan -Minutes 10) -MultipleInstances IgnoreNew -StartWhenAvailable
|
||||
|
||||
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger @($tLogon, $tNet) `
|
||||
-Principal $principal -Settings $settings -Force | Out-Null
|
||||
|
||||
# Startmenü-Verknüpfung: startet das Skript im Benutzerkontext mit Ergebnisfenster
|
||||
$wsh = New-Object -ComObject WScript.Shell
|
||||
$lnk = $wsh.CreateShortcut($ShortcutPath)
|
||||
$lnk.TargetPath = $conhost
|
||||
$lnk.Arguments = "--headless powershell.exe $psArgs -ShowResult"
|
||||
$lnk.WorkingDirectory = $InstallDir
|
||||
$lnk.IconLocation = "$env:SystemRoot\System32\shell32.dll,9"
|
||||
$lnk.Description = 'Netzlaufwerke erneut verbinden'
|
||||
$lnk.Save()
|
||||
|
||||
Write-Output "Installiert: $target, Aufgabe '$TaskName' registriert, Verknüpfung $ShortcutPath angelegt."
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Uninstall) {
|
||||
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue
|
||||
Remove-Item -Path $ShortcutPath -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item -Path $InstallDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Write-Output "Aufgabe '$TaskName', Verknüpfung und $InstallDir entfernt."
|
||||
exit 0
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Laufwerke verbinden (Benutzerkontext)
|
||||
# ---------------------------------------------------------------------------
|
||||
$enabled = Get-PolicyValue -Name 'Enabled' -Default $null
|
||||
if ($null -ne $enabled -and [int]$enabled -eq 0) {
|
||||
Write-Log 'Policy "Enabled" = 0, nichts zu tun.'
|
||||
Show-Result 'Die Laufwerkszuordnung ist für dieses Gerät deaktiviert.' -IsError
|
||||
exit 0
|
||||
}
|
||||
|
||||
$persistent = [bool][int](Get-PolicyValue -Name 'MapPersistent' -Default ([int]$Defaults.Persistent))
|
||||
$retryCount = [int](Get-PolicyValue -Name 'RetryCount' -Default $Defaults.RetryCount)
|
||||
$mappings = @(Get-DriveMappings)
|
||||
|
||||
if ($mappings.Count -eq 0) {
|
||||
Write-Log 'Keine Laufwerkszuordnungen konfiguriert.' 'WARN'
|
||||
Show-Result "Es sind keine Netzlaufwerke konfiguriert.`nBitte an die IT wenden, falls Laufwerke fehlen." -IsError
|
||||
exit 0
|
||||
}
|
||||
|
||||
Write-Log "Start: $($mappings.Count) Zuordnung(en), Persistent=$persistent, Benutzer=$env:USERNAME"
|
||||
$net = New-Object -ComObject WScript.Network
|
||||
$done = [System.Collections.Generic.List[string]]::new() # für das Ergebnisfenster
|
||||
$skipped = [System.Collections.Generic.List[string]]::new()
|
||||
$pending = [System.Collections.Generic.List[object]]::new()
|
||||
$mappings | ForEach-Object { $pending.Add($_) }
|
||||
|
||||
for ($attempt = 1; $attempt -le $retryCount -and $pending.Count -gt 0; $attempt++) {
|
||||
$current = Get-CurrentMappings
|
||||
|
||||
foreach ($m in @($pending)) {
|
||||
$path = [Environment]::ExpandEnvironmentVariables($m.Path).TrimEnd('\')
|
||||
$drive = "$($m.Letter):"
|
||||
|
||||
# Bereits korrekt verbunden?
|
||||
if ($current.ContainsKey($m.Letter) -and $current[$m.Letter].TrimEnd('\') -ieq $path) {
|
||||
Write-Log "$drive ist bereits mit $path verbunden."
|
||||
$done.Add("$drive $path")
|
||||
[void]$pending.Remove($m)
|
||||
continue
|
||||
}
|
||||
|
||||
$server = ($path -replace '^\\\\', '').Split('\')[0]
|
||||
if (-not (Test-SmbReachable -Server $server)) {
|
||||
Write-Log "Versuch $attempt/${retryCount}: $server (445) nicht erreichbar, $drive wird später erneut versucht." 'WARN'
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
# Nur den eigenen Buchstaben trennen, wenn er auf ein anderes Ziel zeigt
|
||||
if ($current.ContainsKey($m.Letter)) {
|
||||
Write-Log "$drive zeigt auf $($current[$m.Letter]), wird getrennt."
|
||||
$net.RemoveNetworkDrive($drive, $true, $true)
|
||||
}
|
||||
elseif (Test-Path "$drive\") {
|
||||
Write-Log "$drive ist durch ein lokales Laufwerk belegt, übersprungen." 'ERROR'
|
||||
$skipped.Add("$drive durch ein lokales Laufwerk belegt")
|
||||
[void]$pending.Remove($m)
|
||||
continue
|
||||
}
|
||||
|
||||
if ($m.Username -and $m.Password) {
|
||||
$net.MapNetworkDrive($drive, $path, $persistent, $m.Username, $m.Password)
|
||||
} else {
|
||||
$net.MapNetworkDrive($drive, $path, $persistent)
|
||||
}
|
||||
Write-Log "$drive -> $path verbunden."
|
||||
$done.Add("$drive $path")
|
||||
[void]$pending.Remove($m)
|
||||
}
|
||||
catch {
|
||||
Write-Log "Fehler beim Verbinden von $drive -> ${path}: $($_.Exception.Message)" 'ERROR'
|
||||
}
|
||||
}
|
||||
|
||||
if ($pending.Count -gt 0 -and $attempt -lt $retryCount) { Start-Sleep -Seconds $Defaults.RetryDelaySec }
|
||||
}
|
||||
|
||||
foreach ($m in $pending) { $skipped.Add("$($m.Letter): Server nicht erreichbar oder Fehler") }
|
||||
|
||||
$msg = ''
|
||||
if ($done.Count -gt 0) { $msg += "Verbunden:`n " + ($done -join "`n ") + "`n`n" }
|
||||
if ($skipped.Count -gt 0) { $msg += "Nicht verbunden:`n " + ($skipped -join "`n ") + "`n`nIm Büro oder per VPN erneut versuchen. Log: $LogFile" }
|
||||
|
||||
if ($pending.Count -gt 0) {
|
||||
Write-Log "Nicht verbunden: $(($pending | ForEach-Object { $_.Letter + ':' }) -join ', ')" 'ERROR'
|
||||
Show-Result $msg.Trim() -IsError
|
||||
exit 1
|
||||
}
|
||||
Write-Log 'Fertig.'
|
||||
Show-Result $msg.Trim() -IsError:($skipped.Count -gt 0)
|
||||
exit 0
|
||||
Binary file not shown.
Reference in new issue
Block a user