Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Add-PnPFileSensitivityLabel cmdlet for assigning sensitivity labels to SharePoint files #4538

Merged
merged 4 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions documentation/Add-PnPFileSensitivityLabel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
---
Module Name: PnP.PowerShell
schema: 2.0.0
applicable: SharePoint Online
online version: https://pnp.github.io/powershell/cmdlets/Add-PnPFileSensitivityLabel.html
external help file: PnP.PowerShell.dll-Help.xml
title: Add-PnPFileSensitivityLabel
---

# Add-PnPFileSensitivityLabel

## SYNOPSIS

**Required Permissions**

* Microsoft Graph API : One of Files.ReadWrite.All, Sites.ReadWrite.All

Add the sensitivity label information for a file in SharePoint.

## SYNTAX
```powershell
Add-PnPFileSensitivityLabel -Url <String> -SensitivityLabelId <Guid> -AssignmentMethod <Enum> -JustificationText <string>
```

## DESCRIPTION

The Add-PnPFileSensitivityLabel cmdlet adds the sensitivity label information for a file in SharePoint using Microsoft Graph. It takes a URL as input, decodes it, and specifically encodes the '+' character if it is part of the filename. It also takes the sensitivity label Id , assignment method and justification text values as input.

## EXAMPLES

### Example 1
This example adds the sensitivity label information for the file at the specified URL.

```powershell
Add-PnPFileSensitivityLabel -Url "/sites/Marketing/Shared Documents/Report.pptx" -SensitivityLabelId b5b11b04-05b3-4fe4-baa9-b7f5f65b8b64 -JustificationText "Previous label no longer applies" -AssignmentMethod Privileged
```

This example adds the sensitivity label information for the file at the specified URL.

gautamdsheth marked this conversation as resolved.
Show resolved Hide resolved
## PARAMETERS

### -Url
Specifies the URL of the file on which we add the sensitivity label information.

```yaml
Type: String
Parameter Sets: (All)

Required: True
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False
```

### -SensitivityLabelId
ID of the sensitivity label to be assigned, or empty string to remove the sensitivity label.

```yaml
Type: string
Parameter Sets: (All)

Required: True
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False
```

### -AssignmentMethod
The assignment method of the label on the document. Indicates whether the assignment of the label was done automatically, standard, or as a privileged operation (the equivalent of an administrator operation).

```yaml
Type: Guid
Parameter Sets: (All)
Accepted values: Standard, Privileged, Auto
Required: False
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False
```

### -JustificationText
Justification text for audit purposes, and is required when downgrading/removing a label.

```yaml
Type: Guid
Parameter Sets: (All)

Required: False
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False
```

## RELATED LINKS

[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp)
9 changes: 9 additions & 0 deletions src/Commands/Enums/SensitivityLabelAssignmentMethod .cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace PnP.PowerShell.Commands.Enums
{
public enum SensitivityLabelAssignmentMethod
{
Standard,
Privileged,
Auto
}
}
72 changes: 72 additions & 0 deletions src/Commands/Files/AddFileSensitivityLabel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using PnP.Framework.Utilities;
using PnP.PowerShell.Commands.Attributes;
using PnP.PowerShell.Commands.Base;
using PnP.PowerShell.Commands.Utilities.REST;
using System;
using System.Management.Automation;

namespace PnP.PowerShell.Commands.Files
{
[Cmdlet(VerbsCommon.Add, "PnPFileSensitivityLabel")]
[RequiredApiDelegatedOrApplicationPermissions("graph/Files.ReadWrite.All")]
[RequiredApiDelegatedOrApplicationPermissions("graph/Sites.ReadWrite.All")]

public class AddFileSensitivityLabel : PnPGraphCmdlet
{
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
public string Url = string.Empty;
gautamdsheth marked this conversation as resolved.
Show resolved Hide resolved

[Parameter(Mandatory = true)]
public string SensitivityLabelId;

[Parameter(Mandatory = false)]
public Enums.SensitivityLabelAssignmentMethod AssignmentMethod = Enums.SensitivityLabelAssignmentMethod.Privileged;

[Parameter(Mandatory = false)]
public string JustificationText = string.Empty;

protected override void ExecuteCmdlet()
{
var serverRelativeUrl = string.Empty;

if (Uri.IsWellFormedUriString(Url, UriKind.Absolute))
{
// We can't deal with absolute URLs
Url = UrlUtility.MakeRelativeUrl(Url);
}

// Remove URL decoding from the Url as that will not work. We will encode the + character specifically, because if that is part of the filename, it needs to stay and not be decoded.
Url = Utilities.UrlUtilities.UrlDecode(Url.Replace("+", "%2B"));

Connection.PnPContext.Web.EnsureProperties(w => w.ServerRelativeUrl);

var webUrl = Connection.PnPContext.Web.ServerRelativeUrl;

if (!Url.ToLower().StartsWith(webUrl.ToLower()))
{
serverRelativeUrl = UrlUtility.Combine(webUrl, Url);
}
else
{
serverRelativeUrl = Url;
}

var file = Connection.PnPContext.Web.GetFileByServerRelativeUrl(Url);
file.EnsureProperties(f => f.VroomDriveID, f => f.VroomItemID);

var requestUrl = $"https://{Connection.GraphEndPoint}/v1.0/drives/{file.VroomDriveID}/items/{file.VroomItemID}/assignSensitivityLabel";

var payload = new
{
sensitivityLabelId = SensitivityLabelId,
assignmentMethod = AssignmentMethod.ToString(),
justificationText = JustificationText
};

var responseHeader = RestHelper.PostGetResponseHeader<string>(Connection.HttpClient, requestUrl, AccessToken, payload: payload);

WriteVerbose($"File sensitivity label assigned to {Url}");
WriteObject(responseHeader.Location);
}
}
}
34 changes: 17 additions & 17 deletions src/Commands/Utilities/REST/RestHelper.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -7,16 +8,15 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using Microsoft.SharePoint.Client;

