首页 > 解决方案 > 如何使用 PowerShell 从文件名中删除句点?

问题描述

我正在尝试在 PowerShell 中编写一个脚本,该脚本在文件夹中搜索包含不必要句点的文件,然后从文件名中大量删除句点。

前任。Example.File.doc ---> ExampleFile.doc

每当我运行代码时,控制台都会返回以下内容:“重命名项目:无法将参数绑定到参数'NewName',因为它是一个空字符串。”

有谁知道问题是什么?

提前感谢您的帮助!

$files = get-childitem -path "C:\XXXX\XXXX\XXXX" -Recurse 
foreach($file in $files) {

    if($file.Name -match ".") {
        $newName = $file.Name -ireplace (".", "")
        Rename-Item $file.FullName $newName
        Write-Host "Renamed" $file.Name "to $newName at Location:" $file.FullName
    }
}

标签: powershell

解决方案


关于字符串替换的一件事:当我在没有转义句点的情况下尝试您的示例时,它没有替换任何内容并且没有返回任何内容(空字符串),我相信这可以回答您的“无法将参数绑定到参数'NewName',因为它是一个空字符串"

这通过逃避该时期而起作用。此外,它可以在有或没有括号的情况下使用。

$string = "the.file.name"

$newstring = $string -ireplace "\.", ""
// output: thefilename
$newstring.length
// output: 11

$othernewstring = $string -ireplace ("\.", "")
// output: thefilename
$othernewstring.length
// output: 11

// What the OP tried
$donothingstring = $string -ireplace (".", "")
// output:
$donothingstring.length
// output: 0

这里有一些关于字符串替换的附加信息,仅供参考https://vexx32.github.io/2019/03/20/PowerShell-Replace-Operator/


推荐阅读