我正在嘗試根據可能出現在檔案名中任何位置的文本移動 .pdf 檔案,但它不起作用。它執行沒有錯誤,但它不會移動檔案。
所有檔案名中帶有“已售出”的 .pdf 檔案都放在一個地方,而檔案名中沒有“已售出”的所有檔案都放在另一個地方。
get-childitem -Recurse -path $sourcePathPDF {-filter '*.pdf' -and '*Sold*'} | move-item -Destination $destinationPathSoldPDF
get-childitem -Recurse -path $sourcePathPDF {-filter '*.pdf' -not '*Sold*'} | move-item -Destination $destinationPathPDF
我是否在過濾/使用 -not 錯誤?
謝謝您的幫助。
uj5u.com熱心網友回復:
-Filter只接受單個圖案。使用
-Includeand-Exclude代替,兩者都接受多個模式。
# Two inclusion patterns
Get-ChildItem -Recurse -Path $sourcePathPDF -Include *.pdf, *sold*
# One inclusion, one exclusion pattern.
Get-ChildItem -Recurse -Path $sourcePathPDF -Include *.pdf -Exclude *Sold*
注意:
從 PowerShell 7.2 開始,
-Include并且-Exclude受到性能問題的阻礙,正如Mathias R. Jessen指出的那樣,由于它們的實作效率低下(請參閱GitHub 問題 #8662),因此Where-Object可能會呼叫下面討論的基于 - 的解決方案,而不僅僅是為了更復雜的匹配邏輯,但僅針對性能。-Include并-Exclude使用 PowerShell 的通配符運算式,它具有更多功能并且缺乏-Filter支持的平臺原生模式的遺留怪癖- 請參閱此答案以獲取更多資訊。- 使用的好處
-Filter是它比-Include/快得多-Exclude,因為-Filter過濾器 _at 源,而-Include/-Exclude過濾器是在事實之后應用的,由PowerShell,在所有專案都首先被檢索之后。
- 使用的好處
沒有
-Recurse,-Include并且-Exclude不能按預期作業 -Get-Item * -Include/-Exclude ...改用 - 請參閱此答案。
要獲得更復雜的模式匹配和/或更好的性能,請按照 Mathias 的建議,通過管道傳輸到Where-Object腳本塊中的呼叫,您可以使用基于通配符的-like運算子;或者,為了更靈活的匹配,您可以使用基于正則運算式的-match運算子。從評論中修改-like基于Mathias的Where-Object解決方案:
Get-ChildItem -Recurse -Path $sourcePathPDF |
Where-Object { $_.Name -like '*.pdf' -and $_.Name -notlike '*Sold*' }
對于(目前)的最佳性能,您可以預先篩選具有-Filter:
Get-ChildItem -Recurse -Path $sourcePathPDF -Filter *.pdf |
Where-Object { $_.Name -notlike '*Sold*' }
至于你嘗試了什么:
-Filter,-Include, and-Exclude是字串型別的 - 不支持傳遞腳本塊({ ... }用任意運算式傳遞給它們。- 雖然管道系結引數可以接受腳本塊,以便根據手頭的輸入物件動態提供引數值(稱為延遲系結腳本塊的功能),但這些引數都不支持這種系結,因此傳遞腳本塊不會不適用。
在您的嘗試中實際發生的情況是腳本塊的字串化版本
{-filter '*.pdf' -and '*Sold*'}——即其逐字內容(不包括{和})——在位置上系結到-Filter引數。- 也就是說,您有效地通過了
-Filter "-filter '*.pdf' -and '*Sold*'",可以預見它不匹配任何檔案,因為逐字逐字-filter '*.pdf' -and '*Sold*'用作模式。
- 也就是說,您有效地通過了
uj5u.com熱心網友回復:
使用 -not,由于運算子優先級,您將需要括號:
get-childitem | where {$_.name -like '*.pdf' -and -not ($_.name -like '*Sold*')}
你也可以進入 wmi 以提高速度:
Get-WmiObject CIM_DataFile -filter 'Drive="C:" and Extension="pdf" and
not name like "%Sold%" and path like "\\%"'
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363104.html
標籤:电源外壳
上一篇:用戶輸入路徑作為字串
下一篇:配置更新-PowerShell