namespace PnP.PowerShell.Commands.Utilities.REST
{
internal static class RestHelper
{
{
#region GET
public static T ExecuteGetRequest<T>(ClientContext context, string url, string select = null, string filter = null, string expand = null, uint? top = null)
{
var returnValue = ExecuteGetRequest(context, url, select, filter, expand, top);
var returnValue = ExecuteGetRequest(context, url, select, filter, expand, top);

var returnObject = JsonSerializer.Deserialize<T>(returnValue, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
return returnObject;
Expand Down Expand Up @@ -208,9 +208,9 @@ public static T Get<T>(HttpClient httpClient, string url, ClientContext clientCo
return default(T);
}

#endregion
#endregion

#region POST
#region POST

public static string Post(HttpClient httpClient, string url, string accessToken, string accept = "application/json")
{
Expand Down Expand Up @@ -270,7 +270,7 @@ public static string Post(HttpClient httpClient, string url, ClientContext clien
message = GetMessage(url, HttpMethod.Post, clientContext, accept);
}
return SendMessage(httpClient, message);
}
}

public static T Post<T>(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true)
{
Expand Down Expand Up @@ -333,9 +333,9 @@ public static T Post<T>(HttpClient httpClient, string url, ClientContext clientC
}


#endregion
#endregion

#region PATCH
#region PATCH
public static T Patch<T>(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true)
{
var stringContent = Patch(httpClient, url, accessToken, payload);
Expand All @@ -360,7 +360,7 @@ public static T Patch<T>(HttpClient httpClient, string url, string accessToken,

public static string Patch(HttpClient httpClient, string url, string accessToken, object payload, string accept = "application/json")
{
HttpRequestMessage message = null;
HttpRequestMessage message = null;
if (payload != null)
{
var content = new StringContent(JsonSerializer.Serialize(payload, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }));
Expand All @@ -373,9 +373,9 @@ public static string Patch(HttpClient httpClient, string url, string accessToken
}
return SendMessage(httpClient, message);
}
#endregion
#endregion

#region PUT
#region PUT
public static T ExecutePutRequest<T>(ClientContext context, string url, string content, string select = null, string filter = null, string expand = null, string contentType = null)
{
HttpContent stringContent = new StringContent(content);
Expand Down Expand Up @@ -439,9 +439,9 @@ private static HttpResponseMessage ExecutePutRequestInternal(ClientContext conte
var returnValue = client.PutAsync(url, content).GetAwaiter().GetResult();
return returnValue;
}
#endregion
#endregion

#region MERGE
#region MERGE
public static T ExecuteMergeRequest<T>(ClientContext context, string url, string content, string select = null, string filter = null, string expand = null, string contentType = null)
{
HttpContent stringContent = new StringContent(content);
Expand Down Expand Up @@ -506,9 +506,9 @@ private static HttpResponseMessage ExecuteMergeRequestInternal(ClientContext con
var returnValue = client.PostAsync(url, content).GetAwaiter().GetResult();
return returnValue;
}
#endregion
#endregion

#region DELETE
#region DELETE

public static string Delete(HttpClient httpClient, string url, string accessToken, string accept = "application/json")
{
Expand Down Expand Up @@ -584,7 +584,7 @@ private static HttpResponseMessage ExecuteDeleteRequestInternal(ClientContext co
var returnValue = client.DeleteAsync(url).GetAwaiter().GetResult();
return returnValue;
}
#endregion
#endregion

private static HttpRequestMessage GetMessage(string url, HttpMethod method, string accessToken, string accept = "application/json", HttpContent content = null)
{
Expand Down Expand Up @@ -693,7 +693,7 @@ private static System.Net.Http.Headers.HttpResponseHeaders SendMessageGetRespons
}
else
{
var errorContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); ;
var errorContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
throw new HttpRequestException(errorContent);
}
}
Expand Down
Loading