Monday, May 19, 2025

🧹 Clean Up SharePoint Online File Versions: Keep Only the Latest 5 in a Specific Folder Using PnP PowerShell

 Versioning in SharePoint Online is a powerful feature that allows teams to maintain historical copies of documents. However, over time, these versions can accumulate and consume significant storage space—especially in document libraries with frequent updates.

This article provides a step-by-step PowerShell script using the SharePointPnPPowerShellOnline module to clean up old versions of files in a specific folder within a document library—retaining only the latest 5 versions of each file.


🔧 Why This Is Useful

  • Storage Optimization: SharePoint libraries with thousands of old file versions can significantly inflate site storage.

  • Performance: Reducing version history helps improve performance in large libraries.

  • Targeted Cleanup: Instead of affecting the entire document library, you can limit cleanup to a specific folder.


🛠️ Prerequisites

Install-Module -Name SharePointPnPPowerShellOnline -Force
  • SharePoint Online site URL and access permissions to the library/folder.

  • PowerShell with administrative rights.

📜 Script Overview

This script:

  1. Connects to the SharePoint Online site.

  2. Targets a specific folder in a document library.

  3. Retrieves all files in that folder (recursively).

  4. Keeps only the latest 5 versions of each file and deletes the rest.


🔍 PowerShell Script

# Install and Import the Module (if not already done)
Install-Module -Name SharePointPnPPowerShellOnline -Force
Import-Module SharePointPnPPowerShellOnline

# Variables
$SiteURL = "https://gks.sharepoint.com/sites/yoursite"
$ListName = "TestVersionsDocLib"
$FolderServerRelativeUrl = "/sites/yoursite/TestVersionsDocLib/TargetFolder"  # Change as needed

# Connect to SharePoint
Connect-PnPOnline -Url $SiteURL -UseWebLogin  # Use -Interactive if using modern auth

# Get PnP Context
$Ctx = Get-PnPContext

# Get all files in the specified folder recursively
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 -Query "<View Scope='RecursiveAll'><Query><Where><BeginsWith><FieldRef Name='FileRef'/><Value Type='Text'>$FolderServerRelativeUrl</Value></BeginsWith></Where></Query></View>" | Where { $_.FileSystemObjectType -eq "File" }

foreach ($Item in $ListItems) {
    $File = $Item.File
    $Versions = $File.Versions

    $Ctx.Load($File)
    $Ctx.Load($Versions)
    $Ctx.ExecuteQuery()

    Write-Host "Scanning File: $($File.Name) with $($Versions.Count) versions"

    if ($Versions.Count -gt 5) {
        # Keep latest 5, delete the rest
        $VersionsToDelete = $Versions | Sort-Object -Property Created -Descending | Select-Object -Skip 5
        foreach ($version in $VersionsToDelete) {
            $version.DeleteObject()
        }

        $Ctx.ExecuteQuery()
        Write-Host "Deleted $($VersionsToDelete.Count) older versions of the file: $($File.Name)"
    }
}

📁 Example Folder Path

If your document library is called TestVersionsDocLib and the target folder is Invoices/2025, the relative URL should be:

/sites/yoursite/TestVersionsDocLib/Invoices/2025

✅ Output

The script will:

  • Display each file being scanned.

  • Show how many versions were found.

  • Confirm deletion of versions beyond the latest 5.

⚠️ Important Considerations

  • This script only affects a specific folder—not the whole document library.

  • Always test in a development or QA site before using in production.

  • Deleting versions is irreversible—ensure you retain what’s necessary.


$SiteURL = "https://tc.sharepoint.com/teams/GK/ms"
$FolderSiteRelativeUrl = "Shared Documents/TargetTest"
 Connect-PnPOnline -Url $SiteURL -UseWebLogin
 # Test folder access
$Folder = Get-PnPFolder -Url $FolderSiteRelativeUrl
Write-Host "Folder found: $($Folder.Name)"
# Get files
$Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeUrl -ItemType File -Recursive
Write-Host "Found $($Files.Count) files in the folder"

You can test if the folder exists using this:

Get-PnPFolder -FolderSiteRelativeUrl "Shared Documents"
Get-PnPFolder -FolderSiteRelativeUrl "Shared Documents/4. Projects - WIP"
Get-PnPFolder -FolderSiteRelativeUrl "Shared Documents/4. Projects - WIP/FY'24"

 Get-PnPFolder -FolderSiteRelativeUrl "Shared%20Documents%2F04%2E%20Projects%20%2D%20WIP"

