Use PowerShell to Create Year and Month Folders in Library

How do you create a year and month folder structure in a SharePoint document library?

Every year, I needed to create a folder structure in a report library that looks like this:

Next Year – 01 …… 12

Using PowerShell I’m able to create the parent folder (year), then create the subfolders (months).

*NOTE*
This can be executed using a scheduled task or using a workflow in SharePoint Designer with the help of the iLoveSharePoint add in.

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$spWeb = Get-SPWeb "http://sharepointed.com/sites/reports"
$spDocLib = $spWeb.Lists["TacoReports"]

$yearFolder = (get-date (Get-Date).AddYears(1) -UFormat "%Y")

$targetFolder = $spWeb.GetFolder($spDocLib.RootFolder.ServerRelativeUrl + "/$yearFolder")

if($targetFolder.Exists -eq $false)
{
    $spFolder = $spDocLib.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$yearFolder)
	$spFolder.Update()

	$i = 1
	While ($i -le 12)
	{
		$subFolder= "{0:D2}" -f $i
		$spSubFolder = $spDocLib.AddItem($spFolder.Folder.ServerRelativeUrl,[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$subFolder)
		$spSubFolder.Update()

		$i++
	}
}

Get the current year and add one.
Check if the new folder already exist.
Create the year folder.
Then create the twelve subfolders (one for each month).

Use PowerShell to Loop Through Folders in a Library

Here is an example of using PowerShell to look through folders in a SharePoint Document Library.


if(-not(Get-PSSnapin | where { $_.Name -eq "Microsoft.SharePoint.PowerShell"}))
{
      Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$site = Get-SPweb "http://sharepointed.com/site/taco/"

$mList=$site.Lists["Shared Tacos"]

foreach($f in $mlist.Folders)
 {
 Write-Host $f.Name
 }

$site.dispose()