Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally specifying switch parameters in PowerShell

I'm writing a PowerShell script that uses the SharePoint 2010 New-SPWeb cmdlet to create sites defined by an Xml file:

<?xml version="1.0" encoding="utf-8" ?>
<siteStructure>
  <site>
    <url>Corporate</url>
    <name>Corporate</name>
    <language>1033</language>
    <addToQuickLaunch>0</addToQuickLaunch>
    <addToTopNav>0</addToTopNav>
    <useParentTopNav>1</useParentTopNav>
  </site>
</siteStructure>

The New-SPWeb cmdlet has three switch parameters:

  1. AddToQuickLaunch
  2. AddToTopNav
  3. UseParentTopNav

I'm having trouble figuring out how to only set the switch parameter when the matching value in the Xml is 0 or $true.

It's almost like I need some sort of inline-if syntax when calling New-SPWeb to set the three switch parameters.

$siteStructureData = [xml](Get-Content .\Data-SiteStructure.xml)

# find the template to use
$webTemplate = Get-SPWebTemplate | Where {$_.Title -like $templateName } 

if ($webTemplate)
{
    # iterate through and create sites
    foreach ($siteToCreate in $siteStructureData.siteStructure.site)
    {   
        "Creating site $webtitle at $URL/$webUrl"

        # http://technet.microsoft.com/en-us/library/ff607579.aspx
        New-SPWeb `
            -Url "$URL/$siteToCreate.url" `
            -Name $siteToCreate.name `
            -Template $webTemplate `
            -Language $siteToCreate.language 
            # set -AddToQuickLaunch
            # set -AddToTopNav
            # set -UseParentTopNav
    }
}
else
{
    throw ("Could not find template $templateName");
}

Many thanks!

like image 568
George Durzi Avatar asked Oct 18 '11 13:10

George Durzi


1 Answers

There is one more way. You can use splatting like this:

$params = @{
            Url = "$URL/$siteToCreate.url"
            Name = $siteToCreate.name
            Template = $webTemplate 
            Language = $siteToCreate.language }
# if needed, add the keys to the hashtable
if ($result) {
    $params.AddToQuickLaunch = $true
    $params.AddToTopNav = $true
    $params.UseParentTopNav = $true
}
# now you just pass the parameters:
New-SPWeb @params

More about splatting:

What does the "@" symbol do in Powershell? http://blogs.msdn.com/b/powershell/archive/2009/01/02/how-and-why-to-use-splatting-passing-switch-parameters.aspx

like image 92
stej Avatar answered Sep 25 '22 09:09

stej