Created
September 1, 2017 10:51
-
-
Save absolutejam/da8cf3b4c3b1129f6cab517097c0668c to your computer and use it in GitHub Desktop.
Remove-LongFolderPath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Remove-LongFolderPath { | |
[CmdletBinding()] | |
Param( | |
[Parameter( | |
Mandatory = $True | |
)] | |
[string]$Path, | |
[switch]$Force | |
) | |
if (!(Test-Path -Path $Path)) { | |
Throw "$Path is not a valid path" | |
} | |
$PSDriveName = 'LongFolderPathTmp' | |
$PathRoot = Split-Path -Path $Path | |
$PathTarget = Split-Path -Leaf -Path $Path | |
$CurrentLocation = Get-Location | |
Try { | |
# Map the drive | |
$PSDrive = New-PSDrive -Name $PSDriveName -PSProvider FileSystem -Root $PathRoot -Description "Temporary PSDrive use to circumvent max file path issue" | |
# Jump into the drive | |
Set-Location -Path "$($PSDrive):" | |
# Delete the item using the mapped drive | |
$RemoveArgs = @{ | |
'Path' = ".\$PathTarget" | |
'Recurse' = $True | |
'Confirm' = $True | |
} | |
if ($Force) { | |
$RemoveArgs['Force'] = $False | |
$RemoveArgs['Confirm'] = $False | |
} | |
Remove-Item @RemoveArgs | |
} catch { | |
Write-Error -Message $_.Exception.Message | |
} finally { | |
# Go back to previous location | |
Set-Location -Path $CurrentLocation | |
# Remove the drive | |
if (Get-PSDrive $PSDriveName -ErrorAction SilentlyContinue) { | |
Remove-PSDrive -Name $PSDriveName | |
} | |
} | |
} | |
Remove-LongFolderPath -Path "\\server\share\one\two\three\four" -Force | |
$Folders = ( | |
'\\server\share\path1', | |
'\\server\share\path2', | |
'\\server\share\path3' | |
) | |
ForEach ($Folder in $Folders) { | |
Remove-LongFolderPath -Path $Folder -Force | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment