当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 使用 SharePoint 中的自定义操作注入 JavaScript 或 CSS

作者:精品下载站 日期:2024-12-14 14:39:26 浏览:14 分类:玩电脑

PowerShell 使用 SharePoint 中的自定义操作注入 JavaScript 或 CSS


要求:在 SharePoint 中注入 JavaScript 或 CSS,无需编辑母版页。

PowerShell 使用自定义操作在 SharePoint 中注入 JavaScript:

假设“ga.js”文件已上传到站点资产库,下面是 SharePoint 母版页中用于 JavaScript 注入的 PowerShell。


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set Site variable
$SiteURL="https://intranet.crescent.com"
$CustomActionTitle ="Google Analytics"

Try {
    #Get the Web
    $Web = Get-SPWeb $SiteURL
 
    #Check if the Custom Action Exists already
    $CustomAction = $web.UserCustomActions | Where { $_.Title -eq $CustomActionTitle }

    If($CustomAction -eq $Null)
    {
        #Add new custom action
        $UserCustomAction = $web.UserCustomActions.Add()

        #Set the Properties of the custom action
        $UserCustomAction.Title = $CustomActionTitle
        $UserCustomAction.Location = "ScriptLink"
        $UserCustomAction.ScriptSrc = "~sitecollection/SiteAssets/ga.js"
        $UserCustomAction.Sequence = 1000
        $UserCustomAction.Update()
 
        Write-Host -f Green "Custom Action Added Successfully!"
    }
    Else
    {
        write-host -f Yellow "Custom Action Already Exists!"
    } 
} Catch {
    Write-Host -ForegroundColor Red "Error:" $_.Exception.Message
}

使用自定义操作插入 CSS - PowerShell

同样,您可以使用 PowerShell 将 CSS 插入母版页。


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set Site variable
$SiteURL="https://intranet.crescent.com"
$CustomActionTitle ="Custom Branding CSS"

Try {
    #Get the Site
    $Site = Get-SPSite $SiteURL
 
    #Check if the Custom Action Exists already
    $CustomAction = $Site.UserCustomActions | Where { $_.Title -eq $CustomActionTitle } | Select -First 1

    #Update the Custom action if found already
    If($CustomAction -eq $Null)
    {
        #Add new custom action
        $UserCustomAction = $Site.UserCustomActions.Add()
    }
    $CSSURL=$Site.URL+"/SiteAssets/Custom.css"
    #Set the Properties of the custom action
    $UserCustomAction.Title = $CustomActionTitle
    $UserCustomAction.Location = "ScriptLink"
    $UserCustomAction.ScriptBlock = "document.write('<link rel=""stylesheet"" After=""Corev15.css"" href=""$($CSSURL)"" type=""text/css""/>')"
    $UserCustomAction.Sequence = 1000
    $UserCustomAction.Update()
 
    Write-Host -f Green "Custom Action Updated Successfully!"
} Catch {
    Write-Host -ForegroundColor Red "Error:" $_.Exception.Message
}

这是关于将 JavaScript 注入到 SharePoint Online 母版页的另一篇文章 将 JavaScript 注入到 SharePoint Online

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