2014-10-10 161 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