【问题标题】:Powershell moving files between foldersPowershell在文件夹之间移动文件
【发布时间】:2015-12-08 05:07:28
【问题描述】:

我知道有很多与这个问题相关的答案,但他们从来没有完全按照我的意愿行事。

我有一个根文件夹,其下可能有 1 个或多个子文件夹。最初文件是在根文件夹Rejected 中创建的,程序将尝试处理它,如果不成功,则根据错误将其移动到特定的子文件夹中。所以在这种情况下,我们有:

| - Rejected
    |
    | - duplicate_found
    |   | - Informed
    |
    | - no_name
        | - Informed

我的程序想要遍历每个子文件夹(而不是 Informed 文件夹),并保留在子文件夹中找到的文件列表,然后通过电子邮件将列表发送给随后将进行调查的收件人。

通过电子邮件发送所有文件后,我想将这些文件移动到与其父拒绝原因子文件夹相关的子文件夹Informed。

所以如果在duplicate_found 中找到文件,该文件将被移动到duplicate_found/Informed。如果在no_name 中找到文件,则将移动到no_name/Informed 等。

我可以做电子邮件部分,这是循环遍历每个子文件夹然后移动我无法处理的文件的部分。

我无法在流程结束时进行完整的文件夹移动,因为可能有新文件尚未通过电子邮件发送。因此,我是否需要在循环时移动文件并同时保留电子邮件列表。不确定最佳方法。

帮助非常感谢

【问题讨论】:

    标签: powershell directory


    【解决方案1】:

    这是一个示例(Get-ChildItem 的 -File 和 -Directory 参数需要 PS 3.0):

    #set root folder
    $baseFolder = "C:\Rejected"
    
    #get folders inside root
    $folders = Get-ChildItem $baseFolder -Directory
    
    #for each folder
    foreach($folder in $folders) {
    
        #list the files
        $files = Get-ChildItem $folder.FullName -File
    
        #if there are files
        if($files.Count) {
    
            #build the move destination path
            $destination = Join-Path $folder.FullName "Informed"
    
            #move the files
            $files | % { Move-Item $_.FullName $destination }
    
            #build an email message with some information + the file listing
            $emailMessage = "$($files.Count) files reported and moved in folder $destination"
    
            #this could be formatted, i'm only pushing what you would see
            #in the console in the text message
            $emailMessage += $files | Out-String
    
            #i.e.: 5 files reported in folder duplicate_found and moved to
            #C:\Rejected\duplicate_found\Informed
            #
            # [file listing]
    
            #send email report for this folder
    
            $emailMessage
        }
    }
    

    【讨论】:

    • 那太好了。看到代码看起来很简单,但找到要使用的代码似乎总是最难的部分。谢谢
    • 不客气 :-)。如果您喜欢这个答案,您可以通过点击其投票下方的绿色对勾来接受它。
    猜你喜欢
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多