I'm trying to put together a script that should iterate through all webs in a site collection, then iterate through all lists in those webs, then add a column where a list has a certain name.

This is what I have so far:


$spsite = Get-SPsite $sc 

foreach ($web in $spsite.AllWebs)
        foreach ($list in $spsite.AllWebs)
            $splist = $list.Lists["PSList"]
            $splist.Fields.Add("Calc", "Calculated", 0)
            $spfield = $splist.Fields.Getfield("Calc")
            $spfield.formula = "=TEXT([Start Date],`"mm/dd/yyyy`")`&`" - `"`&TEXT([End Date],`"mm/dd/yyyy`")"
            $spfield.outputtype = "Text"

This is the error I get:

You cannot call a method on a null-valued expression. At C:\scripts\addcalc.ps1:24 char:22 + $splist.Fields.Add <<<< ("Calc", "Calculated", 0) + CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull

I'm sure it's because I'm not iterating through the webs and then through the lists property. What's the correct way to achieve what I'm trying to do?

2 Answers 2


First - you must delete foreach ($list in $spsite.AllWebs) then find list using

$list = $web.Lists["InternalNameOfTheList"]


$list = $web.GetList($web.Url + "/Lists/" + $ListName) and after that add column using

$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text //change to your field type


And dispose SPWeb object after using it, like you do for SPSite object .

  • The original poster is already getting the list by ID. $list in their example is the actual SPWeb. Other than that, this answer appears correct - the method signature is probably expecting an enum like you're suggesting. Commented Apr 20, 2014 at 8:10

Thanks Andrey. Your suggestion led me down the right path. Here's the final working version of the script that solves the original question.

$site = Get-SPSite $sc
$webs = Get-SPWeb $sc
$count = 0
foreach ($web in $site.AllWebs)
            if (($webs.Count -le $Count) -and ($list = $web.Lists["PSList"]))

                $list.Fields.Add("Calc", "Calculated", 0)
                $field = $list.Fields.Getfield("Calc")
                $field.formula = "=TEXT([Start Date],`"mm/dd/yyyy`")`&`" - `"`&TEXT([End Date],`"mm/dd/yyyy`")"
                $field.outputtype = "Text"
$count ++       
  • Andrey, do you have any suggestions to make this script more efficient?
    – spex5
    Commented Apr 20, 2014 at 23:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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