Get-PnPFolder -FolderSiteRelativeUrl "Shared%20Documents%2F04%2E%20Projects%20%2D%20WIP%2FFY%2724%2FFY%2724%20%2D%20Cancellation%20Reason%20%26%20Subreason"

 This helps isolate where the path is breaking.

📝 Final Thoughts

Keeping version history under control is a best practice for maintaining a clean and efficient SharePoint environment. Automating this process with PowerShell ensures consistency and saves valuable administrator time.

If you need to scale this to multiple folders or automate it on a schedule, consider integrating it into an Azure Automation Runbook or a task scheduler.

To package a complete Flask project into a distributable .exe file using PyInstaller, follow these steps:

🧩 How to Convert a Complete Flask Project into a Distributable .exe File Using PyInstaller

Flask is a popular Python web framework, but distributing a Flask app to non-technical users or across an organization can be a challenge—especially when you want to avoid complex setups or Python dependencies. Fortunately, PyInstaller lets you turn your Flask app into a single Windows .exe file that can be executed without installing Python or managing virtual environments.

🚀 To convert a complete Flask project into a distributable .exe file using PyInstaller, follow the steps outlined below:

✅ 1. Prepare Your Flask Project

Make sure your Flask app has an entry point, typically something like app.py or run.py with a structure like:

from flask import Flask

app = Flask(__name__)

@app.route('/')

def home():

    return "Hello, Flask!"

if __name__ == "__main__":

    app.run()

✅ 2. Install PyInstaller

pip install pyinstaller

✅ 3. Use the PyInstaller Command

Run the following command in your project directory to generate a standalone executable that includes all dependencies:

pyinstaller --onefile --windowed --add-data "templates;templates" --add-data "static;static" app.py

Replace app.py with the main entry-point file of your Flask app.

🔍 Explanation of Flags

--onefile: Package everything into a single .exe file.

--windowed: Hides the console window (optional; good for GUI apps).

--add-data: Includes folders like templates and static.

Format: "source;destination" (use : instead of ; on macOS/Linux).

✅ 4. Output Location

After running the command, your .exe will be in the dist/ folder:

dist/

└── app.exe

✅ 5. Distribute Within the Company

You can share the dist/run.exe file directly. Ensure:

Target machines have the required firewall permissions (Flask runs a local server).

If the app uses a browser interface, it should auto-open or include instructions to visit http://127.0.0.1:5000.

💡 Optional: Auto-Open Browser on Run

In your app.py, add:

import webbrowser from threading import Timer

def open_browser():

    webbrowser.open("http://127.0.0.1:5000")

if __name__ == "__main__":

    Timer(1, open_browser).start()

    app.run()

🎯 Conclusion

Packaging your Flask application into a .exe file using PyInstaller is a powerful way to simplify deployment and make your app more accessible to end users. With just a few commands and a clear structure, you can create and share production-ready desktop versions of your web applications within your company—no Python installation required.


Tuesday, May 6, 2025

PowerShell script to delete file versions from the specified SharePoint document library

Managing file versions in SharePoint Online is essential to maintain storage hygiene and performance, especially when versioning is enabled for document libraries. Over time, older versions of files can accumulate and consume significant storage space. This PowerShell script demonstrates how to connect to a SharePoint Online site and delete all previous versions of files from a specified document library.

  Prerequisites

  • PnP PowerShell Module installed (Install-Module -Name "PnP.PowerShell")
  • Permissions to access the SharePoint Online site and document library
  • SharePoint versioning must be enabled for the document library

📝 Script Overview

$SiteURL = "https://{domain}.sharepoint.com/sites/GKS_Demosite"
$ListName="TestVersionsDocLib"
Connect-PnPOnline -Url $SiteURL -UseWebLogin
#Get the Context
$Ctx= Get-PnPContext
#Get All Items from the List - Exclude 'Folder' List Items
$ListItems = Get-PnPListItem -List $ListName | Where {$_.FileSystemObjectType -eq "File"}
ForEach ($Item in $ListItems)
{
    #Get File Versions
    $File = $Item.File
    $Versions= $File.Versions
    $Ctx.Load($File)
    $Ctx.Load($Versions)
    $Ctx.ExecuteQuery()
    Write-host  "Scanning File:"$File.Name
     
    If($Versions.Count -gt0)
    {
        #Delete all versions
        $Versions.DeleteAll()
        $Ctx.ExecuteQuery()
        Write-Host  "Deleted All Previous Versions of the File:"$File.Name
    }
}

📝 What the Script Does

  1. Connects to the specified SharePoint Online site using PnP PowerShell.
  2. Retrieves all file items from the specified document library (excluding folders).
  3. Loads each file’s version history.
  4. Deletes all previous versions for each file, keeping only the latest one.

