4

Been trying to search for the answer to this, what I need to do is re-order the fields of a SharePoint list and propagate that change down to 300+ sites (should have used a content type, but oh well)

From the little I've been able to see, there is some sort of XML building like written here: http://exxlence.com/2008/07/19/reorder-sharepoint-list-fields-from-code/

But I need a PowerShell equivalent and I am not sure how it can be done, any help would be great!

4

After some effort I converted it into PowerShell YAY!

[Microsoft.SharePoint.SPList] $list = $web.Lists["Stakeholders Register"];
if(($list.Fields["Job Number"] -ne $null) -and ($list.Fields["Role within project"] -ne $null)) {

    $fieldReorderable = [string]::Empty;
    $fieldNonReorderable = [string]::Empty;
    $firstField = "Role_x0020_within_x0020_project";
    $secondField = "Job_x0020_Number";

    foreach ($element in $list.Fields) {
        if ($element.Reorderable)
        {
            if ($element.InternalName -eq $firstField)
            {
                $fieldReorderable += "<Field Name='" + $firstField + "'/>\r\n";
                $fieldReorderable += "<Field Name='" + $secondField + "'/>\r\n";
            }
            if ($element.InternalName -ne $secondField -and $element.InternalName -ne $firstField)
            {
                $fieldReorderable += "<Field Name='" + $element.InternalName + "'/>\r\n";
            }
        }
        elseif(-not($element.Reorderable))
        {
            $fieldNonReorderable += "<Field Name='" + $element.InternalName + "'/>\r\n";
        }
    }

    $fieldList = [string]::Format("<Fields>{0}{1}</Fields>", $fieldReorderable, $fieldNonReorderable);

    $reorderMethodFormat = '<?xml version="1.0" encoding="UTF-8"?><Method ID="0">' +
    '<SetList Scope="Request">{0}</SetList>' +
    '<SetVar Name="Cmd">REORDERFIELDS</SetVar>' +
    '<SetVar Name="ReorderedFields">{1}</SetVar></Method>';

    $reorder = [string]::Format($reorderMethodFormat, $list.ID, [Microsoft.SharePoint.Utilities.SPHttpUtility]::HtmlEncode($fieldList));
    $web.AllowUnsafeUpdates = $true;
    $res = $web.ProcessBatchData($reorder);
    $web.AllowUnsafeUpdates = $false;
}
0

PowerShell is using objects to manipulate so to make C# code portable to PowerShell is quite easy. There are only some little changes like declar variable and create objects.

Other thing is that you can just load a DLL with methodes to call and execute these methodes in PowerShell.

hope it helps,

Andrew

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.