【问题标题】:Connect-SPOService Only When Necessary仅在必要时连接 SPOService
【发布时间】:2021-05-24 03:20:36
【问题描述】:

我正在为我的 SharePoint Online 实例编写管理脚本,并试图弄清楚如何防止与 SPO 服务的不必要连接。

例如,我有 5 个职能,每个执行一个行政职能。显然,每一个都要求我已经成功连接到 SPO 服务,然后才能运行其余的。

如果我打开脚本的目的是运行多个函数,我不想连接多次。

有没有办法让我在再次连接之前检查连接是否已经建立?

示例代码:

 function Admin-Function_A{
    Write-Host "Connecting to SharePoint Online" -ForegroundColor White

    try {
        Connect-Function
        Write-Host "Successfully connected to SharePoint Online." -ForegroundColor Green
    } catch {
        Write-Host "Connection to SharePoint Online failed." -ForegroundColor Red 
    }

}

function Connect-Function{
    # Import the module 
    Import-Module Microsoft.Online.SharePoint.Powershell -DisableNameChecking
    # Load credential 
    $credential = Get-Credential -Message "Enter admin account password" -UserName $adminUsername
    Connect-SPOService -Url $adminUrl -Credential $credential 
}

【问题讨论】:

    标签: powershell sharepoint sharepoint-online


    【解决方案1】:

    根据我对 SPOService 连接的了解,一旦您打开它,它就会一直保持连接,直到您使用 Disconnect-SPOService 或会话关闭时关闭它。 您可以将所有函数添加到同一个脚本中,并在开始工作之前调用 Connect-Function。

    我理解正确吗? 有什么告诉我

    【讨论】:

    • 这……很有意义。伙计,事后看来,这是一个多么愚蠢的问题。这不是一个技术挑战,更多的是关于更好地规划:)
    • 哈哈哈没有什么愚蠢的问题。最明显的事情是我们认为理所当然的事情。很高兴我能帮上忙!
    【解决方案2】:

    这都是理论上的,因为我无法访问 SPO

    function Test-SPOConnected {
        [CmdletBinding()]
        param()
    
        Write-Verbose 'Testing Connection to SharePoint Online'
        try {
            # Choose a command that you know should return something if you are connected, 
            # preferably only a small amount of objects, or error otherwise
            # Based off documentation I've choosen Get-SPOSite 
            # however there could be a better option
            $results = Get-SPOSite -ErrorAction Stop
    
            If ($results) {
                Write-Verbose 'Successfully connected to SharePoint Online.' 
                $true
            }
            else {
                Write-Warning 'Nothing returned.  Not connected to SharePoint Online.'
                $false
            }
        }
        catch {
            Write-Warning 'Connection to SharePoint Online failed.' 
            $false
        }
    }
    

    然后在其他代码/函数中,您可以使用 if 语句检查连接

    if (!Test-SPOConnected) {
        Connect-Function
    }
    # do SPO stuff
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 2012-05-25
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2016-01-22
      相关资源
      最近更新 更多