2014-10-10 328 views
0

我想运行一个Powershell脚本来删除目录中的某些文件。该名称必须包含blahblahblah,因为我可以删除它。字符串比较没有比较

在我的测试子目录中,我有几个这样的文件名。然而,当我执行下面的代码:

$itemsToDelete = get-childItem -path $pathName | where {$_.Name -contains blahblahblah"}

它不选择任何项目。

我有三重检查,以确保在执行脚本时我处于正确的目录中。

编辑

因为已经向我指出。我错误地使用了contains

$itemsToDelete = get-childItem -path $pathName | where {($_.Name).Contains("blahblahblah")} 

正确治愈了我的困惑。

+2

'-contains' [不像你可能认为它应该工作](http://technet.microsoft.com/en-us/library/hh847759.aspx)。这不是你的错 - 经营者的名字是误导性的。无论如何,只需使用'-match'。 – 2014-10-10 15:26:21

+0

你是对的。 '{($ _。Name).Contains(“blahblahblah”)'。这工作。谢谢。如果你想发表一个答案,我会很乐意除外。 – Johnrad 2014-10-10 15:31:10

回答

1

根据作者的要求重新发表我的评论(有一些背景)。

引自TechNet

-Contains 
    Description: Containment operator. Tells whether a collection of reference 
    values includes a single test value. Always returns a Boolean value. Returns TRUE 
    only when the test value exactly matches at least one of the reference values. 

    When the test value is a collection, the Contains operator uses reference 
    equality. It returns TRUE only when one of the reference values is the same 
    instance of the test value object. 

总之,-Contains不会让你检查一个字符串包含特定字符串。您需要-Match-Like。请注意,-Match将您的测试值视为regular expression,因此您可能需要转义特殊字符。

我的意见是,-Contains既不是非常直观,也非常有帮助。从理论上讲,如果你支持"don't program by coincidence"的想法,这种事情是有道理的,但对于脚本语言来说,它们有点矫枉过正。

0

另一种替代方法是使用-like-unlike)与野生字符*结合以符合您的搜索。这更像SQL中的like

$itemsToDelete = get-childItem -path $pathName | where { $_.Name -like '*blahblahblah*' } 
+0

虽然这已经在评论中完成了,但如果没有别的,你至少应该解释为什么你的解决方案将有助于OP的情况。 – Matt 2014-10-10 17:13:58