尝试使用 Powershell 删除仅包含一行内容的文件;获取空路径错误

Attempt to remove files that only contain one line of content using Powershell; Getting null Path error

我在测试环境中积累了大量文件,其中大部分只包含 header 行,因此没有有用的信息。当我们想找到有用的数据时,它们会消耗分析资源,所以我想删除它们。

我已经弄清楚如何识别文件名,但是当我随后应用 Remove-Item commandlet 时,会发生以下情况:

 Remove-Item : Cannot bind argument to parameter 'Path' because it is
 null. At line:3 char:44
 +   where-object { $_.lines -eq 1 }).Name  | remove-item -whatif  )
 +                                            ~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
     + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand

这是我编造的Powershell命令..

gci *20210114*X0000002015*CDR.csv -file | % {
   (($_ | select-object -property 'Name', @{ label = 'lines'; expression = { (gc $_ | measure-object -line).lines  } } |
   where-object { $_.lines -eq 1 }).Name  | remove-item -whatif  )
}

如果我删除内部流的最后一部分,'| remove-item -whatif',然后只显示我要删除的两个文件的名称。这意味着逻辑基本上是正确的。

我试过移动'| remove-item' 部分到语法中的其他地方(例如到最后结束后 } ),结果是一样的:它将删除我要删除的文件并为其余部分显示上述错误。

我要么想要一个不会出错的语法,要么想要抑制这个错误,避免在命令 运行.

时分心

OS 是 Windows 10,PS 版本 5.1

此致, 奈杰尔

Remove-Item cmdlet 期望通过 PropertyName 或 Value 绑定其 属性“路径”。这意味着您传入的对象必须是具有路径 属性 的对象或作为文件完整路径的字符串。

您需要将 属性 'Name' 替换为 'FullName'

这里是关于 Remove-Item 的 Path 参数的帮助

Get-Help Remove-Item -Parameter Path

  -Path <System.String[]>
        Specifies a path of the items being removed. Wildcard characters are permitted.

        Required?                    true
        Position?                    0
        Default value                None
        Accept pipeline input?       True (ByPropertyName, ByValue)
        Accept wildcard characters?  true

奈杰尔,

试试这个语法,它对我有用。

(gci -Path "G:\Test\Scripts\*Dev*V*.ps1" -file).FullName  |
  Where-object {((Get-Content $_ | measure-object -line).lines) -gt 20
         } | Remove-Item

当然,根据您的需要更改路径选择信息以及测试和测试值。您还需要将 -Force 参数添加到 Remove-Item 以防某些文件被标记为只读。