【问题标题】:Powershell - Unable to Compare Strings Output from Sharepoint ListPowershell - 无法比较来自 Sharepoint 列表的字符串输出
【发布时间】:2016-04-18 04:29:04
【问题描述】:

从 SharePoint 提取列表后,我需要根据其 BRTeam 值验证每个项目。这是脚本:

cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
     Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$sourceWebUrl = "http://theoracle/WorkingHere/"
$sourceListName = "Policies & Procedures"

$spSourceWeb = Get-SPWeb $sourceWebUrl
$spSourceList = $spSourceWeb.Lists[$sourceListName]

$spSourceItems = $spSourceList.Items

$spSourceItems | ForEach-Object {
    Write-Host $_['Name']
    Write-Host $_['BRTeam']
}

代码在获取数据和将所需项目写入主机方面运行良好。

但是,如果我添加以下 If 语句来验证项目,我会看到一个错误:

if ($_['BRTeam'].Contains('HR')) {
    Write-Host $_['Name']
    Write-Host $_['BRTeam']
} 

在分配$x = $_['BRTeam'] 后,我也尝试用$x -contains 'HR' 替换布尔检查,但这不会返回任何输出(也没有错误)。以下错误:

Method invocation failed because [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue] doesn't contain a method named 'Contains'.
At line:21 char:9
+     if ($_['BRTeam'].Contains('HR')) {
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

谁能告诉我这里缺少什么?

【问题讨论】:

    标签: arrays powershell sharepoint


    【解决方案1】:

    我可以通过使用 -Match 运算符来解决此问题:

    $spSourceItems | ForEach-Object {
        #Write-Host $_['ID']
        #Write-Host $_['Workflow Started']
        $x =  $_['BRTeam']
    
        if ($_['BRTeam'] -Match 'HR') {
            Write-Host $_['Name']
        }     
    }
    

    如果我担心其他一些 BRTeam 可能包含 HR 而实际上不是 HR,我还可以对所有其他部门执行 -NotMatch。

    例如:

    $spSourceItems | ForEach-Object {
        #Write-Host $_['ID']
        #Write-Host $_['Workflow Started']
        $x =  $_['BRTeam']
    
        if ($_['BRTeam'] -Notmatch 'Accounts' -And $_['BRTeam'] -Notmatch 'IT') {
            Write-Host $_['Name']
        }     
    }
    

    【讨论】:

    • .Contains 不起作用的原因是字段的值是一个 SPFieldValue 对象,不一定是字符串。您可以将其转换为字符串以显示它,当您将其与带有-match 的字符串进行比较或使用Write-Host 将其写入控制台时,Powershell 就是这样做的。使用-match 的替代方法是$_['BRTeam'].ToString().Contains('HR')
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多