r/ScriptSwap • u/qedlab • Oct 27 '21
r/ScriptSwap • u/troylatroy • Apr 08 '21
[BASH] Request. Move and rename multiple files
As the title says, I need to move and rename .pdf files from one dir to another. The name has to have the date with a number on the end. It's on an Ubuntu server.
Below is what I am trying.
!/bin/bash
d=$(date +%Y%m%d%H%M%S)
counter=1
cd /path/to/files
for f in *.pdf; do
mv -- "$f" "$d-$((counter))${f%.pdfl}.pdf" /other/path/.
done
exit
It does move the files but it isn't renaming.
r/ScriptSwap • u/[deleted] • Oct 14 '20
Help with a modification to an existing script.
Hello,
I am wondering if anyone could assist me. I have a need to determine if a specific user account (local user account) has a password set.
I have a script that I found at ServerFault. https://serverfault.com/questions/930582/check-whether-user-account-has-password-set and this script works great. It will scan the local accounts and output if the local accounts do not have a password.
I am wondering if someone could help me modify this script to search for a predefined user account rather than scanning all user accounts.
As an example I am looking for the user account ="pogo246" .
Anyway, if you do have a moment to look I would be very greatful.
Thanks in advance
r/ScriptSwap • u/mmguero • Oct 13 '20
[bash] clone all of a GitHub user's or organization's repositories and set up upstream remotes for forks
Here's a gist for those who prefer reading the code on GitHub or in case I update it.
This script requires you to have a GitHub personal access token.
#!/bin/bash
# "git clone" all of a GitHub user's or organization's repositories (up to 100)
# if the repo is a GitHub fork, add the parent fork as an upstream remote.
ENCODING="utf-8"
function print_usage() {
echo "Usage: $(basename $0)" >&2
echo -e "\t -v\t(optional)\tverbose bash\t\tdefault FALSE" >&2
echo -e "\t -e\t(optional)\tfail on first error\tdefault FALSE" >&2
echo -e "\t -g\t(optional)\tgit@ vs. https:// clone\tdefault https://" >&2
echo >&2
echo -e "\t -t XXX\t\t\tGitHub OAUTH token\tdefault \$GITHUB_OAUTH_TOKEN env. variable" >&2
echo >&2
echo -e "\t -o\torganization name" >&2
echo -e "\t OR" >&2
echo -e "\t -u\tuser name" >&2
echo >&2
echo -e "\t -p XXX\t(optional)\tupstream remote name\tdefault \"upstream\"" >&2
}
GIT_API_URL_PREFIX="https://api.github.com"
GIT_CLONE_URL_PREFIX="https://github.com/"
GIT_CLONE_URL_SUFFIX=""
UPSTREAM_NAME=upstream
REMOTE_NAME=
TOKEN=${GITHUB_OAUTH_TOKEN:-""}
API_ENTITY_NAME=
API_ENTITY_TYPE=
while getopts 'vegt:o:u:r:p:' OPTION; do
case "$OPTION" in
# enable verbose bash execution tracing
v)
set -x
;;
# exit on any process error
e)
set -e
;;
# use git@ instead of https:// to checkout
g)
GIT_CLONE_URL_PREFIX="[email protected]:"
GIT_CLONE_URL_SUFFIX=".git"
;;
# specify GitHub OAUTH token (defaulted to $GITHUB_OAUTH_TOKEN above)
t)
TOKEN="$OPTARG"
;;
# organization name, if organization
o)
API_ENTITY_NAME="$OPTARG"
API_ENTITY_TYPE=orgs
;;
# user name, if user
u)
API_ENTITY_NAME="$OPTARG"
API_ENTITY_TYPE=users
;;
# name for "origin" remote (defaults to the repository project name)
r)
REMOTE_NAME="$OPTARG"
;;
# name for "upstream" remote (defaults to "upstream")
p)
UPSTREAM_NAME="$OPTARG"
;;
?)
print_usage
exit 1
;;
esac
done
shift "$(($OPTIND -1))"
if [[ -z $API_ENTITY_NAME ]] || [[ -z $TOKEN ]]; then
# no organization/user or token
print_usage
exit 1
fi
# default "origin" remote to the repository project name
[[ -z $REMOTE_NAME ]] && REMOTE_NAME="$API_ENTITY_NAME"
# retrieve and loop through the organization's|user's repositories
for REPO_NAME in $(curl -sSL -H "Authorization: token $TOKEN" "$GIT_API_URL_PREFIX/$API_ENTITY_TYPE/$API_ENTITY_NAME/repos?per_page=100" | \
jq -r '.[] | .html_url' | \
sed "s/.*github\.com\///g" | \
sort -u); do
# do the clone
PROJECT_NAME="$(basename "$REPO_NAME")"
git clone -o "$REMOTE_NAME" --recursive "${GIT_CLONE_URL_PREFIX}${REPO_NAME}${GIT_CLONE_URL_SUFFIX}" ./"$PROJECT_NAME" || continue
pushd ./"$PROJECT_NAME" >/dev/null 2>&1
# if there is a fork, set up the upstream remote
PARENT_FORK_URL="$(curl -f -sSL -H "Authorization: token $TOKEN" "$GIT_API_URL_PREFIX/repos/$REPO_NAME?per_page=100" | jq -r '.parent.html_url' 2>/dev/null)"
if [[ -n $PARENT_FORK_URL ]] && [[ $PARENT_FORK_URL != "null" ]]; then
git remote add "$UPSTREAM_NAME" "$PARENT_FORK_URL"
git remote set-url --push "$UPSTREAM_NAME" no_push
git fetch "$UPSTREAM_NAME"
fi
git fetch --all
popd >/dev/null 2>&1
done # end repositories loopEDIT: added ?per_page=100
r/ScriptSwap • u/[deleted] • Jun 19 '19
[Bash] generate/use passwords without saving to database
Thoughts and suggestions about this?
r/ScriptSwap • u/snarwan • May 15 '19
[Python] Reddit Text To Speech
https://github.com/sarjann/reddit_text_to_speech
Allows you to browse a subreddit's hot posts and play audio from a post.
r/ScriptSwap • u/ASarcasticUsername • Dec 07 '18
[Batch] Bget
INTRODUCTION
Bget is a batch-file command-line tool for handling Windows scripts. It is built to be a companion to those who write, use and maintain Windows scripts. It helps those who use scripts easily download, update and remove scripts. It’s built for scripters, by scripters.
Features
Download scripts from the Bget server: These scripts are vetted and sorted by us. We’ve gone about curating some of the most interesting scripts we could find that we think would be interesting and useful to you as well.
Download scripts from Pastebin: Pastebin has long been the coder’s friend, and so we added the ability to fetch scripts from Pastebin. These scripts are not pre-vetted however, but they offer the ability for fast code downloading without waiting for us to vet them.
Update scripts: Rather than manually re-download the latest version of every script, Bget handles that for you, getting the latest version of any script you’ve downloaded. Easily remove scripts: Don’t like a script you downloaded? Easily remove it with Bget. One command and it’s buh-bye script.
View script info: This allows you to see basic information about a script such as its name, author and description, allowing you to make an informed decision before downloading.
Bget also allows you to list all scripts on the server and list downloaded scripts on the local computer.
Upgrade feature: Bget also updates itself so you always stay up-to-date.
Multiple download methods: Bget has many ways to get a script. These are: Jscript, VBScript, Powershell, BITSAdmin and CURL.
The Goal
The objective is to create an apt-like utility for windows scripters so we need not scour the internet in search of this-or-that tool.
I'd really like for the batch community to give this tool a try and provide valuable feedback.
Thanks.
r/ScriptSwap • u/[deleted] • Feb 07 '18
venv - a very simple python virtualenv manager
Though my primary focus is in Rust, I've had quite a few projects in Python recently. Over the past year, I've gained more and more appreciation for virtual environments. They're very useful for both development and deployment, in situations where you don't want to clutter the host system with a bunch of random modules pertaining to one program. However, there are a few things that just don't sit well with me.
Activating them is a PITA. Firstly, you have to remember (or look for) the directory that you left your virtualenv in for the project. Typically, the searching isn't the hard part, but having to write out the entire path to the
activatesource file just isn't a pretty solution here.Speaking of the directory, what is the freaking standard? Am I going to put it in
./.venv,./venv,~/.venv/...,~/venvs/...?? Nobody seems to have the same answer to this question, and that kind of uncertainty in my life upsets me.Deactivating - is there even such a thing? Yes, I know that there really isn't a point in "deactivating" the environment because there's not much harm, but sometimes I just want to reuse the shell in-place without reopening it (tiling WMs for the win). Additionally, that tag on the prompt is a major distraction for me - it does not belong there if that's not what I'm using this shell for anymore.
Oh wait, that tag. Isn't it kind of annoying that it looks like
(.venv)with no descriptive name? And if I want to create a custom name, I have to use the--promptflag on creation? Why would this kind of functionality be imnplemented in the most inconvenient/non-ergonomic way?
This last month or so, I sat down and wrote a few scripts and set a few standards for myself for managing my virtual environments. This is the end result; I've compiled them into a single shell script that I can distribute to wherever I need it. It features a central directory for storing all created virtualenvs, and it sources the activate script in a new shell process so I can type exit and be back at the default prompt.
Source Code
This work is licensed as public domain; I have no intent to try to protect it as my "intellectual property." Do with it what you wish, and I hope you find it useful!
The source is alsohosted on GitLab.
#!/bin/bash
#
# virtual environment management script
# author: adam gausmann
# licensed under public domain. you are free to use, modify,
# and distribute as you wish.
#
VENV_HOME="$HOME/.venv"
case $1 in
create)
if [ -e "$VENV_HOME/$2" ]
then
echo "'$2' already exists. To activate, type \`$0 activate $2\`."
exit 1
fi
mkdir "$VENV_HOME/$2"
virtualenv "$VENV_HOME/$2"
echo "Virtual environment '$2' created. To activate, type \`$0 activate $2\`."
;;
delete)
if ! [ -e "$VENV_HOME/$2" ]
then
echo "Virtual environment '$2' does not exist."
exit 1
fi
rm -r "$VENV_HOME/$2"
echo "Virtual environment '$2' deleted."
;;
activate)
if ! [ -e "$VENV_HOME/$2" ]
then
echo "Virtual environment '$2' does not exist."
exit 1
fi
echo "'$2' activated. To deactivate, type \`exit\`."
bash --init-file <(cat /etc/profile ~/.bashrc "$VENV_HOME/$2/bin/activate")
;;
esacr/ScriptSwap • u/[deleted] • Jun 14 '17
Notificator (Reminder script)
What this script does is pop up a message box with reminders from a specific date if one is present in the data file. You can also have TV programmes show up too.
https://pastebin.com/9AuQDjtc - Script https://pastebin.com/HgJuq1Ln - Data file example.
I also made it so it'll send these reminders to your phone!
Basically, it's a calendar script, but without the annoying calendar feel (which I personally hate).
Enjoy.
r/ScriptSwap • u/expectocode • May 02 '17
Analyse Telegram chatlogs easily - a collection of 11 Python scripts [MIT]
https://github.com/expectocode/telegram-analysis
New features are in development ;)
r/ScriptSwap • u/trebk • Sep 04 '16
Steam game price checker and observer
-PYTHON 3-
With this script you can watch your desired games' prices on steam store and check the price is less or equal than your target price. If that is true, the script will alert you with a little messagebox.
https://github.com/tr3boo/steam-price-checker
My first script so tell me your opinion
r/ScriptSwap • u/faubiguy • Aug 06 '16
[Bash] Set default applications in GNU/Linux
This is a bash script that takes the name of an application and sets it as the default application (as used by xdg-open) for all the file types it supports. Note that xdg-mime must be installed and this only works if the application has a .desktop file in /usr/share/applications (most should put one there when installed).
https://gist.github.com/faubiguy/dc2c0099e219494e15426523720548e7
#!/bin/bash
if [[ $# -eq 0 ]]; then
echo "Must specify an application"
exit 1
fi
# Find the .desktop file for the specified application
app="${1%.desktop}"
desktop="$app.desktop"
desktopfile="$(find /usr/share/applications -iname "$desktop" | head -1)"
if [[ ! -e "$desktopfile" ]]; then
echo "Application '$app' not found"
exit 1
fi
# Get the list of mimetypes handled by the application
mimetypes=$(grep '^MimeType=' "$desktopfile" | sed 's/^.*=//;s/;/\n/g' | sed -n '/./p')
if [[ "$mimetypes" == "" ]]; then
echo "Application '$app' does not specify any mime types"
exit 1
fi
# Get confirmation from user before changing anything
echo "Okay to set '$app' as default for the following mime types? [y/N]"
echo "$mimetypes" | sed 's/^/ /'
read -r yesno
if [[ ! "$yesno" =~ ^[yY].*$ ]]; then
echo "Cancelled setting '$app' as default application"
exit 1
fi
errortypes=""
# Set application as default for each type, recording errors
while read -r mimetype; do
if ! xdg-mime default "$desktop" "$mimetype"; then
errortypes="$errortypes$mimetype\n"
fi
done <<< "$mimetypes"
# Count failures and successes
total=$(echo "$mimetypes" | wc -l)
errors=$(echo -n "$errortypes" | wc -l)
successful=$((total - errors))
# Give feedback to user
echo "Successfully set '$app' as default application for $successful/$total mime types"
if [[ $errors != 0 ]]; then
echo "Errors occured while trying to set '$app' as the default application for the following mimetypes:"
echo -n "$errortypes" | sed 's/^/ /'
fir/ScriptSwap • u/[deleted] • Jun 30 '16
Server Ping Script for r/2007scape
I'm trying to make a script that will ping old school runescape servers and output the results to a text file in the temp folder. I'd really like some help with finding a way to display the results via domain name (or server name) instead of IP. This is my first powershell script, so feel free to shred my script!
https://github.com/FireSpark142/RunescapePing/blob/master/RunescapePingTest.ps1
r/ScriptSwap • u/bzsparks • Apr 07 '16
[Python3] apcupsd-alert, scripts for alerting on apcupsd events.
The other day I had some spare time, a raspberry pi, and a battery backup unit so I decided to work on a small project. apcupsd is a daemon to monitor battery backup units. It was written for APC units but I'm successfully using it with a Cyberpower CP1500AVRLCD.
The scripts currently included in the repository are:
onbattery.py
offbattery.py
createDb.py
required-EXAMPLE.json
Both the on and off battery scripts are designed to be incorporated into the apccontrol script included with the apcupsd package. The createDB script will create a sqlite3 database that both on and off battery will utilize. Finally the required.json file is where you put your personally identifiable information that will be used to send the alerts.
The repository is here: https://github.com/bzsparks/apcupsd-alert
r/ScriptSwap • u/ATGUNAT • Oct 08 '15
Download imgur albums from subreddits V2
This is a bash script that downloads imgur albums from subreddits. It has a lot of improvements over the last script I wrote. You'll need imguralbum.py for this to work. Imgur has changed the way the site works slightly so you will need to remove the +/noscript from line 63 of imguralbum.py or it will download empty albums imguralbum.py has been updated
#!/bin/bash
now=$(date +%Y_%m_%d_%T)
#down is where you want the files to be saved to
down=~/Pictures
#These are the subreddits you want to download imgur albums from
if [ "$1" == -h ]
then
printf "Help \n\n -lo Get links but does not download \n -l Logs time when ran\n"
exit
fi
subreddits=()
for i in "${subreddits[@]}"
do
echo "$i"
curl https://www.reddit.com/r/"$i".json >> /tmp/reddit_json
grep -o "http://imgur.com/a......" /tmp/reddit_json >> /tmp/links.txt
grep -o "https://imgur.com/a......" /tmp/reddit_json >> /tmp/links.txt
done
#This changes http to https
sed -i 's/https/http/g' /tmp/links.txt
sed -i 's/http/https/g' /tmp/links.txt
# This puts each link on a newline
awk '{ for (i=1;i<=NF;i++) print $i }' /tmp/links.txt
#Passing the script -lo only gets the links but does not download them
if [ "$1" == -lo ]; then
cat /tmp/links.txt >> ~/imgur_links
rm /tmp/links.txt
rm /tmp/reddit_json
exit
fi
while read line;
do
imguralbum.py "$line" "$down"
done < /tmp/links.txt
#Note it seems imgur has changed the way the site works meaning imguralbum.py no longer works as is. To make it work you need to remove the +/noscript from line 63 from imguralbum.py
# Logs when/if it ran
if [ "$1" == -l ]
then
touch ~/imgur_log
echo "Ran at $now" >> ~/imgur_log
fi
rm /tmp/links.txt
rm /tmp/reddit_jsonr/ScriptSwap • u/sbicknel • Jan 14 '15
[bash] up() function: move up the directory tree
I've seen several of these around, but all had some shortcomings, so I wrote one of my own:
up() {
#======================================================================
# move up the directory tree
# usage: up [N]
# N is an integer (defaults to 1)
#
# silently exits if non-numeric input given
# translates signed integers to absolute values
# ignores all but the first parameter
#
# exit codes:
# 0: success
# 1: invalid input
# 2: unable to change directory
# 255: nothing to do
#======================================================================
# convert parameter to an absolute value, if possible, or return error code
declare levels="${1:-1}" # set the number of levels up the directory tree to traverse
levels=${levels#*-} # strip leading negative sign
levels=${levels#*+} # strip leading positive sign
if [[ $levels =~ [^[:digit:]] ]]; then
return 1
fi
declare targetDir="$PWD" # new working directory starts from the current directory
# set targetDir to target directory
for (( l=1; l<=levels; l++ )); do
# %/* will produce an empty string in first-level directories. This handles that case
if [[ -n "${targetDir%/*}" ]]; then
targetDir="${targetDir%/*}"
else # set targetDir to / and break out of loop
targetDir=/
break
fi
done
# if new working directory is different from current directory, change directories
if [[ "$targetDir" != "$PWD" ]]; then
cd "$targetDir" || return 2 # if cd fails
else
return -1 # nothing to do (exit code = 255)
fi
}This one uses nothing but internal commands and breaks out of its loop when the root directory is reached. It only changes the directory when the target and $PWD don't match.
r/ScriptSwap • u/h2opologod94 • Dec 07 '14
[bash] Get Project Euler problem description and add to top of new file.
I submitted this to /r/projecteuler already, but I figured y'all might like it too.
This is a fairly customized script for me, but the beef of it should be easily adaptable. This script will take the first argument as the Project Euler problem number and create a new directory. Inside that dir, it will create a new C file, then add the nicely formatted Project Euler problem description at the top of the file in a comment. It also adds a little bit of a C template (calling one lib and starting main) and creates a basic Makefile.
https://github.com/JohnMoon94/Project-Euler/blob/master/getProblem.sh
This is what is gives me after running ./getProblem 75 : http://i.imgur.com/GFramar.png
I'm a pretty amateur programmer, but let me know what you think! If you adapt it for another language, I'd also love to see it. Thanks!
r/ScriptSwap • u/akaleeroy • Nov 06 '14
[batch] Ping a list of domains one-liner command
To use at the console:
for %a in (tradermail.info zippymail.info monumentmail.com) do ping -n 1 -w 200 %a | find "Request timed out" && echo %a >> Dead-Mailinator-Alt-Domains.txtAs batch script (%%a instead of %a):
for %%a in (tradermail.info zippymail.info monumentmail.com) do ping -n 1 -w 200 %%a | find "Request timed out" && echo %%a >> Dead-Mailinator-Alt-Domains.txtr/ScriptSwap • u/sbicknel • Aug 30 '14
[bash] Medley Grid Video Player
A shell script that takes a list of video files and plays them in an on-screen grid in random order. Options include explicitly setting the aspect ratio used for spacing videos in the grid, setting how many videos to place in each row, how wide each video should be, whether to unsort the play list, and whether to play single videos or lists that will be played one at a time in full-screen mode.
Mplayer or mplayer2 must be installed. Unsort is optional.
The script assumes the user has KDE installed and looks in KDE’s configuration for the height of the panel, assuming that the user has only one configured. It also uses qdbus to inhibit the screensaver. These features can be changed or disabled in the code.
r/ScriptSwap • u/[deleted] • Jun 17 '14
WinRM Enable Script w/ PDQ Deploy
I'm trying to write a batch script to run remotely using PDQ Deploy that will enable WinRM to allow remote computers to connect with WinRS. Any WinRM command seems to cause PDQ to freak out and stop executing the rest of the script. I can maybe get lucky and get two WinRM commands in before the scripts ends.
Does anyone know of a script to enable this? I want to enable WinRM to run with compatibility listeners (ports 80 and 443), not the new WinRM 2.0 default ports (ports 5985 and 5986). My company will never allow 5985, 5986 to be open, so the compatibility listeners are a must.
Anyone have any ideas? I have all of the commands, but gettings them to execute remotely - even with a scheduled task seems tricky.
Steps my script current takes and fails when any WinRM command is run twice: Powershell script to change network location to 'Work' to bypass an annoying security feature. Change WinRM startup to automatic. Start WinRM Enable Compatibility listeners (ports 80 and 443). Enable basic authentication. Allow unencrypted access.
EDIT: Group policy is not an option for this unfortunately. I need to be able to deploy it to any computer that I have the local administrator credentials for, no matter what domain it is.
r/ScriptSwap • u/pushme2 • May 24 '14
[Bash] 4chan image downloader
This script is broken up into a bunch of different functions, one, so that the user can have a choice as to what they want to do, and second, because it is a huge PITA to debug bash...
Using 4front will automatically create a directory for each thread. The script could be extended to do the same to have a directory for each board as well.
I personally have a file at ~/.functions where this is stored (among other nifty functions I have). Then my ~/.bashrc has:
source ~/.functionsSo I can call the functions from anywhere, including other scripts. If for some reason it still doesn't work in another script, just put the source line it in at the top and it should work.
To use this script, you must have wget and curl.
update: I added a new function, 4update. Inside it exists an array called "BOARDS", simply add in whatever boards you want and it will automatically do everything for you.
#For a given thread, print all URLs to content like images.
#Example: $ 4parse "https://boards.4chan.org/k/thread/XXXXXXXX"
4parse(){
curl --silent --compressed $1 |
tr "\"" "\n" | grep -i "i.4cdn.org" |
uniq |
awk '{print "https:"$0}'
}
#Downloads all images in a thread. If TLS is a problem, remove the "s".
#Example: $ 4get "https://boards.4chan.org/k/thread/XXXXXXXX"
4get(){
wget --continue --no-clobber --input-file=<(4parse "$1")
}
#For a given board name, like "w", "b", etc... print all links to threads
#Example: $ 4threads w
4threads(){
curl -s "https://boards.4chan.org/"$1"/" |
tr "\"" "\n" |
grep -E "thread/[0-9]+/" |
grep -v "#" |
uniq
}
#Download all media in each thread currently on the front page.
#Example: $ 4front w
4front(){
4threads "$1" |
while read LINE; do
DIR4=$(echo "$LINE" | cut -c 8- | tr "/" "-")
URL=$(echo $LINE | awk -v r=$1 \
'{print "https://boards.4chan.org/"r"/"$0}')
echo $URL
mkdir -p "$DIR4"
cd $DIR4
4get $URL
cd ..
done
}
#Download front page of all boards in the BOARDS array.
#Example: $ 4update
4update(){
mkdir -p $HOME/Pictures/4chan/
DIR4CHAN="$HOME/Pictures/4chan/"
BOARDS=(e h s w)
for ITEM in ${BOARDS[@]}; do
mkdir -p "$ITEM"
cd $DIR4CHAN$ITEM
4front "$ITEM"
done
}r/ScriptSwap • u/Vutpa • May 04 '14
[Request] Automatically search through a folder, delete duplicate music tracks and store the rest in another folder
I'm in search for a script that does what I described in the title.
I have a folder with a lot of UK Top 40 Albums, and need something to look through them as soon as they are stored there, look for duplicates from another folder, delete the duplicates and then put the rest of the songs in the other folder.
How could I achieve this?
r/ScriptSwap • u/danekan • Nov 01 '13
[Powershell] Generate Excel report of current Office subscription status for machines in specified OUs
This script generates an Excel report of the current Microsoft Office 2010 / 2013 license status for subscription status.
We were getting a lot of calls from mainly new employees who when onboarding get the old user's subscription until the new user's license is purchased. Or in other scenarios, their system was new and just prompting them to authenticate their subscription, and they continuously ignore the activation wizard until Office deactivates.
http://gallery.technet.microsoft.com/scriptcenter/Office-Subscription-6034b7d6
r/ScriptSwap • u/vocatus • Jun 26 '13
[BATCH] OCPN: Orbital Cached Profile Nuker (delete old cached profiles)
crosspost from /r/usefulscripts
A while ago we had the requirement to delete old cached and roaming profiles for a large network, so I hacked together this script to do it remotely (or locally).
It's called OCPN or Orbital Cached Profile Nuker.
It takes an IP, hostname, or list of systems in a text file as the target, then prompts you for the age in days you want to nuke, deletes the matching profiles, and saves a log file of what it did. Also checks for missing required files (Delprof.exe etc) when running. OCPNv3 will also report to you what it will delete before actually deleting anything.
OCPN v1 (Works on 2000/XP, requires delprof.exe)
OCPN v2 (Works on XP/Vista, requires delprof.exe and Joe Shonk's delete profiles script, here)
I recommend OCPNv3, it works on any version of Windows up to 8/2012.
Make sure to edit the script and set the variables before running it (where you want the log file and the name of the text file that has a list of your systems).
r/ScriptSwap • u/Sn0zzberries • May 05 '13
Load User's ThumbNailPhoto Attribute to Windows Vista/7/2008 User Account Picture
First things first; we need a centralized database to store these images in. This database also needs to be relational to their user account. Lucky for us, Active Directory Domain Services has a specific attribute for storing user images. This attribute is called the thumbnailPhoto attribute. The thumbnailPhoto attribute has been around in ADDS since 2000, but it is just now finally being used throughout applications. Some applications of note are Outlook (>2010), Lync, and Sharepoint. The one caveat of this attribute though, it is a byte field; meaning that you cannot just upload an image and call it good (although there are other utilities that allow for this). Again we are lucky, thanks to the proliferation of PowerShell, converting files to their byte format is very simple. Also, I am keeping the system of jpg > byte > jpg for continuity's sake; although theoretically you could convert the images mid-stream.
Here is the main outline of how this process looks:
Crop image to a square layout
Resize/Compress image to be less than 100 KB
Convert the image to a byte form
Set the user’s thumbnailPhoto attribute to byte form of the image
Have a user GPO that executes a PowerShell script at logon
The PowerShell script retrieves the thumbnailPhoto attribute data and saves the data as an image file
Then the PowerShell script calls an executable where it passes the image in
User’s image is set
Steps 1-3 should be processed by a script. I haven't written one for that though.
Step 4 as well should be handled by a script. The below can give you an idea where to start.
Import-Module ActiveDirectory
$photo = [byte[]](gc \\path\to\edited\photos\user1.jpg -Encoding Byte)
Set-ADUser user1 –Replace @{thumbnailPhoto=$photo}Step 5 you will want to create a new GPO. I setup one computer policy and one user preference to accomplish this.
Computer Configuration => Preferences => Windows Settings => Files => New File
Action: Replace
Source File: \\domain.com\netlogon\domainLogo.bmp
Destination File: C:\ProgramData\Microsoft\User Account Pictures\user.bmp
User Configuration => Policies => Windows Settings => Scripts => Logon => Add
Name: \\domain.com\netlogon\executeUserTile.ps1Step 6 below is the code to accomplish the actual picture creation and application.
# Executes PowerShell in STA (Single Threaded Apartment) Mode and then executes the actual script.
powershell -sta \\domain.com\NETLOGON\userTile.ps1##################################################################################
# PowerShell script wrote by Michael Soule #
#
# C Sharp source code. Credit for the discovery of the DLL hook point goes to http://joco.name/ #
##################################################################################
$source = @"
[DllImport("shell32.dll", EntryPoint = "#262", CharSet = CharSet.Unicode, PreserveSig = false)]
public static extern void SetUserTile(string username, int whatever, string picpath);
[STAThread]
public static void ChangeUserTile(string user, string picPath){
SetUserTile(user, 0, picPath);
}
"@
# Retrieve the Username, Domain, and Temp path respectively.
$username = $env:USERNAME
$domain = $env:USERDOMAIN
$temp = $env:TEMP
# Retrieve the current user’s thumbnailPhoto attribute value.
$photo = ([ADSISEARCHER]"samaccountname=$($username)").findone().properties.thumbnailphoto
# Save the thumbnailPhoto attribute value to an image file in the user’s temporary folder.
$photo | set-content $temp\$domain+$username.jpg -Encoding byte
# Instantiate the C Sharp code.
Add-Type -MemberDefinition $source -Namespace DMD -Name Program
# Call the C Sharp method and pass it the username and image file.
[DMD.Program]::ChangeUserTile("$domain\$username","$temp\$domain+$username.jpg")Resources used:
http://www.myotherpcisacloud.com/post/2011/12/02/More-Pictures-with-AD-thumbnailPhoto.aspx
http://joco.name/2010/12/06/i-discovered-the-new-windows-user-tile-api/
http://blog.cjwdev.co.uk/2010/11/03/the-thumbnailphoto-attribute-explained/
http://www.moe.am/?s=active+directory+user+picture
http://gallery.technet.microsoft.com/scriptcenter/Set-UserTileFromAD-99029716
http://technet.microsoft.com/en-us/library/hh849914.aspx
http://csharp.net-tutorials.com/classes/method-overloading/
http://depsharee.blogspot.com/2011/06/powershell-sta-and-mta.html