⚠️ Important Notes

  • This script permanently deletes all previous versions. Make sure this is what you intend before running it.
  • Test the script in a non-production environment first.
  • You may want to add logging or backups depending on your organization’s governance policies.

🧠 Use Cases

  • Reclaiming storage space in libraries with heavy versioning.
  • Maintaining SharePoint Online quota limits.
  • Cleaning up outdated versions during migration or audits.

Monday, April 28, 2025

How to Delete Previous Versions in a SharePoint Document Library Using PowerShell

Managing document versions in SharePoint is crucial for maintaining an organized and efficient workspace. Over time, document libraries can accumulate numerous versions, consuming storage space and complicating file management. This article provides a step-by-step guide on how to delete previous versions in a SharePoint document library using PowerShell.

Prerequisites

Before you begin, ensure you have the following:

  • Access to the SharePoint site and document library.
  • PowerShell installed on your machine.
  • Necessary permissions to execute scripts and manage SharePoint libraries.

Step 1: Install the PnP PowerShell Module

The PnP PowerShell module is essential for interacting with SharePoint Online. Install the module using the following command:

Install-Module -Name PnP.PowerShell


If you are using PowerShell 7 or later, you might need to install it specifically for that version:

Install-Module -Name PnP.PowerShell -Scope CurrentUser

Step 2: Import the PnP PowerShell Module

After installing the module, import it into your session:

Import-Module PnP.PowerShell

Step 3: Connect to SharePoint Online

Use the Connect-PnPOnline cmdlet to connect to your SharePoint site. Replace the placeholders with your actual SharePoint site URL and credentials:
Connect-PnPOnline -Url "https://yoursharepointsite.sharepoint.com" -Credentials (Get-Credential)

You will be prompted to enter your credentials.


Step 4: Delete Previous Versions in a Document Library

Once connected, you can use the following script to delete previous versions in a specified document library. Replace "YourLibraryName" with the actual name of your document library:

$library = "YourLibraryName"
$files = Get-PnPListItem -List $library
foreach ($file in $files) {
    Remove-PnPFileVersion -List $library -Identity $file.Id -AllVersions

}

This script retrieves all items in the specified document library and deletes all previous versions of each file.

Troubleshooting Common Issues

If you encounter errors such as CommandNotFoundException, ensure the PnP PowerShell module is installed correctly and imported into your session. Verify the installation with:

Get-Module -ListAvailable -Name PnP.PowerShell

Ensure you are using the latest version of PowerShell by checking your version:

$PSVersionTable.PSVersion

Restarting PowerShell after installing a module can also resolve recognition issues.

Alternative Solutions

If PowerShell isn't your preferred method, consider these alternatives:

  • Power Automate: Create a custom flow to automatically delete older versions based on specific criteria.
  • Manual Deletion: Use the SharePoint interface to manually delete versions via the Version History option.
  • SharePoint Trim Versions Feature: Utilize SharePoint's built-in feature to trim versions based on age or count limits.

By following these steps, you can efficiently manage document versions in your SharePoint libraries, ensuring a streamlined and organized workspace.

USING POWER AUTOMATE

Implementing the deletion of previous versions in a SharePoint document library using Power Automate can help automate and streamline the process. Here’s a step-by-step guide to create a Power Automate flow for this task:

Step-by-Step Guide to Create a Power Automate Flow

1. Create a New Flow

  1. Go to Power Automate.
  2. Click on Create and select Instant cloud flow.
  3. Name your flow and choose the trigger Manually trigger a flow. Click Create.

2. Get Files from the Document Library

  1. Add a new action Get files (properties only).
  2. Configure the action:
    • Site Address: Select your SharePoint site.
    • Library Name: Select your document library.

3. Loop Through Each File

  1. Add an Apply to each action.
  2. Set the value from the Get files (properties only) action as the output to loop through each file.

4. Get File Versions

  1. Inside the Apply to each action, add a Send an HTTP request to SharePoint action.
  2. Configure the action:
    • Site Address: Select your SharePoint site.
    • Method: GET
    • Uri: _api/web/lists/getbytitle('YourLibraryName')/items(@{items('Apply_to_each')?['ID']})/versions
  3. This action retrieves all versions of each file.

