pf-psDrive.ps1
function Initialize-PSDrive ($DriveName, $Root, $Credential) { $psDriveParams = @{Credential = $Credential; Root = $Root} $psDriveParams = $psDriveParams | Remove-EmptyValues # gci HKCU:\Network\ | where RemotePath -eq '\\192.168.150.219\c$' # remove-item if (-not $DriveName) { $existing = Get-PSDrive | Where-Object DisplayRoot -eq $Root | Select-Object -First 1 if ( $existing ) { return $existing } $drive = Invoke-Script_InMutexBlock -name 'Initialize-PSDrive' -ArgumentList $psDriveParams -script { $takenDriveLetters = @('A','B','C') $takenDriveLetters += Get-PSDrive | Where-Object { $_.Name.Length -eq 1 } | ForEach-Object { $_.Name } $allLetters = Get-Chars -letters $driveLetter = $allLetters | Where-Object { $_ -notin $takenDriveLetters } | Select-Object -First 1 if (-not $driveLetter) { throw 'No drive letter is available' } $regBasePath = "HKCU:\Network\$driveLetter" if (test-path $regBasePath ) { remove-item $regBasePath -Force } $localpsDriveParams = $args[0] $result = New-PSDrive @localpsDriveParams -Name $driveLetter -PSProvider FileSystem -Scope Global -Persist return $result } return $drive } if ( Get-PSDrive | Where-Object Name -eq $DriveName ) { Remove-PSDrive -Name $DriveName } New-PSDrive -Name $DriveName -PSProvider FileSystem -Credential $Credential -Root $Root -Scope Global } function Initialize-PSDrive:::Example { $drive = Initialize-PSDrive -Root \\196.168.150.130\c$ $drive | Remove-PSDrive } |