Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
126 changes: 126 additions & 0 deletions documentation/Set-PnPFileVersionExpirationDate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
---
Module Name: PnP.PowerShell
title: Set-PnPFileVersionExpirationDate
schema: 2.0.0
applicable: SharePoint Online
external help file: PnP.PowerShell.dll-Help.xml
online version: https://pnp.github.io/powershell/cmdlets/Set-PnPFileVersionExpirationDate.html
---

# Set-PnPFileVersionExpirationDate

## SYNOPSIS

Keeps the file version with option to set an expiry date.

## Syntax

```powershell
Set-PnPFileVersionExpirationDate [-List] <ListPipeBind> [-Identity] <ListItemPipeBind> [-Version] <ListItemVersionPipeBind> [[-ExpirationDate] <DateTime>] [-Connection <PnPConnection>] [<CommonParameters>]
```

## DESCRIPTION

This cmdlet keeps the file version with option to set an expiry date.

## Examples

### Example 1
```powershell
Set-PnPFileVersionExpirationDate -List "Documents" -Identity 1 -Version "1.0" -ExpirationDate "2025-12-31"
```

Sets the expiration date for version 1.0 of list item with ID 1 in the Documents library to December 31, 2025.

### Example 2
```powershell
Set-PnPFileVersionExpirationDate -List "Documents" -Identity 1 -Version "1.0"
```

Clears the expiration date for version 1.0 of list item with ID 1 in the Documents library, setting the version to `Never expires`.

## Parameters

### -List

The library to retrieve the file from.

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

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

### -Identity

The ID of the file to update.

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

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


### -Version

The version of the file to modify. This can be specified by version label (e.g. "1.0") or version ID.

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

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

### -ExpirationDate

The new expiration date for the version. If not specified, the expiration date will be cleared.

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

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

### -Connection
Optional connection to be used by the cmdlet. Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection.

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

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

## Outputs

This cmdlet does not produce any output.

## Related Links

[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp)

113 changes: 113 additions & 0 deletions src/Commands/Lists/SetFileVersionExpirationDate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using System;
using System.Linq;
using System.Management.Automation;
using System.Net.Http;
using Microsoft.SharePoint.Client;
using PnP.Core.Model.SharePoint;
using PnP.Core.QueryModel;
using PnP.PowerShell.Commands.Base.Completers;
using PnP.PowerShell.Commands.Base.PipeBinds;

namespace PnP.PowerShell.Commands.Lists
{
[Cmdlet(VerbsCommon.Set, "PnPFileVersionExpirationDate")]
public class SetListItemVersion : PnPWebCmdlet
{
[Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0)]
[ArgumentCompleter(typeof(ListNameCompleter))]
public ListPipeBind List;

[Parameter(Mandatory = true, ValueFromPipeline = true)]
public ListItemPipeBind Identity;

[Parameter(Mandatory = true, ValueFromPipeline = true)]
public ListItemVersionPipeBind Version;

[Parameter(Mandatory = false)]
public DateTime? ExpirationDate { get; set; }

protected override void ExecuteCmdlet()
{
var list = List.GetList(Connection.PnPContext);

if (list is null)
{
throw new PSArgumentException($"Cannot find the list provided through -{nameof(List)}", nameof(List));
}

var item = Identity.GetListItem(list);

if (item is null)
{
throw new PSArgumentException($"Cannot find the list item provided through -{nameof(Identity)}", nameof(Identity));
}

item.EnsureProperties(i => i.All, i => i.Versions, i => i.File);

var itemVersionCollection = item.Versions.AsRequested();

IListItemVersion version = null;
if (!string.IsNullOrEmpty(Version.VersionLabel))
{
version = itemVersionCollection.FirstOrDefault(v => v.VersionLabel == Version.VersionLabel);
}
else if (Version.Id != -1)
{
version = itemVersionCollection.FirstOrDefault(v => v.Id == Version.Id);
}

if (version is null)
{
throw new PSArgumentException($"Cannot find the list item version provided through -{nameof(Version)}", nameof(Version.VersionLabel));
}

// Only proceed if the item has an associated file (i.e., is a document)
if (item.File == null)
{
throw new PSArgumentException("The specified list item does not represent a file. Expiration date can only be set for file versions in document libraries.");
}

// Build REST API URL
var siteUrl = Connection.Url.TrimEnd('/');
var fileUrl = item.File.ServerRelativeUrl;
if (string.IsNullOrEmpty(fileUrl))
{
throw new PSArgumentException("Cannot determine the file URL for the list item.");
}
var encodedFileUrl = Uri.EscapeDataString(fileUrl);
var expirationUrl = $"{siteUrl}/_api/web/GetFileByServerRelativePath(DecodedUrl='{encodedFileUrl}')/versions({version.Id})/SetExpirationDate()";

LogDebug($"Calling: {expirationUrl}");

// Prepare REST payload
var expirationPayload = ExpirationDate.HasValue
? $"{{ \"expirationDate\": \"{ExpirationDate.Value.ToString("o")}\" }}"
: "{ \"expirationDate\": null }";

var stringContent = new StringContent(expirationPayload);

try
{
var httpClient = PnP.Framework.Http.PnPHttpClient.Instance.GetHttpClient(Connection.Context);
var accessToken = Connection.Context.GetAccessToken();

var payload = new { expirationDate = ExpirationDate.HasValue ? ExpirationDate.Value.ToString("o") : null };

var responseString = Utilities.REST.RestHelper.Post(
httpClient,
expirationUrl, // The full REST API URL
accessToken,
payload // Pass as an object, not a string
);


LogDebug($"Updated expiration date for version {version.VersionLabel} of list item {item.Id} in list {list.Title}");
}
catch (Exception ex)
{
LogError($"Error setting expiration date: {ex.Message}");
throw;
}
}
}
}
Loading