带有路径的Powershell foreach找不到文件 [英] Powershell foreach with path not finding files

查看:116
本文介绍了带有路径的Powershell foreach找不到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过foreach块重命名特定目录中的文件,但找不到任何文件.

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
        }
    }   

我的问题是foreach永远不会输入.我可以通过控制台中永远不会显示我的调试信息"FOUND ITEM"来证明这一点.

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.

我还试图根据在foreach中具有的replace和named参数来重命名路径中找不到的文件而不是目录.我不确定这些方法是否也有效,如果有经验的眼睛可以给我一次机会,让我知道我正在尝试的方法是否应该起作用,还有没有更好的方法,我将不胜感激.

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.

推荐答案

PetSerAl 指出的那样,使用:

As PetSerAl pointed out, using:

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

将起作用.引起您麻烦的是文件名中的方括号[ ],而-LiteralPath不会解释它们.

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

从PowerShell v2开始,它们被视为特殊字符,用于字符范围.请参阅从字面上理解事物(例如文件路径).

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

这篇关于带有路径的Powershell foreach找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