Powershell 仅在必要时连接SPO服务

Powershell 仅在必要时连接SPO服务,powershell,sharepoint,sharepoint-online,Powershell,Sharepoint,Sharepoint Online,我正在为我的SharePoint Online实例编写一个管理脚本,并试图找出如何防止不必要的连接到SPO服务 例如,我有5个职能,每个执行官都有一个行政职能。显然,每一项都要求我在运行其余服务之前已成功连接到SPO服务 如果我打开脚本的目的是运行多个函数,那么我不想连接多次 在我再次连接之前,是否有办法检查连接是否已建立 示例代码: function Admin-Function_A{ Write-Host "Connecting to SharePoint Online&

我正在为我的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 
}

从我所看到的关于SPOService连接的一点,一旦您打开它,它将保持连接,直到您使用Disconnect SPOService关闭它,或者当会话关闭时。 您可以将所有函数添加到同一脚本中,并在执行工作之前调用Connect函数

我理解对了吗?
任何让我知道的事情都是理论上的,因为我没有访问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

那个这很有道理。老兄,事后看来这是个多么愚蠢的问题。这不是一个技术挑战,而是一个更好的计划:)哈哈哈,没有愚蠢的问题。最明显的是我们认为理所当然的事情。很高兴我能帮忙!