Question

I use this script to create a content organizer rule on my SP2013 site

[Microsoft.SharePoint.SPSite]$site = Get-SPSite http://www.mycompany.com
[Microsoft.SharePoint.SPWeb]$web = Get-SPWeb http://www.mycompany.com
[Microsoft.SharePoint.SPContentType]$ct = $site.RootWeb.ContentTypes["MyContentType"]
[Microsoft.Office.RecordsManagement.RecordsRepository.EcmDocumentRouterRule]$rule = New-Object Microsoft.Office.RecordsManagement.RecordsRepository.EcmDocumentRouterRule($web)

$rule.Aliases = $ct.Name
$rule.ConditionsString = "<conditions></conditions>"
$rule.CustomRouter = ""
$rule.Name = $ct.Name
$rule.Description = "Routes '" + $ct.Name + "' documents to it's own library"
$rule.ContentTypeString = $ct.Name
$rule.RouteToExternalLocation = $false
$rule.Priority = "5"
$rule.TargetPath = $web.Lists["MyLibrary"].RootFolder.ServerRelativeUrl
$rule.Enabled = $true
$rule.Update()

When I run this script 3 times I get 3 rules. How can I check if a rule exists and if so delete it.

Was it helpful?

Solution

I think there is room for improvement, but it looks like what you can do is wrap

$rule.Update()

in a condition to check if the rule already exists. if you want, you can also delete all with that name currently added.

example:

$web = get-spweb $webUrl
$ruleName = "test001"

$newRule = New-Object Microsoft.Office.RecordsManagement.RecordsRepository.EcmDocumentRouterRule($web)
$newRule.Aliases = $ruleName
$newRule.ConditionsString = "<conditions></conditions>"
$newRule.CustomRouter = ""
$newRule.Name = $ruleName
$newRule.Description = "test route"
$newRule.ContentTypeString = "ctname"
$newRule.RouteToExternalLocation = $false
$newRule.Priority = "5"
$newRule.TargetPath = "/sites/a/lib"
$newRule.Enabled = $true

#relevant code below
$routeWeb = New-Object Microsoft.Office.RecordsManagement.RecordsRepository.EcmDocumentRoutingWeb($web)
$allRules = $routeWeb.RoutingRuleCollection

#if rule exists, delete all with rule name
$duplicateRules = $allRules | ?{$_.Name -eq $ruleName}
if($duplicateRules -ne $null)
{
    write-host "Rule already exists!"

    $deleteIfExists = $true
    if($deleteIfExists)
    {
        foreach($ruleToDelete in $duplicateRules)
        {
            write-host ("Deleting " + $ruleToDelete.Name + " rule...")
            $ruleToDelete.Delete()
        }
    }

}

#create rule
write-host ""
write-host "Creating rule..."
$newRule.Update()#add rule
write-host "Rule created!"

Output:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top