5. Delete Previous Versions

  1. Add another Apply to each action inside the first one to loop through each version.
  2. Set the value from the Send an HTTP request to SharePoint action as the output.
  3. Add a Condition to check if the version is not the current version.
    • Expression: @not(equals(items('Apply_to_each_2')?['IsCurrentVersion'], true))
  4. In the If yes branch, add a Send an HTTP request to SharePoint action to delete the version.
    • Site Address: Select your SharePoint site.
    • Method: DELETE
    • Uri: _api/web/lists/getbytitle('YourLibraryName')/items(@{items('Apply_to_each')?['ID']})/versions(@{items('Apply_to_each_2')?['ID']})

Summary

This flow will loop through each file in the specified document library, retrieve all versions, and delete all previous versions while keeping the current version intact. This automation helps maintain a clean and efficient document library without manual intervention.

If you have any questions or need further assistance, feel free to reach out! 😊

Thursday, April 24, 2025

To open or edit code in Linux server

we can use various terminal-based editors depending on what's installed on your Linux server. Here are a few ways to do it:

For example, the code resides in /var/www/proj_management.

🛠️ View files in the project directory:

bash
ls -la /var/www/proj_management

✏️ Edit a specific file (e.g., index.php):

Using nano (simple editor):

bash
sudo nano /var/www/proj_management/index.php

Using vim (powerful, but has a learning curve):

bash

sudo vim /var/www/proj_management/index.php

Using code (if Visual Studio Code CLI is installed):

bash
sudo code /var/www/proj_management


If you're accessing the server via SSH and want to edit with a GUI-based editor like VS Code on your local machine,
you can use Remote - SSH extension in VS Code.

----------------------------------------------------------

If you want to use Remote - SSH extension in VS Code to open and work with files on a remote Linux server (like your /var/www/proj_management directory), here’s a quick setup guide:


Step 1: Install Remote - SSH Extension in VS Code

  1. Open VS Code.

  2. Go to the Extensions panel (Ctrl+Shift+X).

  3. Search for “Remote - SSH”.

  4. Click Install.


Step 2: Add SSH Configuration

  1. Press Ctrl+Shift+P to open the Command Palette.

  2. Type Remote-SSH: Add New SSH Host and select it.

  3. Enter your SSH command, e.g.:

    bash
    ssh your_username@your_server_ip
  4. Choose the SSH config file to save this entry (usually ~/.ssh/config).


Step 3: Connect to the Server

  1. Open the Command Palette again (Ctrl+Shift+P).

  2. Select Remote-SSH: Connect to Host.

  3. Choose your saved server from the list.

  4. VS Code will open a new window connected to the remote server.


Step 4: Open Your Project Directory

Once connected:

  1. Click File > Open Folder.

  2. Enter:

    bash
    /var/www/proj_management
  3. You now have full access to browse, edit, run, and debug the code remotely as if it's on your local machine.


Tuesday, April 22, 2025

30 Websites for job seekers to check out in 2025!

 Forget Naukri, Upwork, Fiver, and Indeed 

These are overcrowded...

Here are 30 Websites for job seekers to check out in 2025! 

🏷Save this post for Later use 

1. SimplyHired (simplyhired.com)

2. Jobspresso (jobspresso.co)

3. Stack Overflow Jobs (stackoverflow)

4. Outsourcely

5. Toptal (toptal.com)

6. Skip The Drive (skipthechive.com)

7. NoDesk (nodesk.co)

8. RemoteHabits (remotehabits.com)

9. Remotive (remotive.com)

10. Remote4Me (remote4me.com)

11. Pangian (pangian.com)

12. Remotees (remotees.com)

13. Europe Remotely (europeremotely.com)

