CmdLets/Master/Connect-Fileshares.ps1
|
Function Connect-Fileshares { <# .SYNOPSIS Connects to specified network file shares and maps them as persistent global PowerShell drives. .DESCRIPTION The Connect-Fileshares function iterates through a collection of file share configurations, authenticates using provided or prompted credentials, and maps them as persistent global PSDrives using New-PSDrive. It features a retry mechanism via a Do-While loop if authentication fails, and automatically logs successful connection details into a session-scoped state tracker object ($State). .PARAMETER FileShares An optional collection or array of custom objects defining the file shares. Each file share object typically contains the following properties: - Name: The drive letter or name for the PSDrive (e.g., "Z"). - Root: The UNC path to the network share (e.g., "\\server\share"). - Username: (Optional) The account username for authentication. - Password: (Optional) The plain-text password corresponding to the username. .EXAMPLE $Shares = @( [PSCustomObject]@{ Name = "Z"; Root = "\\fileserver01\corp"; Username = ""; Password = "" } ) Connect-Fileshares -FileShares $Shares Description: Connects to the specified corporate file share and interactively prompts for credentials if they are blank. .NOTES Prerequisites: - Requires an existing session-level or global `$State` variable if you wish to track connected shares. - Requires network access to the target file shares. .LINK https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-psdrive #> [CmdletBinding()] Param( [Parameter(Mandatory=$False)] $FileShares ) $Shares = @() ForEach ($FileShare in $FileShares) { Write-Host $FileShare.Root If ($FileShare.Username -ne ""){ $Cred = New-Object System.Management.Automation.PSCredential ($FileShare.Username, (ConvertTo-SecureString $FileShare.Password -AsPlainText -Force)) } Do { if (!$cred) { Write-Host "Please enter the credential to connect to the File share" -ForegroundColor Yellow $cred = Get-Credential -Message "<username>@<domain>" -UserName $FileShare.UserName } try { If (!(Get-PSDrive -Name $FileShare.Name -ErrorAction SilentlyContinue)) { New-PSDrive -PSProvider FileSystem -Root $FileShare.Root -Name $FileShare.Name -Credential $Cred -Persist -Scope Global } } catch { Write-Error $_ } finally { if (!(Get-PSDrive -Name $FileShare.Name -ErrorAction SilentlyContinue)) {$Cred = $null} } } While (!(Get-PsDrive -Name $Fileshare.Name -ErrorAction SilentlyContinue)) $Shares += @{Name=$FileShare.Name; Root=$FileShare.Root; UserName=$Cred.Username; Password=$Cred.GetNetworkCredential().Password} } $Shares = ($Shares | ConvertTo-JSON) | ConvertFrom-Json If (!($State.Shares) -and $Shares.Count -gt 0) { $State | Add-Member -NotePropertyName "Shares" -NotePropertyValue $Shares } elseif ($Shares.Count -gt 0) { $State.Shares = $Shares } } |