在变量中提供文件名时删除项不起作用

Remove-Item not working when a file name is provided in a variable

我对此很好奇,我花了一段时间但我想不通

首先,我运行使用以下脚本获取目录中的所有 Zip 文件

$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
        }
    }

显示如下:

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

然后我尝试删除第一个(2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - 复制 - Copy.zip),像这样删除项目:

Remove-Item -Path "\tools-backup.nas\Tools-Backup\FakeS3\Rollback$serverName$entryList[0]" -ErrorAction Stop

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.
At 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

我遇到路径太长的异常。但是,如果我将文件名放在 "Remove-Item" 中而不是通过 $entryList[0] 传递它,它就起作用了

Remove-Item -Path "\tools-backup.nas\Tools-Backup\FakeS3\Rollback$serverName16-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - Copy (2).zip" -ErrorAction Stop

您的问题是在您引用的字符串中使用“$entryList[0]”。

运行 这个代码看看它是如何工作的(或不工作)...

$entryList = New-Object System.Collections.ArrayList
$entryList.Add("This is an entry.")

"Broken"
# This is a string with: This is an entry.[0]
Write-Output "This is a string with: $entryList[0]"

"Fixed1"
# This is a string with: This is an entry.
Write-Output "This is a string with: $($entryList[0])"

# or...
"Fixed2"
# This is a string with: This is an entry.
$item = "This is a string with: {0}" -f $entryList[0]
Write-Output $item

您可以尝试类似的方法:

Remove-Item -Path "\tools-backup.nas\Tools-Backup\FakeS3\Rollback$serverName$($entryList[0])" -ErrorAction Stop

此外,您可以重构代码以使用 FullName...而不是使用名称...

$entryList.Add($_.FullName)

尽情享受吧。

Kory Gill 是正确的。当您在用双引号括起来的字符串中引用字符串数组时,您需要在数组名称前添加 $(,然后添加 )。所以,

Write-Host "This is a $test[0]"

不会给你想要的结果。下面将正确获取数组中的字符串并插入到字符串中。

WRite-Host "This is a $($test[0])"

当我第一次开始使用 PowerShell 时,正是这些 "gotchas" 中的一个吸引了我。