在 Powershell 中重命名文件列表并创建文件夹

发布于 2024-11-26 16:15:01 字数 464 浏览 0 评论 0原文

我需要一个 PowerShell 或批处理脚本中的脚本,它将执行以下操作。

  1. 重命名文件以将创建日期减 1 天附加到文件名中。

    例如:

    foo.xlsx(创建于 7/27/2011)

    foo-2011-07-26.xlsx --注意,这是昨天的日期。

    日期格式并不重要,只要它存在即可。将有 10 个文件(全部具有相同的创建日期),因此我可以为不同的文件复制并粘贴相同的重命名行(只需重命名文件名),或者只是让脚本影响现有文件夹中的所有 *.xlsx 文件。

  2. 在这些文件所在的位置创建一个新文件夹,并将其命名为“fooFolder-2011-07-26”(昨天的日期)。

  3. 将这些重命名的文件移至该文件夹。

我对 PowerShell 的经验有限。它在我要学习的语言待办事项列表中..

I'm in need a script, in PowerShell or batch script, that will do the following.

  1. Rename a file to append creation date minus 1 day to the filename.

    For example:

    foo.xlsx (created 7/27/2011)

    foo-2011-07-26.xlsx --note, it's yesterday's date.

    Date format isn't too important as long as it's there. There will be 10 files (all with the same creation date), so either I can copy and paste the same renaming line for the different files (just rename the filename) or just have the script affect all *.xlsx files in the existing folder.

  2. Create a new folder where those files are and name it 'fooFolder-2011-07-26' (yesterday's date).

  3. Move those renamed files to that folder.

I only have limited experience with PowerShell. It's on my todo list of languages to learn..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仅冇旳回忆 2024-12-03 16:15:01

干得好。使用别名和管道之类的东西可以大大缩短它,但由于您仍然不熟悉 Powershell,我决定以更程序化的方式编写以供您阅读:

function MoveFilesAndRenameWithDate([string]$folderPrefix, [string]$filePattern) {
  $files = Get-ChildItem .\* -include $filePattern
  ForEach ($file in $files) {
    $yesterDate = $file.CreationTime.AddDays(-1).ToString('yyyy-MM-dd')
    $newSubFolderName = '{0}-{1}' -f $folderPrefix,$yesterDate
    if (!(Test-Path $newSubFolderName)) {
      mkdir $newSubFolderName
    }
    $newFileName = '{0}-{1}{2}' -f $file.BaseName,$yesterDate,$file.Extension
    Move-Item $file (Join-Path $newSubFolderName $newFileName)
  }
}

您可以将以上内容粘贴到您的 Powershell 会话中(将其放在您的个人资料)。然后你像这样调用该函数:

MoveFilesAndRenameWithDate 'fooFolder' '*.xslx'

我倾向于使用比上面的函数更多的别名和管道。我编写的第一个版本是这样的,然后我将其部分分开,以便 Powershell 新手更容易理解:

function MoveFilesAndRenameWithDate([string]$folderPrefix, [string]$filePattern) {
  gci .\* -include $filePattern |
    % { $date = $_.CreationTime.AddDays(-1).ToString('yyyy-MM-dd')
        mkdir "$folderPrefix-$date" 2>$null
        mv $_ (join-path $newSubFolderName ('{0}-{1}{2}' -f $_.BaseName,$date,$_.Extension))}
}

编辑:修改了这两个函数,为与该日期匹配的文件创建带日期的文件夹。我考虑创建一个临时目录并从移至其中的文件中获取单个日期,最后在循环后重命名该目录。但是,如果错过一天并且将 2 天(或更多)天的文件放在一起处理,那么每天仍然会有一个文件夹包含这些文件,这样更加一致。

Here you go. It could be shortened up a lot using aliases and piping and whatnot, but since you're unfamiliar with Powershell still, I decided to write in a more procedural style for your reading:

function MoveFilesAndRenameWithDate([string]$folderPrefix, [string]$filePattern) {
  $files = Get-ChildItem .\* -include $filePattern
  ForEach ($file in $files) {
    $yesterDate = $file.CreationTime.AddDays(-1).ToString('yyyy-MM-dd')
    $newSubFolderName = '{0}-{1}' -f $folderPrefix,$yesterDate
    if (!(Test-Path $newSubFolderName)) {
      mkdir $newSubFolderName
    }
    $newFileName = '{0}-{1}{2}' -f $file.BaseName,$yesterDate,$file.Extension
    Move-Item $file (Join-Path $newSubFolderName $newFileName)
  }
}

You would paste the above into your Powershell session (place it in your profile). Then you call the function like this:

MoveFilesAndRenameWithDate 'fooFolder' '*.xslx'

I tend to use more aliases and piping than the above function. The first version I wrote was this, and then I separated parts of it to make it more comprehensible to a Powershell newcomer:

function MoveFilesAndRenameWithDate([string]$folderPrefix, [string]$filePattern) {
  gci .\* -include $filePattern |
    % { $date = $_.CreationTime.AddDays(-1).ToString('yyyy-MM-dd')
        mkdir "$folderPrefix-$date" 2>$null
        mv $_ (join-path $newSubFolderName ('{0}-{1}{2}' -f $_.BaseName,$date,$_.Extension))}
}

Edit: Modified both functions to create dated folder for the files that match that date. I considered making a temporary directory and grabbing a single date from the files moved to it, finally renaming the directory after the loop. However, if a day should be missed and files for 2 (or more) days get processed together, there would still be a folder for each day with these, which is more consistent.

酒废 2024-12-03 16:15:01

好的,我已经做到了

 function NameOfFunction([string]$folderpath)
 {
    foreach ($filepath in [System.IO.Directory]::GetFiles($folderpath))
    {
        $file = New-Object System.IO.FileInfo($filepath);
        $date = $file.CreationTime.AddDays(-1).ToString('yyyy-MM-dd');
        if (![System.IO.Directory]::Exists("C:\\test\foo-$date"))
        {
            [System.IO.Directory]::CreateDirectory("$folderpath\foo-$date");
        }
        $filename = $file.Name.Remove($file.Name.LastIndexOf('.'));
        $fileext = $file.Name.SubString($file.Name.LastIndexOf('.'));
        $targetpath = "$folderpath\foo-$date" + '\' + $filename + '-' + $date + $fileext;
        [System.IO.File]::Move($filepath, $targetpath);
    }
 }

说明:
首先获取根文件夹中的所有文件。
对于每个文件夹,我们创建一个 FileInfo-Object 并获取 CreationTime -1 Day。
然后我们检查应该创建的目录是否存在,如果不存在则创建它。
然后我们得到文件名和扩展名。
最后,我们将文件移动到新目录下的新文件名下。

希望对您有帮助

ok i´ve made it

 function NameOfFunction([string]$folderpath)
 {
    foreach ($filepath in [System.IO.Directory]::GetFiles($folderpath))
    {
        $file = New-Object System.IO.FileInfo($filepath);
        $date = $file.CreationTime.AddDays(-1).ToString('yyyy-MM-dd');
        if (![System.IO.Directory]::Exists("C:\\test\foo-$date"))
        {
            [System.IO.Directory]::CreateDirectory("$folderpath\foo-$date");
        }
        $filename = $file.Name.Remove($file.Name.LastIndexOf('.'));
        $fileext = $file.Name.SubString($file.Name.LastIndexOf('.'));
        $targetpath = "$folderpath\foo-$date" + '\' + $filename + '-' + $date + $fileext;
        [System.IO.File]::Move($filepath, $targetpath);
    }
 }

Explanation:
First get all Files in the rootfolder.
Foreach Folder we create a FileInfo-Object and get the CreationTime -1 Day.
Then we check, if the Directory, which should be created, exists and create it if false.
Then we get the filename and the extension.
At the End we move the files to the new Directory, under the new Filename.

Hope that help you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文