How to Take Ownership of Files and Folders Using PowerShell
Ever had to take ownership of a bunch of files and folders? It’s a pain, right? Well, not anymore!
The Problem
Picture this: You’ve just gotten an external hard drive from a dead computer and need to access the files. But wait! You don’t have the correct permissions. I had to do this, and setting the file permissions through Explorer was failing randomly. It appears that the folders all had different permissions, and the propagation was failing.
The Solution
I’ve got a PowerShell script that’ll save you time. It does two things:
- Takes ownership of a folder and all its subdirectories and files (recursively) and sets the owner to the current logged-in user
- Adds the current user to the permissions with full control
The Script
First, here’s the script. Don’t worry, I’ll break it down for you:
# Ensure the script is running with administrator privileges
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You do not have Administrator rights to run this script!`nPlease re-run this script as an Administrator!"
Break
}
# Get the current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# Function to take ownership and set permissions
function Set-OwnershipAndPermissions {
param (
[string]$path
)
try {
# Take ownership
$acl = Get-Acl $path
$owner = New-Object System.Security.Principal.NTAccount($currentUser)
$acl.SetOwner($owner)
Set-Acl -Path $path -AclObject $acl -ErrorAction Stop
# Set permissions
$acl = Get-Acl $path
if (Test-Path -Path $path -PathType Container) {
# It's a directory
$permission = $currentUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
} else {
# It's a file
$permission = $currentUser, "FullControl", "None", "None", "Allow"
}
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
Set-Acl -Path $path -AclObject $acl -ErrorAction Stop
Write-Host "Successfully processed: $path"
}
catch {
Write-Warning "Failed to process $path. Error: $_"
}
# Process subdirectories and files if it's a directory
if (Test-Path -Path $path -PathType Container) {
try {
Get-ChildItem $path -Force -ErrorAction Stop | ForEach-Object {
Set-OwnershipAndPermissions $_.FullName
}
}
catch {
Write-Warning "Failed to access contents of $path. Error: $_"
}
}
}
# Prompt for the folder path
$folderPath = Read-Host "Enter the full path of the folder"
# Check if the folder exists
if (Test-Path $folderPath) {
# Run the function
Set-OwnershipAndPermissions $folderPath
Write-Host "Process completed for $folderPath and all accessible contents."
} else {
Write-Host "The specified folder does not exist."
}
How to Use It
- Copy this script and save it as a
.ps1
file (liketake_ownership.ps1
). - Right-click on PowerShell and select “Run as administrator” (this is crucial!).
- Navigate to where you saved the script.
- Run it by typing
.\take_ownership.ps1
. - When prompted, enter the full path of the folder you want to process.
What’s Going On Here?
Let’s break this down a bit:
- Admin Check: The script starts by ensuring you run it as an admin. No admin rights? No dice.
- Current User: It grabs the current user’s name. This is who’s going to own everything.
- The Magic Function:
Set-OwnershipAndPermissions
is where the real magic happens. It:- Takes ownership of the item (file or folder)
- Sets the current user as the owner
- Gives the current user full control
- If it’s a folder, it does all this recursively for everything inside
- Error Handling: The script’s got your back with some neat error handling. It’ll let you know if it can’t process something and keep on truckin’.
- File vs. Folder: It’s smart enough to know the difference between files and folders and set the right permissions for each.
Why This is Awesome
- Time Saver: Imagine doing all this manually. Yikes!
- Consistency: It applies the same permissions everywhere, no mistakes.
- Flexibility: Works on any folder you point it to.
Wrapping Up
There you have it, folks! A powerful little script to take control of your files and folders. No more permission headaches, no more “access denied” nightmares — just pure, unadulterated file access bliss.
Got questions? Hit me up in the comments. And don’t forget to share this with your IT buddies – they’ll thank you later!
Happy scripting!
How to enable MacFuse/PCloud Drive on Mac Sonoma 14.2.1
I recently upgraded to Mac Sonoma 14.2.1 and MacFuse stopped loading which affected my ability to load PCloud and NTFS drives. I spent a few days trying to troubleshoot everything and in the end it turned out I had to disable Mac System Integrity Protection to get everything to load. I’m sharing in case it helps anyone else.
To disable SIP on your Mac Sonoma for extensions like MacFuse and pCloud Drive:
- Shut down your Mac: Turn off your Mac completely by pressing and holding the power button until the screen goes black.
- Restart in Recovery Mode: Enabling Recovery Mode depends on your Mac. You can try the steps below or follow Apple’s guide here.
Power on your Mac and immediately press and hold Command (⌘) + R to enter Recovery Mode.
Power on your Mac and hold the power button down until Other Options displays. - Open Terminal: In Recovery Mode, select “Utilities” in the macOS Utilities window and select “Terminal.”
- Disable SIP: Type
csrutil disable
in Terminal and press Enter. This disables System Integrity Protection (SIP). - Restart Mac: Click the Apple menu and select “Restart” to reboot your Mac with SIP disabled.
- Re-enable SIP (if needed): Follow the same steps but use
csrutil enable
in Terminal to re-enable SIP.
Note: Disabling SIP poses security risks. Re-enable it once you’ve installed the necessary extensions. Only disable SIP when necessary and understand the potential risks involved.
How to Delete a Row in Excel Using the Elgato Stream Deck
Recently I was working on a massive Excel Spreadsheet and needed to manually review each entry and clean up rows that were no longer needed. The Elgato Stream Deck came in handy for a quick shortcut so I thought I’d share it in case anyone else can use it.
I took this opportunity to practice creating the first of what I hope are many training videos. This took me around 30 minutes to do from start to finish as I had to learn the video editing software including how to record, how to split and edit, and how to add text overlays. Hopefully the next videos will be faster but it was a fun exercise and I hope someone else finds it useful.
How to Delete Folder with Special Character in Windows 10/11
I ran into an issue where a folder was created by some application with a special Unicode character that Windows Explorer doesn’t seem to play nicely with. I also was unable to tell what the character was since nothing would reveal it. The folder’s there, but you can’t rename or delete it. If I tried to remove or delete it, I’d get an error saying the folder doesn’t exist:
I have LockHunter installed but it wasn’t able to delete it for some reason. The easiest way I found to delete the folder was to use Git Bash and then use the appropriate commands to rename or delete the folder.
Browse to the folder where the offending folder is located. For example purposes, I’ll use c:\temp\folder1
cd c:/temp
Rename:
mv fol (hit tab to autocomplete) folder1
Delete:
del fol (hit tab to autocomplete)
If you don’t have Git Bash or are not a developer/power user, you can download the portable version from https://git-scm.com/download/win to use temporarily. Once you decompress the files to a folder, you’ll find git-bash.exe which you can double-click to run and use the above commands.
How to deploy a React app to Amazon S3 using Gitlab CI/CD
I’ve been trying to build more CI/CD scripts using Gitlab to automate pipeline deployments for work. Here’s a useful one for building and deploying a React app to Amazon S3.
You’ll need to add a variable called S3_BUCKET_NAME to your repo or replace the variable with your bucket path.
stages:
- build
- deploy
build react-app:
#I'm using node:latest, but be sure to test or change to a version you know works. Sometimes node updates break the npm script.
image: node:latest
stage: build
only:
- master
script:
# Set PATH
- export PATH=$PATH:/usr/bin/npm
# Install dependencies
- npm install
# Build App
- CI=false npm run build
artifacts:
paths:
# Build folder
- build/
expire_in: 1 hour
deploy master:
image: python:latest
stage: deploy
only:
- master
script:
- pip3 install awscli
- aws s3 sync ./build s3://$S3_BUCKET_NAME --acl public-read
How to Setup CI/CD of Jigsaw Site to Digital Ocean Droplet Using Bitbucket Pipelines
I created a new personal resume site and decided I wanted to build a static site since it wouldn’t be frequently updated. I evaluated Nuxt, Gatsby, and a few others but settled on Jigsaw, a static site generator based on Laravel. I had never used it before and figured this would be a good learning experience while building something I needed. I was pleasantly surprised by how easy it is to use and setup, so kudos to the Tighten team for putting together such an elegant solution.
I wanted to get a CI/CD pipeline configured to handle the site’s deployment but couldn’t find any working tutorials, so I’m sharing my solution in case it helps others. I’m using Bitbucket for this since it’s a personal private repo, so I’m using Bitbucket Pipelines.
Instructions
After you enable pipelines for your project, you’ll need to configure a Pipelines Repository Variable in your project. Go to the settings tab in your repo, and then select Repository variables:
Add 3 variables:
- USER_NAME – The SSH user name you want Bitbucket to use to connect to your server.
- PRODUCTION_HOST – Your domain that Bitbucket should connect to
- FOLDER – Folder Path where the site should be deployed to
Generate an SSH key (or use your own) and add it to your server under the SSH Keys tab in Pipelines:
I generated a new key and then added it to ~/.ssh/authorized_keys for the account.
Add this YAML snippet to your bitbucket-pipelines.yml in your root. This will use PHP 7.4, install rsync, node + npm, composer, and build the production version of the site to deploy to the specified folder.
The -aVP switch for rsync is to give me verbose progress feedback so I can see what’s happening. If you don’t need the detail, switch it to -a.
image: php:7.4-fpm
pipelines:
branches:
master:
- step:
name: Jigsaw Build
script:
- apt-get update && apt-get install -y unzip
- apt-get install rsync openssh-client nodejs npm -y
- curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
- composer install
- npm install
- npm run production
- rsync -avP build_production/ $USER_NAME@$PRODUCTION_HOST:$FOLDER --exclude=bitbucket-pipelines.yml --chown=www-data:www-data
I received a few errors when rsync ran. In case you run into them as well, here’s the list and fixes. The first was:
rsync: failed to set times on "$FOLDER": Operation not permitted (1)
I added --no-t
to resolve that and then got a new error:
rsync: failed to set permissions on "$FOLDER": Operation not permitted (1)
which was fixed with adding the switch --no-perms
. My final rsync command became:
rsync -avP --no-t --no-perms build_production/ $USER_NAME@$PRODUCTION_HOST:$FOLDER --exclude=bitbucket-pipelines.yml --chown=www-data:www-data
How to Clear Archive & Read-only flags on Files in Windows in Bulk
I ran into an issue where I had to move files from one system to another and was running into issues because files had been set as read-only, had the archive flag set, or both. It was causing the system to skip files which wasn’t acceptable. Normally you could just use Windows to clear it in bulk, but that could potentially mess up file permissions. I needed a way to automatically just clear all flags but respect permissions.
I did some searching and didn’t find a utility that would do the job and most of the solutions I found required Powershell which wasn’t available on the system I was on. I ended up writing a quick console application in C# to do the trick. I’ve made it free and open sourced it in case anyone wants to use it.
If you need just the app, you can find the release build here with instructions. The app also prompts for input to make things a bit easier to use. There’s no install, no tracking or metrics, or anything else related to privacy concerns in this app. It’s a simple throwaway utility to get the job done and move on.
https://github.com/gregvarghese/clearflags/releases/tag/1.0.0
If you want to see the source code, that is available here:
https://github.com/gregvarghese/clearflags/
Please note that I did this in about 10 minutes for my own use so error handling is pretty much non-existent. I mention this because I did run into one issue where Windows was somehow seeing a folder with files in it as a file and it couldn’t be deleted or renamed and the utility couldn’t get past it until it was resolved. I didn’t spend much time debugging and just used my Mac to rename the folder and Windows was able to recognize it after the change, so the utility was able to continue processing.
How to execute SSH command with Bitbucket Pipelines
I inherited an old site that someone else setup that is just a basic static HTML, which was deployed using a git pull on the server. I wanted to automate the deployment, and instead of using rsync as the site will be re-built, I realized I could just configure the Bitbucket Pipeline to use SSH and run the pull command. This is probably a fringe case but here’s the bitbucket-pipelines.yml in case anyone finds it useful.
Add the repository variables for $USER, $SERVER, and $FOLDER with the appropriate values and then you should be able to run the deployment.
pipelines:
default:
- step:
script:
- pipe: atlassian/ssh-run:0.2.8
variables:
SSH_USER: '$USER'
MODE: 'command'
SERVER: '$SERVER'
COMMAND: 'cd $FOLDER && git pull'
How to get website average latency in BASH
I was working on a project today and wanted to be able to get the average latency for an API that I was working on. Performance is a concern because we’re running the API over a VPN, and then SSH tunneling over to another server. I wanted a quick way to do it and wrote a little bash function that will calculate the average for me. I couldn’t find an example on how to do this online so I’m sharing in case anyone else runs into the same issue.
This is tested on Mac only. Add these two functions to your .bashrc and do a shellupdate in terminal to load the latest, or just grab my dotfiles from my github: https://github.com/gregvarghese/dotfiles
curlb(){
curl -s -o /dev/null -w '%{time_starttransfer}\n' "$@"
}
# Usage:
# latencyavg [# of times to run] [URL]
function latencyavg()
{
time=0.00
for (( c=1; c<=$1; c++ ))
do
num1=$(curlb $2 -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-US,en;q=0.8,ja;q=0.6' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36' -H 'Connection: keep-alive' --compressed)
echo "$c - $num1"
time=$(echo "$time + $num1" | bc -l)
done
echo "Total Time $time"
echo $(echo $time / $1 | bc -l)
}
Usage example:
latencyavg 20 https://www.godaddy.com
List of my must-have Alfred Workflows
Use a mac? You’ll want to grab Alfred App. I’m finding it an invaluable replacement for spotlight and the workflows allow me to supercharge my workflows. It’s so useful that I’ve purchased the Powerpack lifetime license.
In addition to the standard features, here are a list of the most useful workflows for dev/tech:
Kill process – by Nathan Greenstein (@ngreenstein)
I use it as an activity monitor for CPU usage, and from there I can easily force quit any process if needed. It’s easier to see all processes on the Alfred UI instead of opening Activity Monitor on your mac. There’s also the workflow Kill Application – by Sebastian Hallum Clarke (and also on his site you can find other cool workflows).
Timer – by Daniel Bader
I use this one a lot. It’s super simple and by writing “Timer” and the number of minutes, you can easily set a reminder. It’s great for anyone using the Pomodoro technique or even if you leave something on the stove and want to go back to work.
Copy SSH Public Key – By oldcai
This one saves me time when I need to deploy my SSH key on a new server. Type ‘pk [ssh key file name]’ and it’ll copy the ssh key to the clipboard.
Incognito – by Nedwood
I find myself using this when I need to test a page and bypass the cache. Type ‘incog [url]’ and it’ll launch a new chrome window in incognito mode.
Find Folder by Samvlu
Finds a folder by name. I find this is faster than spotlight in just about every search.
Smart Folders by Deanishe
List all the Smart Folders/Saved Searches (same thing) on your system and drill down into their contents. Works in much the same way as Alfred’s File Filter, but Smart Folders are also available outside Alfred and are a bit more flexible.
For example, you can configure a Smart Folder to show all video/audio/image files without having to specify each different filetype individually. If you already use Smart Folders, this workflow can save you the work of re-implementing them as File Filters.
What’s more, you can exclude specific filetypes with a Smart Folder, which Alfred cannot do.
Advanced Google Maps Search by stuartcryan
This workflow gives you some quick and dirty shortcuts into Google Maps:
Commands:
To Configure:
mapsethome <home address including street number, name, postcode> (i.e. what you would type into Google Maps)
mapsetwork <work address including street number, name, postcode> (i.e. what you would type into Google Maps)
Commands for Use:
maps <query> – Search Google maps for an address
dir <query> to <query> to <query> etc (seperate multiple addresses with ” to ” minus the quotes, and you will get a multiple location search)
dirfw Show directions from Work to address
dirfh Show directions from Home to address
dirtw <query> Show directions from query to Work address
dirth <query> Show directions from query to Home address
trafficw – Show traffic from Home to Work
traffich – Show traffic from Work to Home
StackOverflow Search by deanishe
If you use stackoverflow as much as I do, this is a must-have.
Date Calculator
I find myself needing to calculate differences between dates in my personal life a lot lately. This workflow saves me a lot of time to do that. Want to know how far Christmas is away in days? ‘dcalc 12-25-16 – now d’ returns the number of days (assuming you’re using the US short format like I am).
Wifi Control by miroman
All my Macbooks periodically have issues with wifi. I’ve never been able to figure out what’s causing it but I use Wifi Control to restart the wifi which allows me to connect successfully.
Bugnot by vitor
If you use bugmenot at all, this is a useful extension to get logins without loading a new tab. Type ‘bn domain.com’ and you’ll get a list of matching passwords to use.