0

If QuickLaunch has nodes, the following causes the error "You cannot call a method on a null valued expression". If not, it carries on as normal.

$nodes = $subWeb.Navigation.QuickLaunch
write-host $nodes.Count
while($nodes.Count -gt 0)
{
    $nodes[0].Delete()
}
write-host $nodes.Count  #error
1

I made a mistake. The error happens in the while loop.

Apparently $nodes.Count never changes, so the while loop runs until $nodes[0] is null and $nodes[0].Delete() throws the error. I changed the while condition to catch it.

$nodes = $subWeb.Navigation.QuickLaunch
write-host $nodes.Count
while($nodes.Count -gt 0 -and $nodes[0] -ne $null) 
{
    $nodes[0].Delete()
}
write-host $nodes.Count 
0

I think after deleting the last node, QuickLaunch (SPNavigationNodeCollection) is not exists anymore as no child items exists in the database. That why $nodes is null in your example.

  • do you know how I would add new nodes to it then, after deleting everything? currently I have to run my script twice - first time to clear existing nodes and the second time to add new nodes, because quicklaunch is null after deleting but not null if I run again – user33518 Sep 17 '14 at 15:42
  • You can use web.Navigation.AddToQuickLaunch: msdn.microsoft.com/en-us/library/… – Ruslan Dayanov Sep 17 '14 at 16:04

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.