PowerShell Move (Move-Item) files to designated folders based on CSV file

Recently I had to move over 5000 documents to their respective folders.

Scenario:

There there two columns in a csv file. First column contains folder name and second column the filename. The files had to be moved to individual folders. There can be multiple documents per folder. You need to ensure that the folders have been created in the $dir location.

#PowerShell script to create folder

Set-Location “D:\Export\Files”

$Folders = Import-Csv D:\folders.csv -Header folders

 ForEach($Folder in $Folders) {

 New-Item $Folder.folders -type directory

}

 #Here is the PowerShell script for moving the files in required folder:

$text = Import-Csv “D:\InputFile.csv” 

$dir = Get-ChildItem D:\Export\Files

 foreach($item in $text ){

 foreach ($folder in $dir) {

#where Package is the name of the column in the csv file and FileName the name of #second column in the input csv file

 if($item.Package – eq $Folder.Name){

 $sourcefile = “D:\Export\” + $item.Filename 

$target = “D:\Export\Files\” + $folder.Name

 Move-Item$sourcefile$target

Write-Host“Folder $item.FileName moved sucessfully to $target”-ForegroundColor Green

 }

}

}

Advertisements

NServiceBus replay error queue from remote server

Here is an approach for playing NServiceBus error queue from Remote server. Quite often this is required if the operation team does not have access to teh Messaging server or you have a Distributor setup. This setup uses references to ReturnToSourceQueue.exe tools that is supplied from NServiceBus.

Save the command below in a .ps1 file and run it from Remote server. Remeber you need to have permission to run PowerShell in local server and Read/Write permission to the Error qs in the remote server.

param (

[Parameter(Mandatory=$false, HelpMessage=‘-Computername – The Servername for the Powershell session.’)]

[string]$Computername=“YOURREMOTECOMPUTERNAME”,

[Parameter(Mandatory=$false, HelpMessage=‘-Errorqueuename – The name of the Error Queue to be replayed.’)]

[string]$Errorqueuename=“error”,

[Parameter(Mandatory=$false, HelpMessage=‘-Path – The path location to the ReturnToSourceQueue.exe.’)]

[string]$Locationpath=“C:\install\nServiceBus\tools”

 );

##### check the the server, error queue name and Path exists #####

Write-Host “Checking Server: “$Computername;

Write-Host “Checking Error Queue: “$Errorqueuename ;

Write-Host“Checking Path: “$Locationpath ;

##### creates a remote session on the Servercomputer #####

$sessiontem = new-pssession-computername$Computername;

##### change directory to the location of the ReturnToSourceQueue.exe #####

Invoke-Command -Session $sessiontem {cd“C:\install\nServiceBus\tools”};

##### invoke the command to call replay the error queue #####

Invoke-Command -Session $sessiontem {.\ReturnToSourceQueue.exe error all};

##### close pssession #####

Remove-pssession $sessiontem;

##### completed #####

Write-Host $Errorqueuename“queue replayed successfully.” ;

PowerShell script to create many SharePoint sites in a site collection

All you need to change is the Site Title (@Subsites) and the Site Collection URL ($SiteCollectionURL):

Write-Output ” “
Write-Output “Creating Sub Sites”

$SiteCollectionURL = “http://yoursharepointsite/sitecollection/01″

$SiteCollectionTemplate = “SiteDefinitionTemplate#0”

$SiteCollectionLanguage = 1033

$SubSites = @(“Site Titel 1”, “Site Title 2”)

for($i=0 ; $i -lt $SubSites.count ; $i++)
{
$SiteUrl = “”
$SiteUrl = $SiteCollectionURL + “/”
$SiteUrl = $SiteUrl += $SubSites[$i]
Write-Output ” “
#Write-Output “Creating Site for ” += $SubSites[$i]
Write-Output ” “
New-SPWeb $SiteUrl -Template $SiteCollectionTemplate -Name “Your Site Name:” $SubSites -UseParentTopNav -Language $SiteCollectionLanguage -Description “Document Library description” $SubSites
Write-Output ” “
#Write-Output “Site Created for ” += $SubSites[$i]
Write-Output ” “
}

PowerShell to Update Created By and Modified By entries in SharePoint List or Document Library

[Reflection.Assembly]::Load(“Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”)

$SPSite = New-Object Microsoft.SharePoint.SPSite(http://yoursitename/site1/site2/)

$SPWeb = $SPSite.OpenWeb()

$SPList = $SPWeb.Lists[“Your List”]

$SPListItemCollection = $SPList.Items

foreach ($ListItem in $SPListItemCollection)

{

$SPFieldUserValue=New-Object Microsoft.SharePoint.SPFieldUserValue ($SPWeb,10, “domainname\username”)

$ListItem[“Editor”] = $SPFieldUserValue$ListItem[“Author”] = $SPFieldUserValue$ListItem.Update()

}

$SPWeb.Update()

Count any type of document in your SharePoint farm using PowerShell

Have you experienced a scenario when you have multiple SharePoint content databases across multiple SQL Servers. The scenario I had was following:

1. 3 SQL Servers.

2. Each SQL Server hosts multiple content databases

I did not want to write a script with the name of all the content databases but my script should pickup any SQL Server content database with the word “contet” in the database name. I save the SQL Server to a local file and call the query from PowerShell. In the script there are 2 variables defined, 1 the queryfile and 2 the SharePoint SQL Server instances. Here I am finding the total number of PDFs in my farm but you can use it to find any type of document. The script is as below (rememeber you need Farm Admin access and also need access to SQL Servers):

Save the script below as DocumentCount.ps1 and remember to save the SQL script to your desired location.

#Script starts here

$spqueryfile = “C:\SPDBQuery.sql” 

$sharepointDBinstances = @(“Server\SQLInstance1”,“Server\SQLInstance2”,“Server3\SQLInstance3”)

 $Final = 0 

foreach($sharepointDBinstance in $sharepointDBinstances){

 $initialresult= Invoke-Sqlcmd -ServerInstance $sharepointinstance -InputFile  $spqueryfile

 if (!$initialresult.HasErrors -eq $true){

 $Qresult = $initialresult | %{$_.Count} 

$Sum = $Qresult -join ‘+’ 

$Totals = Invoke-Expression $Sum

 $output “total PDFs in your SharePoint Farm”

    $Final = $Totals $Final

 }

}

Write-Host “The $output has value $Final”

#End of PowerShell script

The SQL Query is, you can change the query to report of doc or xlsx etc:

–Start of SQL Script

DECLARE @DBNAME VARCHAR(100), @STMT NVARCHAR(MAX)
DECLARE DBNAME_CURSOR CURSOR READ_ONLY
 for select name from sys.databases
   where name like (‘%content%’)
OPEN DBNAME_CURSOR  
FETCH NEXT FROM DBNAME_CURSOR into @DBNAME
WHILE @@FETCH_STATUS = 0
 BEGIN
  SET @STMT = ‘SELECT COUNT(*) as Count FROM ‘ + @dbname + ‘.[dbo].[AllDocs] (NOLOCK) WHERE Extension = ”pdf”’
  EXEC sp_executesql @STMT
 FETCH NEXT FROM DBNAME_CURSOR into @DBNAME
 END
 CLOSE DBNAME_CURSOR
  DEALLOCATE DBNAME_CURSOR

 —End of SQL Script

Hit like if you like what you see…..

How to enable delete button to delete SharePoint 2010 Content Type column

Here is the PowerShell script to bring back the Content Type delete button:

$site = Get-SPSite-Identity http://sharepointsite/sites/test 

$ctype =$site.RootWeb.Fields | ?{$_.InternalName -eq“InternalFieldName”}

$ctype.AllowDeletion=“true”

$ctype.Update()

Run the above script from the server and check that the content type button now appears.