mhouston100 mhouston100 - 1 year ago 150
PowerShell Question

Powershell - Delete directory regardless of 260 char limit

I'm writing a simple script to delete USMT migration folders after a certain amount of days:

## Server List ##
$servers = "Delorean","Adelaide","Brisbane","Melbourne","Newcastle","Perth"

## Number of days (-3 is over three days ago) ##
$days = -3

$timelimit = (Get-Date).AddDays($days)

foreach ($server in $servers)
$deletedusers = @()
$folders = Get-ChildItem \\$server\USMT$ | where {$_.psiscontainer}
write-host "Checking server : " $server
foreach ($folder in $folders)
If ($folder.LastWriteTime -lt $timelimit -And $folder -ne $null)
$deletedusers += $folder
Remove-Item -recurse -force $folder.fullname
write-host "Users deleted : " $deletedusers

However I keep hitting the dreaded
Remove-Item : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

I've been looking at workarounds and alternatives but they all revolve around me caring what is in the folder.

I was hoping for a more simple solution as I don't really care about the folder contents if it is marked for deletion.

Is there any native Powershell cmdlet other than Remove-Item -recurse that can accomplish what I'm after?

Answer Source

This is a known limitation of PowerShell. The work around is to use dir cmd (sorry, but this is true).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download