路径中的 Get-Childitem 和方括号 [] -- 或:LiteralPath + Asterisk

Get-Childitem and brackets [] in path -- or: LiteralPath + Asterisk

我正在尝试对 LiteralPath 使用通配符 (*),这样我的代码也可以在带括号的路径上工作。

目前,我的代码没有出现错误,但它也不会删除有问题的文件。

$path="f:\test\test[lala] lulu\file.rar"
$remfile=$(get-childitem -LiteralPath $path )
$remove = $remfile.fullname.substring(0,$($remfile.fullname).length -3)
get-childitem $($remove + '*') | remove-item -force 

remove 行中,我删除了名称的最后 3 个字符。到目前为止,还不错:

write-output $remove
F:\test\test[lala] lulu\file.

最后一行在搜索字符串中添加了一个星号,它没有给我一个错误,但它也没有删除任何内容。

在最后一行的 GCI 中添加另一个 LiteralPath 会出现错误,因为星号未用作通配符。

我怎样才能做到这一点?

这是一个技巧。 -filter 不将括号理解为通配符,即使在 PS 6.

中也是如此
get-childitem -filter file[*] | remove-item -whatif

编辑:哦,这是一个目录。怎么样:

 get-childitem -LiteralPath 'F:\test\test[lala] lulu\' -filter file* | remove-item -WhatIf

或者,如果您已经在 F: 驱动器上:

get-childitem -filter 'test\test[lala] lulu\file*' | remove-item -WhatIf

编辑:你也可以把 where 带进去:

get-childitem -LiteralPath 'test[lala] lulu' -filter file* | 
where name -notlike *.txt | remove-item -WhatIf