powershell为多个文件和子目录设置类别

时间:2015-07-25 00:36:46

标签: powershell categories

我一直在把#34;标签"进入文件的名称,但这是一种组织大量文件的可怕方式。

ex:" ABC - 文件名.docx"

所以,我想将category属性设置为" ABC"而不是使用PowerShell在名称中。该脚本必须找到所有文件" ABC"在其名称中的某个文件夹的子目录中,并将category属性设置为" ABC"。

所以我在第一部分找到了文件,但我不知道从哪里开始。

Get-ChildItem -Filter "ABC*" -Recurse

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:0)

所以这大量借鉴Scripting Guys。我们需要做的是我们发现的每个文件都使用Word COM对象来访问文件的这些特殊属性。使用当前文件名,我们通过拆分第一个连字符并保存两个部分来提取“类别”。首先成为类别,第二个是我们给出文件的新名称,假设类别更新成功。

这还有误差,但是这个

$path = "C:\temp"

# Create the Word com object and hide it sight
$wordApplication = New-Object -ComObject word.application
$wordApplication.Visible = $false

# Typing options for located Word Documents. Mainly to prevent changes to timestamps
$binding = "System.Reflection.BindingFlags" -as [type]

# Locate Documents.
$docs = Get-childitem -path $Path -Recurse -Filter "*-*.docx"
$docs | ForEach-Object{
    $currentDocumentPath = $_.fullname
    $document = $wordApplication.documents.open($currentDocumentPath)
    $BuiltinProperties = $document.BuiltInDocumentProperties
    $builtinPropertiesType = $builtinProperties.GetType()
    $categoryUpdated = $false  # Assume false as a reset of the state.

    # Get the category from the file name for this particular file.
    $filenamesplit =  $_.Name.split("-",2)
    $category = $filenamesplit[0].Trim()

    # Attempt to change the property.
    Try{ 
        $BuiltInProperty = $builtinPropertiesType.invokemember("item",$binding::GetProperty,$null,$BuiltinProperties,"Category")  
        $BuiltInPropertyType = $BuiltInProperty.GetType()
        $BuiltInPropertyType.invokemember("value",$binding::SetProperty,$null,$BuiltInProperty,[array]$category)
        $categoryUpdated = $true
    }Catch [system.exception]{
        # Error getting property so most likely is not populated. 
        Write-Host -ForegroundColor Red "Unable to set the 'Category' for '$currentDocumentPath'" 
    }

    # Close the document. It should save by default. 
    $document.close()

    # Release COM objects to ensure process is terminated and document closed. 
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($BuiltinProperties) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($document) | Out-Null
    Remove-Variable -Name document, BuiltinProperties

    # Assuming the category was successfully changed lets remove the information from the current filename as it is redundant.
    If($categoryUpdated){Rename-Item $currentDocumentPath -NewName $filenamesplit[1].Trim()}
}

$wordApplication.quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($wordApplication) | Out-Null
Remove-Variable -Name wordApplication
[gc]::collect()
[gc]::WaitForPendingFinalizers()

您应该在我尝试添加的评论中看到一些解释,以便澄清。另请阅读上面的链接,以获得有关COM对象发生情况的更多解释。