我对此非常好奇,因为它花了我一段时间,但我无法弄清楚
首先,我运行以下脚本来获取目录中的所有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 - 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\$serverName\2016-08-30_21-15-17_server-1.1.20558_client-1.1.20518 - Copy (2).zip" -ErrorAction Stop
答案 0 :(得分:2)
您的问题是在引用的字符串中使用'$ 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 ...
,而不是使用Name$entryList.Add($_.FullName)
享受。
答案 1 :(得分:1)
Kory Gill是对的。当您在由双引号括起的字符串中引用字符串数组时,您需要在数组名称前添加$(
,之后添加)
。所以,
Write-Host "This is a $test[0]"
不会给你想要的结果。下面将正确获取数组中的字符串并插入字符串。
WRite-Host "This is a $($test[0])"
这是我第一次开始使用PowerShell时遇到的一些“小问题”。