M365関連 プログラム 技術

SharePointに対してリンクチェックをしてみる

SharePointのURLに対して、リンクが切れていないか(アクセス可能か)のチェックする必要がありその際に四苦八苦したのでメモします。PowerShellで実装します

SharePointがオンプレミスかオンラインかで変わる

まず1つ目に躓いたのが、SharePointの種類によってやり方が変わってくるという点でした
2つ目にSharePointOnlineの場合に特殊な接続の仕方をしたことです

オンプレミスの場合

HttpWebRequestを使用してリンクチェックを実施します

$httpStatus = ""
try{
    [System.Net.HttpWebRequest]$request = [System.Net.HttpWebRequest]::Create($targetURL)
    // 本スクリプトを実行しているユーザーの資格で実施
    $request.Credentials = [System.Net.CredentialCache]::DefaultCredentials
    $response = $request.GetResponse()
    $httpStatus = $response.StatusCode.Tostring()
    $response.Close()
    $request.Dispose()
} catch [System.Net.WebException] {
    [System.Net.HttpWebResponse]$err = $_.Exception.Response
    if($err -eq $null) {
        $httpStatus = "NetWorkError"
    } else {
        $httpStatus = $err.StatusCode
    }        
}

オンラインの場合

こちらもHttpWebRequestを使用してリンクチェックを実施します。ただ、CSOMの認証オブジェクトに含まれるcookieで認証を通して確認している形になるため少し変則的な感じになります

$httpStatus = ""
try {
    $webReq = [System.Net.HttpWebRequest]::Create($targetURL)
    $userCredentials  = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($USER, $PASSWORD)
    $cookie_Container = New-Object System.Net.CookieContainer
    # 認証に使用するcookieを作成
    $auth_Cookie = New-Object System.Net.Cookie("SPOIDCRL", $userCredentials.GetAuthenticationCookie((New-Object System.Uri($targetURL))) -replace "SPOIDCRL=", "")
    # 作成したcookieを設定する
    $cookie_Container.Add((New-Object System.Uri($targetURL)), $auth_Cookie)
    $webReq.CookieContainer = $cookie_Container

    $res = $webReq.GetResponse()
    $httpStatus = $res.StatusCode.Tostring()
    $res.Close()
} catch {
    [System.Net.HttpWebResponse]$err = $_.Exception.Response
    if ($err -eq $null) {
        $httpStatus = "NetWorkError"
    }
    else {
        $httpStatus = $err.StatusCode
    }
}

最後に

最初はオンラインの場合でもInvoke-WebRequestでいけるかもと思っていたのですが、存在しないSharePoint上のURLでもステータスコードがOKで返ってきてしまい困っていました
今回紹介した方法にたどり着くまでに時間がかかりました

おまけ:ステータスコードの変換

上記のやり方だとステータスコードが「OK」といった感じで文字で返ってくるので、それを数値に変換します

$statusCodeHashtable = @{
    "Continue"                        = "100" 
    "Switching"                       = "101" 
    "Processing"                      = "102" 
    "EarlyHints"                      = "103" 
    "OK"                              = "200" 
    "Created"                         = "201" 
    "Accepted"                        = "202" 
    "Non-AuthoritativeInformation"    = "203" 
    "NoContent"                       = "204" 
    "ResetContent"                    = "205" 
    "PartialContent"                  = "206" 
    "MultipleChoice"                  = "300" 
    "MovedPermanently"                = "301" 
    "Found"                           = "302" 
    "NotModified"                     = "304" 
    "BadRequest"                      = "400" 
    "Unauthorized"                    = "401" 
    "PaymentRequired"                 = "402" 
    "Forbidden"                       = "403" 
    "NotFound"                        = "404" 
    "MethodNotAllowed"                = "405" 
    "NotAcceptable"                   = "406" 
    "ProxyAuthentication Required"    = "407" 
    "RequestTimeout"                  = "408" 
    "Conflict"                        = "409" 
    "Gone"                            = "410" 
    "LengthRequired"                  = "411" 
    "PreconditionFailed"              = "412" 
    "PayloadTooLarge"                 = "413" 
    "URITooLong"                      = "414" 
    "UnsupportedMediaType"            = "415" 
    "RangeNotSatisfiable"             = "416" 
    "ExpectationFailed"               = "417" 
    "UnprocessableEntity"             = "422" 
    "Locked"                          = "423" 
    "TooEarly"                        = "425" 
    "UpgradeRequired"                 = "426" 
    "TooManyRequests"                 = "429" 
    "RequestHeaderFieldsTooLarge"     = "431" 
    "InternalServerError"             = "500" 
    "NotImplemented"                  = "501" 
    "BadGateway"                      = "502" 
    "ServiceUnavailable"              = "503" 
    "GatewayTimeout"                  = "504" 
    "HTTPVersionNotSupported"         = "505" 
    "VariantAlsoNegotiates"           = "506" 
    "InsufficientStorage"             = "507" 
    "LoopDetected"                    = "508" 
    "NotExtended"                     = "510" 
    "NetworkAuthenticationRequired"   = "511" 
}

# 使い方
$res = $webReq.GetResponse()
if($statusCodeHashtable.Contains($res.StatusCode.ToString())) {
    $STATUS_CODE = $statusCodeHashtable[$res.StatusCode.ToString()]
} else {
    $STATUS_CODE = $res.StatusCode.ToString()
}

-M365関連, プログラム, 技術
-,