powershell - Remove-Item not working when a file name is provided in a variable -
this question has answer here:
i curious took me while couldn't figure out
first, ran following script zip files in dir
$entrylist = new-object system.collections.arraylist get-childitem -path "\\tools-backup.nas\tools-backup\fakes3\rollback\$servername" -erroraction stop | sort -property "lastwritetime" | foreach-object { if($_.name.contains(".zip")) { $entrylist.add($_.name) | out-null } }
it showed below:
2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy - copy.zip 2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy (2).zip 2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy (3).zip 2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy.zip 2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy (6).zip 2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy - copy (2).zip
then tried delete first one(2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy - copy.zip) remove-item this:
remove-item -path "\\tools-backup.nas\tools-backup\fakes3\rollback\$servername\$entrylist[0]" -erroraction stop remove-item : specified path, file name, or both long. qualified file name must less 260 characters, , directory name must less 248 characters. @ line:1 char:1 + remove-item -path "\\tools-backup.nas\tools-backup\fakes3\rollback\$s ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : readerror: (\\toolsbackup....lback\autopatch:string) [remove-item], pathtoolongexception + fullyqualifiederrorid : dirioerror,microsoft.powershell.commands.removeitemcommand
i got path long exception. however, if put file name in "remove-item" instead of passing $entrylist[0], worked
remove-item -path "\\tools-backup.nas\tools-backup\fakes3\rollback\$servername\2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - copy (2).zip" -erroraction stop
your issue using '$entrylist[0]' in quoted string.
run code see how works (or doesn't work)...
$entrylist = new-object system.collections.arraylist $entrylist.add("this entry.") "broken" # string with: entry.[0] write-output "this string with: $entrylist[0]" "fixed1" # string with: entry. write-output "this string with: $($entrylist[0])" # or... "fixed2" # string with: entry. $item = "this string with: {0}" -f $entrylist[0] write-output $item
you can try like:
remove-item -path "\\tools-backup.nas\tools-backup\fakes3\rollback\$servername\$($entrylist[0])" -erroraction stop
also, instead of using name, might refactor code use fullname...
$entrylist.add($_.fullname)
enjoy.
Comments
Post a Comment