14. Remote OK Europe (https://lnkd.in/gr4C-mjp)

15. Remote of Asia (https://lnkd.in/ghrA_z9u)

16. FlexJobs (flexjobs.com)

17. Remote.co (remote.co)

18. We Work Remotely (weworkremotely.com)

19. RemoteOK (remoteok.com)

20. AngelList (angel.co)

21. Linkedin (linkedin.com)

Resume-Making Websites 🎯 

1. Canva - canva.com

2. Resume Genius - resumegenius.com

3. Zety - zety.com

4. Novoresume - novoresume.com

5. Resume.com - resume.com

6. VisualCV - visualcv.com

7. Enhancv - enhancv.com

8. Resume.io - resume.io

9. My Perfect Resume - myperfectresume.com

10. SlashCV - slashcv.com


Interview Preparation Websites📚

1. InterviewBit - interviewbit.com

2. Glassdoor - glassdoor.com

3. Interviewing.io - interviewing.io

4. Jobscan Interview Prep - jobscan.co/interview

5. Indeed Interview Tips - indeed.com/career-advice

6. CareerCup - careercup.com

7. The Muse - themuse.com

8. PrepLounge - preplounge.com

9. Big Interview - biginterview.com


Google is offering FREE online courses with certification.

𝗙𝗥𝗘𝗘 (𝗚𝗼𝗼𝗴𝗹𝗲) 𝗖𝗼𝘂𝗿𝘀𝗲𝘀 𝘆𝗼𝘂 𝘄𝗶𝗹𝗹 𝗿𝗲𝗴𝗿𝗲𝘁 𝗻𝗼𝘁 𝘁𝗮𝗸𝗶𝗻𝗴 𝗶𝗻 𝟮𝟬𝟮𝟱.

🎉 Start Learning Now

🔃7000+ free courses free access: https://lnkd.in/gaE8D-FW

1. Google data Analytics

https://lnkd.in/dF69UPKS

2. Google Project Management

https://lnkd.in/dyDdPT3C

3. Foundations of Project Management

https://lnkd.in/dc7HBE8v

4. Google Introduction to Generative AI

https://lnkd.in/dBpavRzd

5. Google Cybersecurity 

https://lnkd.in/dEkKJA57

6. Google UX Design

https://lnkd.in/d8DCCrT9

7. Google Digital Marketing & E-commerce:

https://lnkd.in/d2dcwWyJ

8. Google IT Support:

 https://lnkd.in/gj7SEh22

9. Web Applications for Everybody Specialization: 

https://lnkd.in/d7J_urhb

10. Get Started with Python

https://lnkd.in/dbVfekE6

11. Learn Python Basics for Data Analysis

https://lnkd.in/dKxTMVkj

12. Google Advanced Data Analytics Capstone

https://lnkd.in/dhXHt4AH

13. Data Analysis with R Programming

https://lnkd.in/dHqdPBVz

14. IBM Full Stack Software Developer Professional Certificate

https://lnkd.in/dxg6NYns

15. Introduction to Web Development with HTML, CSS, JavaScript​

https://lnkd.in/ds6gMSND

16. IBM Back-End Development Professional Certificate

 https://lnkd.in/dNJq5d3C

17. IBM Python for Data Science, AI & Development:

 https://lnkd.in/dxjgY8mx

Monday, April 7, 2025

Extracting x-ms-exchange-parent-message-id from a Text File Using Python

In the world of email processing and automation, extracting specific headers from email metadata can be crucial for various tasks. One such header is the x-ms-exchange-parent-message-id, which can be essential for tracking email threads and parent-child relationships in email conversations. In this blog post, we'll walk through a simple Python script to extract this header from a text file.

Why Extract x-ms-exchange-parent-message-id?

The x-ms-exchange-parent-message-id header is used to identify the parent message in an email thread. This can be particularly useful for:

  • Email Threading: Keeping track of email conversations.
  • Automated Email Processing: Automating responses or actions based on the parent message.
  • Data Analysis: Analyzing email communication patterns.

The Python Script

Here's a step-by-step guide to creating a Python script that reads a text file and extracts the x-ms-exchange-parent-message-id header.

Step 1: Import the Required Module

First, we'll import the re module, which provides support for regular expressions in Python.

import re

Step 2: Define the Function

Next, we'll define a function extract_parent_message_id that takes the file path as a parameter, reads the file content, and searches for the x-ms-exchange-parent-message-id header.

def extract_parent_message_id(file_path):
    # Read the content of the file
    with open(file_path, 'r') as file:
        data = file.read()
    
    # Regular expression to find the x-ms-exchange-parent-message-id
    pattern = r'x-ms-exchange-parent-message-id:\s*<([^>]+)>'
    
    # Search for the pattern in the data
    match = re.search(pattern, data)
    
    # Extract and return the parent message ID if found
    if match:
        return match.group(1)
    else:
        return "x-ms-exchange-parent-message-id not found"

Step 3: Use the Function

Finally, we'll use the function to extract the x-ms-exchange-parent-message-id from a sample text file.

# Example usage
file_path = 'path/to/your/file.txt'
parent_message_id = extract_parent_message_id(file_path)
print("x-ms-exchange-parent-message-id:", parent_message_id)

Conclusion

With this simple script, you can easily extract the x-ms-exchange-parent-message-id from any text file containing email headers. This can be a powerful tool for anyone working with email data, whether for automation, analysis, or other purposes.

Feel free to adapt and expand this script to suit your specific needs. Happy coding!

🧹 Clean Up SharePoint Online File Versions: Keep Only the Latest 5 in a Specific Folder Using PnP PowerShell

 Versioning in SharePoint Online is a powerful feature that allows teams to maintain historical copies of documents. However, over time, the...