SharePoint自动化系列——Site/Web/List级别的导航菜单

转载请注明出自天外归云的博客园:http://www.cnblogs.com/LanTianYou/

需求:在不同的测试用例中,对脚本中不确定的因素需要和用户交互来确定,比如选择哪个site,选择哪个web,选择哪个list。当然也可以手动的copy url来传参到脚本,不过比较不友好。最好的方法是不需要复制粘贴这种,直接在不确定因素的地方做出个导航菜单来,让脚本使用者自选。

代码如下:

Add-PSSnapin Microsoft.SharePoint.PowerShell
function List($target)
{
    if($target.count -gt 1)
    {
        for($i=1;$i -le $target.count;$i++)
        {
            "["+$i+"]"+$target[$i-1] | Write-Host -ForegroundColor Yellow   
        }
    }else
    {
        "[1]"+$target | Write-Host -ForegroundColor Yellow 
    }
}
$siteUrls = Get-SPSite | select {$_.url}
Write-Host "Here are the sites:" -ForegroundColor Cyan
List($siteUrls.'$_.url')
$choice = Read-Host "Choose the site by number before"
$theSite = Get-SPSite $siteUrls[[int]$choice-1].'$_.url'
Write-Host "Here are the webs:" -ForegroundColor Cyan
$webUrls = $theSite.AllWebs.url
List($webUrls)
$choice = Read-Host "Choose the web by number before"
Write-Host "Here are the lists:" -ForegroundColor Cyan
if($webUrls.count -lt 1){
    $theWeb = Get-SPWeb $webUrls[[int]$choice-1]
}else{
    $theWeb = $theSite.rootweb
}
$listTitles = $theWeb.lists.title
List($listTitles)
$choice = Read-Host "Choose the list by number before"
$theList = $theWeb.lists[$listTitles[[int]$choice-1]]
$theItem = ($theList.Items)[0]
$theFile = $theWeb.GetFile($theItem.Url)

运行效果如下:

实际应用:

在实际的编写SharePoint自动化脚本的过程中,可以把这段导航安插在不确定因素(Site/Web/List)出现的地方,最后我们会把用户选择的相应Site,Web以及List分别存储在三个变量中,分别为:$theSite,$theWeb,$theList。在之后的编写脚本的过程中,可以对这三个变量进行取用。来完成对Site,Web以及List中对象的操作。