在PowerShell中有条件地指定开关参数

时间:2011-10-18 13:45:14

标签: powershell sharepoint-2010

我正在编写一个PowerShell脚本,该脚本使用SharePoint 2010 New-SPWeb cmdlet创建由Xml文件定义的网站:

<?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>

New-SPWeb cmdlet有三个开关参数:

  1. AddToQuickLaunch
  2. AddToTopNav
  3. UseParentTopNav
  4. 当Xml中的匹配值为0或$ true时,我无法确定如何仅设置switch参数。

    在调用New-SPWeb设置三个开关参数时,我几乎需要某种内联if语法。

    $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");
    }
    

    非常感谢!

2 个答案:

答案 0 :(得分:19)

之前计算$result$true$false):

$result = ...

在以下之后使用它:

New-SPWeb `
-Url "$URL/$siteToCreate.url" `
-Name $siteToCreate.name `
-Template $webTemplate `
-Language $siteToCreate.language `
-AddToQuickLaunch:$result `
-AddToTopNav:$result `
-UseParentTopNav:$result

答案 1 :(得分:18)

还有一种方法。您可以像这样使用splatting:

$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

更多关于喷溅的信息:

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