Powershell foreach with path not finding files

删除回忆录丶 提交于 2019-12-11 04:07:09

问题


I'm trying to rename files in a specific directory by my foreach block isn't finding any files.

#expected encountered filename = 3000 Miles To Graceland 2001.avi
$path = "D:\Media Holding\[UsaBit.com]_3000 Miles To Graceland 2001"
foreach($file in Get-ChildItem $path) {
        "FOUND ITEM"
        if (!$file.PSIsContainer) {
            $fileName = $file.FullName -replace ("(\w.*?)([12]\d{3})", "$1 ($2)") -replace("\.", " ") -replace("\s{2,}", " ")
            $fileExtension = $file.FullName -replace ("[^\.]*\.(\w{3,4})$", ".$1")
            $fileName = $fileName + $fileExtension
            Rename-Item -NewName $file $fileName
        }
    }   

My problem is that the foreach is never getting entered. I can prove that much by the fact that my debugging message of "FOUND ITEM" is never being displayed in the console.

I had attempted to follow K. Brian Kelly's example of a foreach. But obviously I am missing something here.

I am also attempting to rename the files and not directories found in the path based on the the replace and rename arguments I have inside the foreach. I am not certain if those are valid either and I would love if more experienced eyes could give it a once over and let me know if what I'm trying should work and if there is a better way.


回答1:


As PetSerAl pointed out, using:

foreach($file in Get-ChildItem -LiteralPath $path) {
    # ...
}

will work. It's the square brackets [ ] in your file name that are causing issues for you, and -LiteralPath doesn't interpret them.

They are considered special characters as of PowerShell v2, used for ranges of characters. See Taking Things (Like File Paths) Literally.



来源:https://stackoverflow.com/questions/32468103/powershell-foreach-with-path-not-finding-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!