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

时间:2019-10-03 19:45:14

标签: powershell-2.0

我正在尝试对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 

在删除行中,我删除了名称的最后3个字符。到目前为止,一切都很好。

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

最后一行在搜索字符串中添加了一个星号,并且没有给我一个错误。但也不会删除任何内容。 在最后一行的GCI中添加另一个“ LiteralPath”会给我错误,因为星号未用作通配符。

我该如何实现?

-narf

1 个答案:

答案 0 :(得分:0)

这是个把戏。 -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

编辑:您也可以在其中添加内容:

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