Public/Add-specDriveMap.ps1
Function Add-specDriveMap { <# .SYNOPSIS Maps a network drive using New-PSDrive. .DESCRIPTION The Add-specDriveMap function maps a network drive using the New-PSDrive cmdlet. .PARAMETER Drive Specifies the drive letter for mapping. Type the drive letter as a string. .PARAMETER UNCPath Specifies the UNC path of the network location to map the drive to. Type the UNC path as a string. .PARAMETER User Specifies the username for authentication if required. Type the username as a string. .PARAMETER Password Specifies the password for authentication if required. Type the password as a string. .EXAMPLE Add-specDriveMap -Drive 'N:' -UNCPath '\\Server\Share' Maps drive 'N:' to the UNC path '\\Server\Share'. .EXAMPLE Add-specDriveMap -Drive 'Z:' -UNCPath '\\AnotherServer\AnotherShare' -User 'Username' -Password 'Password' Maps drive 'Z:' to the UNC path '\\AnotherServer\AnotherShare' using specified credentials. .NOTES Prerequisites: Get-specPSCredential Author: owen.heaume Version: 1.0 #> [cmdletbinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)] [ValidateLength(1, 2)] [alias ('Drive')] [alias('RowKey')] [string]$DriveLetter, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)] [ValidateNotNullOrEmpty()] [alias('Path')] [alias('RemotePath')] [string]$UNCPath, [Parameter( Mandatory = $false, ValueFromPipelineByPropertyName = $true, Position = 2)] [alias('UserName')] [string]$User, [Parameter( Mandatory = $false, ValueFromPipelineByPropertyName = $true, Position = 3)] [alias('PW')] [string]$Password ) BEGIN {} Process { foreach ($letter in $DriveLetter) { # if the drive letter ends in a colon, then remove it if ($letter[-1] -eq ':') { $letter = $letter.TrimEnd(':') } if ($password) { try { # create a PSCredential object from the username and password $Pscredential = Get-specPSCredential -User $user -Password $password Write-Host "Mapping drive $($letter) to $($UNCPath)" -ForegroundColor DarkCyan if ($pscmdlet.shouldprocess($letter, 'New-PSDrive')) { new-psdrive -Name $letter -PSProvider FileSystem -Root $UNCPath -Scope global -Persist -Credential $Pscredential -ea stop } Write-Host "OK`n" -ForegroundColor DarkGreen } catch { Write-Warning -Message "Failed to map drive $letter to $UNCPath. The error was $($_.Exception.Message)" } } else { try { Write-Host "Mapping drive $($letter) to $($UNCPath)" -ForegroundColor DarkCyan if ($pscmdlet.shouldprocess($letter, 'New-PSDrive')) { new-psdrive -Name $letter -PSProvider FileSystem -Root $UNCPath -Scope global -Persist -ea stop } Write-Host "OK`n" -ForegroundColor DarkGreen } catch { Write-Warning -Message "Failed to map drive $letter to $UNCPath. The error was $($_.Exception.Message)" } } } } } |