创建PowerShell自定义对象

时间:2017-11-06 21:22:36

标签: powershell sharepoint

我在PowerShell中创建了一个自定义对象。我能够解决我想解决的问题。我希望有一个包含两列的对象,一列用于网站集,一列用于电子邮件。

但是,我想知道是否有更简单的解决方案。你有什么建议吗?

这是我的代码:

$cred = Get-Credential

Connect-PnPOnline "https://tenant.sharepoint.com" -Credentials $cred
$SiteCollections = Get-PnPTenantSite

$object = @()

foreach ($SiteCollection in $SiteCollections) {
    Connect-PnPOnline -Url $SiteCollection.Url -Credentials $cred
    $email = Get-PnPRequestAccessEmails
    Write-Host "Email for $($SiteCollection.Url): $($email)"

    $obj = New-Object System.Object
    $obj | Add-Member -type NoteProperty -name Url -value $SiteCollection.Url
    $obj | Add-Member -type NoteProperty -name Email -value $email
    $object += $obj
}

Write-Output $object

3 个答案:

答案 0 :(得分:4)

可以使用New-Object cmdlet:

从哈希表构建对象
$obj = New-Object -Type PSObject -Property @{
    'Url'   = $SiteCollection.Url
    'Email' = $email
}

或(如果您有PowerShell v3或更新版本)[PSCustomObject]类型加速器:

$obj = [PSCustomObject]@{
    'Url'   = $SiteCollection.Url
    'Email' = $email
}

此外,您可以简单地输出循环内的对象,并在如下变量中收集整个循环输出:

$object = @(foreach ($SiteCollection in $SiteCollections) {
    ...
    New-Object -Type PSObject -Property @{
        'Url'   = $SiteCollection.Url
        'Email' = $email
    }
})

@()循环周围的数组子表达式运算符(foreach)确保结果是数组,即使循环输出少于2个对象。

使用计算属性将是另一种选择:

$object = @(Get-PnPTenantSite | Select-Object Url, @{n='Email';e={
    Connect-PnPOnline -Url $_.Url -Credentials $cred | Out-Null
    Get-PnPRequestAccessEmails
}})

答案 1 :(得分:2)

稍微缩短代码:

$cred = Get-Credential
Get-PnPTenantSite | ForEach-Object {
  Connect-PnPOnline -Url $_.Url -Credentials $cred
  [PSCustomObject] @{
    Url = $_.Url
    Email = Get-PnPRequestAccessEmails
  }
}

[PSCustomObject]类型加速器仅存在于PowerShell 3.0及更高版本中。

答案 2 :(得分:0)

特别是如果您的阵列变得非常大,您可能需要考虑使用arraylist而不是vanilla数组。使用标准数组,每次向其添加数据时,它都会重新创建整个数组,而不是仅仅在最后添加数据。 arraylist只需附加,并且构建大型数组的速度要快得多。

$outArray = New-Object System.Collections.ArrayList

foreach ($SiteCollection in $SiteCollections) {
    Connect-PnPOnline -Url $SiteCollection.Url -Credentials $cred
    $email = Get-PnPRequestAccessEmails
    Write-Host "Email for $($SiteCollection.Url): $($email)"

    $obj = New-Object System.Object
    $obj | Add-Member -type NoteProperty -name Url -value $SiteCollection.Url
    $obj | Add-Member -type NoteProperty -name Email -value $email
    [void]$outArray.Add($obj)
}