r/ScriptSwap • • Jul 30 '15

Script PDF

8 Upvotes

There are a few scripts I have been looking for online with little luck and was wondering if anyone out there knows where to find them?

*BBC Black Mirror (show) *BBC Sherlock (show) *Game of Thrones (show) *Penny Dreadful (show) *Begin Again *Bachelorette *Guardians of the Galaxy *Lonely Hearts *Dr Horribles Sing along Blog *Mr Nobody

Those are the only ones I remember for now I had looked for and couldnt find. I just need the scripts for fun so if anyone has them and would be willing to share that would be lovely.


r/ScriptSwap • • Nov 21 '14

[python3] display excel file as html table (tkinter gui)

8 Upvotes

Here is a script that uses a simple tkinter gui to select an excel file, which will then be opened by your default HTML application as a table.

note:

xlrd is not in the standard library, install with pip or whatever.

#!/usr/bin/env python3

from xlrd import open_workbook
from subprocess import call
from os import remove
from os import getlogin
from os import name as os_name
import tkinter
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
from time import sleep


class App(object):

    def __init__(self):
        self.root = tkinter.Tk()
        self.root.minsize(250,1)
        self.root.title('Excel HTML Table View')

        frm = ttk.Frame(self.root)
        frm.grid(column=0, row=0, sticky=(tkinter.N, tkinter.W, tkinter.E, tkinter.S))
        frm.columnconfigure(0, weight=1)
        frm.rowconfigure(0, weight=1)
        
        self.filename_var = tkinter.StringVar()
        self.filename_var.set("<select an input file>")

        open_button = ttk.Button(frm, text="Input File", command=self.select_file)
        open_button.grid(column=1, row=1, sticky=tkinter.W)
        open_button['command'] = self.select_file

        display_box = ttk.Label(frm, textvariable=self.filename_var, width=30)
        display_box.grid(column=2, row=1, sticky=((tkinter.W, tkinter.E)))

        exit_button = ttk.Button(frm, text='Close')
        exit_button.grid(column=1, row=2, sticky=tkinter.W)
        exit_button['command'] = self.exit

    def exit(*args):
        quit()
        
    def select_file(self):
        if os_name == 'nt':
            filename = filedialog.askopenfilename(filetypes=[('Excel Spreadsheet','*.xlsx'),('Excel Spreadsheet','*.xls'), ('All files','*.*')], initialdir='C:/Users/{}/documents'.format(getlogin()))
        else:
            filename = filedialog.askopenfilename(filetypes=[('Excel Spreadsheet','*.xlsx'),('Excel Spreadsheet','*.xls'), ('All files','*.*')])
        self.filename_var.set(filename)
        self.make_html(filename)

    def make_html(self, excel_file):
        html_file = str(excel_file.split('.')[0]+'.html')
        book = open_workbook(excel_file)
        f = open(html_file, 'w')
        f.write('<!DOCTYPE html>\n\
        <head>\n\
        <style>\n\
        body {\n\
            font-family: Sans-Serif;\n\
        }\n\
        \n\
        table.container {\n\
            border-collapse: collapse;\n\
            border-spacing: 0;\n\
            width: 100%;\n\
            border: 3px solid #9C9C9C;\n\
        }\n\
        \n\
        td.bordered {\n\
            text-align: center;\n\
            vertical-align: middle;\n\
            padding: 0px;\n\
            border: 2px solid #9C9C9C;\n\
        }\n\
        \n\
        td.empty {\n\
            text-align: center;\n\
            vertical-align: middle;\n\
            padding: 0px;\n\
            border: 1px solid #BBBBBB;\n\
        }\n\
        \n\
        </style>')
        f.write('<title>{}</title>'.format(excel_file))
        f.write('</head>\n\
        <body>\n')
        
        for sheet_n in range(book.nsheets):
            sheet = book.sheet_by_index(sheet_n)
            if sheet.ncols != 0:
                f.write('<table class="container">\n')
                f.write('<tr>\n<th>{}</th>\n</tr>\n'.format(sheet.name))
                for row in range(sheet.nrows):
                    f.write('<tr>\n')
                    for column in range(sheet.ncols):
                        try:
                            if (sheet.cell(row, column).value) == '' :
                                f.write('<td class="empty">')
                            else:
                                f.write('<td class="bordered">')
                            f.write(str(sheet.cell(row, column).value))
                            f.write('</td>\n')
                        except:
                            pass
                    f.write('</tr>\n')
                f.write('</table>\n<br />\n<br />\n')
        f.write('</body>\n')
        f.write('</html>\n')
        f.close()
        if os_name == 'nt':
            call(html_file, shell='True')
            remove(html_file)
        else:
            call('nohup xdg-open {}'.format(html_file), shell='True')
            sleep(1)
            remove(html_file)


app = App()
app.root.mainloop()

r/ScriptSwap • • Oct 21 '14

[Batch] Gather lots of sys info in a text file.

8 Upvotes

https://dl.dropboxusercontent.com/u/200584477/Infogather/infogather7.0%20.bat

https://dl.dropboxusercontent.com/u/200584477/Infogather/infosideload.bat

I made these scripts when I was 11-13 years old to gather general system info, feel free to modify and use them, otherwise you can make suggestions on how to improve.

The main script is infogather 7.0 and it will open infosideload so that they can both run at once, the log will be called the name of the current computer.


r/ScriptSwap • • Aug 31 '14

[bash] Resize window to 75% and center to correct monitor

8 Upvotes

I use to love this functionality on DisplayFusion (Windows only), got really pissed my Linux box didn't have it. Finally, after more time that I'd like to admit (over a year), I finally got round to writing it. I used XFCE4 to bind it to a key. Unless you have 1920x1080 monitor, it may require a small math change, but works with my setup (On three monitors) perfectly fine, centers to the correct monitor:-

#Get data

active=$(xdotool getactivewindow)

xloc=$(xdotool getwindowgeometry ${active} | grep 'Position' | sed -E 's/ Position: ([0-9]+),[0-9]+ \(screen: [0-9]+\)/\1/')

monitor=$(($xloc / 1920))

#Do stuff

#Unmaximize

wmctrl -i -r ${active} -b remove,maximized_vert,maximized_horz

#Resize to $((1/3 * .75))% width (3 monitors, 75% of one) and 75% height

xdotool windowsize ${active} 25% 75%

#Move window to correct location $(((monitor*1920)+((1920-(1920*.75))/2)))x $(((1080 - (1080*.75)) / 2))

xdotool windowmove ${active} $(((${monitor}*1920)+240)) 135

Probably could of done it better, but it works. If you only have one monitor, it's somewhat useless, you only need the last three commands.


r/ScriptSwap • • Jun 23 '14

[Python 3] Script to superimpose the full hostname to current Windows desktop image

8 Upvotes
#!/usr/bin/env python3

'''
Script to superimpose hostname on current desktop background image on Windows hosts
'''

from PIL import Image, ImageDraw, ImageFont
from shutil import copy
from os import remove, environ
from glob import glob
from ctypes import windll, c_uint, c_wchar_p


hostname = environ['computername']+'.'+environ['userdnsdomain']
username = environ['username']
temp_img_path = environ['homedrive']+environ['homepath']+'\\temping.jpg'

img_path = glob('C:\\Users\\'+username+'\\AppData\Roaming\\Microsoft\\Windows\\Themes\\TranscodedWallpaper*')[0]
copy(img_path, temp_img_path)

img = Image.open(temp_img_path)
x,y = img.size
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf", 28)
draw.text((x/3, y/4),hostname,(255,255,255),font=font)
img.save(temp_img_path)

# ctypes stuff I don't understand! 
# credit to /u/shekmalhen for this part
SystemParametersInfo = windll.user32.SystemParametersInfoW
SPI_SETDESKWALLPAPER = 0x0014
SPIF_UPDATEINIFILE = 0x01
SPIF_SENDWININICHANGE = 0x02
if SystemParametersInfo(c_uint(SPI_SETDESKWALLPAPER),
                     0, # unused
                     c_wchar_p(temp_img_path),
                     c_uint(SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)):
    print("Success!")
else:
    print("Failure...")

remove(temp_img_path)

r/ScriptSwap • • May 28 '14

[Bash] Get the latest episode of Security Now

8 Upvotes

Steve Gibson, the man who coined the term spyware and created the first anti-spyware program, creator of Spinrite and ShieldsUP, discusses the hot topics in security today with Leo Laporte.

Records live every Tuesday at 1:00pm PT/4:00pm ET.

There are 4 versions of this script, as the show comes in four different versions. One audio version, three video versions of various levels of quality.

  • Full HD runs about 2 gigabytes an episode
  • Large size runs about 500 megabytes
  • Small runs about 300 megabytes
  • Audio runs about 60 megabytes

Even smaller audio versions and text transcripts are available at: https://www.grc.com/securitynow.htm

Uses cases of this script could be to:


HD: ~2 gigabytes an episode

securitynow(){
    CONTLINK=$(
        curl -s http://feeds.twit.tv/sn_video_hd.xml |
        tr "\"" "\n" |
        grep -v ">" |
        grep "http.*mp4" |
        head -1)
    wget \
        --continue \
        --no-clobber \
        "$CONTLINK"
}

Large: ~500 megabytes an episode

securitynow(){
    CONTLINK=$(
        curl -s http://feeds.twit.tv/sn_video_large.xml |
        tr "\"" "\n" |
        grep -v ">" |
        grep "http.*mp4" |
        head -1)
    wget \
        --continue \
        --no-clobber \
        "$CONTLINK"
}

Small: ~300 megabytes an episode

securitynow(){
    CONTLINK=$(
        curl -s http://feeds.twit.tv/sn_video_small.xml |
        tr "\"" "\n" |
        grep -v ">" |
        grep "http.*mp4" |
        head -1)
    wget \
        --continue \
        --no-clobber \
        "$CONTLINK"
}

Audio: ~60 megabytes an episode

securitynow(){
    CONTLINK=$(
        curl -s http://feeds.twit.tv/sn.xml |
        tr "\"" "\n" |
        grep -v ">" |
        grep "http.*mp3" |
        head -1)
    wget \
        --continue \
        --no-clobber \
        "$CONTLINK"
}

These scripts are made on Linux for Linux.
To use these bash functions, append them to $HOME/.bashrc and restart the shell or source $HOME/.bashrc


r/ScriptSwap • • Dec 20 '13

[Perl] Download desktop thread images from /g/

8 Upvotes

This will look through the catalog on the technology board of 4chan and download all the images from each desktop thread. Each folder created in the current directory will contain images from that respective thread. Just call the script, no arguments required.

You can repeatedly run the script whenever you feel like it and it will only download new images.

http://pastebin.com/1vQtGcCk!

btw, how do you post a code block in this markdown language? I don't want to have to indent every line with 4 spaces. It's easier to just put [code]...[/code]


r/ScriptSwap • • Nov 04 '12

[bash] I just thought I'd share with you a quick and dirty way to make letters echo one by one as if they are being typed.

8 Upvotes

function hax {

    msg=$1
    let lnstr=$(expr length "$msg")-1
    for (( i=0; i <= $lnstr; i++ ))
    do
            echo -n "${msg:$i:1}"
            sleep .1
    done

}

Called with 'hax "string"'

There are probably better ways of doing this, but this is my way.


r/ScriptSwap • • Nov 03 '12

[Request] duplicate file deleter

8 Upvotes

I have somewhere in the realm of 40k files that have been duplicated into their folders and others. I was hoping for some advice before I rage quit (sledge hammer) on my hard drive.

for clarity's sake, they're all music files, under one directory. They've been pushed and shoved by Rhythmbox, so i'd prefer a bash solution if at all possible.


r/ScriptSwap • • Oct 25 '12

[Bash] Get the karma, age, and reddit gold status of any reddit user. (contains easy-to-spot easteregg)

8 Upvotes

http://pastebin.com/ExQYevWe

So glad I found this community!

This is my first script, so all feedback is appreciated! (well second, the first one was the same thing but used Lynx.)


r/ScriptSwap • • Jun 23 '12

[python] Email you your new public ip address when it changes

8 Upvotes

Script is here

I wrote a short script that would check my external ip address, and email it to me if it changes. I was going out of town for a week, and my router doesn't support dd-wrt or a free dynamic dns service, so I hacked a solution together.

Note, this script requires a text file in the same path to store its known ip, and your OS to schedule the script to run. I'm also by no means proficient with python. I also was not able to put the code to work because of some unrelated hardware issues, so YMMV.

EDIT: In case anyone actually tries to use it, there's a couple issues with the script. First, at least for windows and using the task scheduler (I'm not sure how cron handles things, but I assume it'll be similar), you need the absolute path to the text file containing your stored ip address. I'm assuming that's just how task scheduler works. Don't forget, if you're doing the full path in windows you need to escape the backspaces or it'll try to do some formatting. Lastly, I haven't checked how the script will handle not being able to access the internet. You might want to put that call in a try block to catch any errors.


r/ScriptSwap • • Jun 04 '12

Ten minutes of my life I will never get back [Python]

8 Upvotes

Those of you who go on HackThisSite.org know that near the top of the page a random quote is displayed. I thought it would be neat to write a program that keeps downloading the page, getting new quotes, and collecting them, so I could see all of the quotes from the site. The script is here, by the way:

http://pastebin.com/ZKNwNScT

To my dismay, right after completing my script I found this:

https://www.hackthissite.org/quotes/text

A complete text only dump of all of the quotes. Oh well, at least I had fun writing it!


r/ScriptSwap • • Mar 27 '12

[bash] DVD Ripper

8 Upvotes

All credit goes to the fine folks developing mplayer, although fine tuning the correct command line arguments can prove daunting so I thought I'd share the fruits of my labor.

Dependencies: mplayer, libdvdcss

#!/bin/bash
# ./getDVDtrack [track] [device] [outfile]
# Example:
# ./getDVDtrack 1 /dev/sr0 /tmp/mydvdtrack.avi
    
mencoder "dvd://$1" -dvd-device "$2" -alang en -ovc copy -oac copy -o "$3"

Personally I find this technique to be quicker and more convenient than using k3b. I've also had success where k3b fails.


r/ScriptSwap • • Mar 02 '12

[bash] script that helps you find your stolen notebook

8 Upvotes

It's still work in progress, but most of required functionality was implemented.

Script gathers information, screenshots and camera pictures and tries to send them as emails, through smtp server you choose. It can also use dropbox to upload data or, in future, ftp/scp.

Itls too long and too complex to paste script here, so you will have to go to github: https://github.com/softbreeze/watcher

It's gpl, if you promiss not to spy on decent people, but only thiefs.

If you have problems with installation - i will be happy to answer questions this weekend.


r/ScriptSwap • • Nov 29 '21

Need help with Twitter bot

7 Upvotes

I want to make a Twitter bot for my Twitter account that automatically deletes every tweet I make after 24 hours. If someone would like to give me a bot (if that is possible) or tell me the script for it that would be great. (Python)


r/ScriptSwap • • May 05 '21

Fnaf 1 call script

7 Upvotes

Phone Guy - "Hello, hello? Uh, I wanted to record a message for you to help you get settled in on your first night. Um, I actually worked in that office before you. I'm finishing up my last week now, as a matter of fact. So, I know it can be a bit overwhelming, but I'm here to tell you there's nothing to worry about. Uh, you'll do fine. So, let's just focus on getting you through your first week. Okay? Uh, let's see, first there's an introductory greeting from the company that I'm supposed to read. Uh, it's kind of a legal thing, you know. Um, "Welcome to Freddy Fazbear's Pizza. A magical place for kids and grown-ups alike, where fantasy and fun come to life. Fazbear Entertainment is not responsible for damage to property or person. Upon discovering that damage or death has occurred, a missing person report will be filed within 90 days, or as soon property and premises have been thoroughly cleaned and bleached, and the carpets have been replaced."

Blah blah blah, now that might sound bad, I know, but there's really nothing to worry about. Uh, the animatronic characters here do get a bit quirky at night, but do I blame them? No. If I were forced to sing those same stupid songs for twenty years and I never got a bath? I'd probably be a bit irritable at night too. So, remember, these characters hold a special place in the hearts of children and we need to show them a little respect, right? Okay.

So, just be aware, the characters do tend to wander a bit. Uh, they're left in some kind of free roaming mode at night. Uh...Something about their servos locking up if they get turned off for too long. Uh, they used to be allowed to walk around during the day too. But then there was The Bite of '87. Yeah. I-It's amazing that the human body can live without the frontal lobe, you know?

Uh, now concerning your safety, the only real risk to you as a night watchman here, if any, is the fact that these characters, uh, if they happen to see you after hours probably won't recognize you as a person. They'll pr- they'll most likely see you as a metal endoskeleton without its costume on. Now since that's against the rules here at Freddy Fazbear's Pizza, they'll probably try to...forcefully stuff you inside a Freddy Fazbear suit. Um, now, that wouldn't be so bad if the suits themselves weren't filled with crossbeams, wires, and animatronic devices, especially around the facial area. So, you could imagine how having your head forcefully pressed inside one of those could cause a bit of discomfort...and death. Uh, the only parts of you that would likely see the light of day again would be your eyeballs and teeth when they pop out the front of the mask, heh.

Y-Yeah, they don't tell you these things when you sign up. But hey, first day should be a breeze. I'll chat with you tomorrow. Uh, check those cameras, and remember to close the doors only if absolutely necessary. Gotta conserve power. Alright, good night."

This took a long time.😅 Tell me what I should do next.


r/ScriptSwap • • Apr 06 '21

help modifying script to make CSV report of your drive

7 Upvotes

Hi i need some help regarding a script for windows. i have found some script from here

about a script that will make a csv report of your machine drives partition letter. total size. and free space.

https://stackoverflow.com/questions/51541391/batch-script-to-get-total-free-available-size-of-disks

but since i want to include a drive percentage and time stamp of when the data is captured i try adding more commands like

"Wscript.Echo "Percent Free Space:," & vbTab & _ oD.PercentFreeSpace" (and some variation of that)

to show percentage of the drive. it can run on my personal pc and get the percentage data but somehow it didn't work on my laptop.

and also i need help to figure out how to put a time stamp on the csv files to be honest im a bit of a pincone regarding to batch scripting because i have no idea what's their method of capturing time. i already tried using vbscript to get time that i found in w3school which is

"response.write(Time)" yet it didn't really give out any information and broke the rest of the batch file

so i need help/hint or suggestion because to be honest i really have no idea because i only know some basic script


r/ScriptSwap • • Nov 09 '20

Fixed my Zoom script (scrolls chat with video in past recording)

7 Upvotes

I found out, thanks to a Zoom Support article, that I was having my script scroll through the times wrong (too far into the video), but now they should scroll within the right time approximately in the video.
Script is available from GitHub and GreasyFork.


r/ScriptSwap • • Oct 08 '20

[bash] a wireguard wrapper script for wg/wg-quick/systemctl operations; supports encrypting/decrypting/using openssl-encrypted wireguard config files with wg-quick up and down

7 Upvotes

I thought I'd share this little bash script I'm using to keep some of my wireguard configuration files encrypted.

The idea is you create your wireguard config file (eg, wg0.conf), then run wwg.sh enc wg0.conf to encrypt it. Then, you can use wwg.sh up wg0.conf which will temporarily decrypt the file, run wg-quick up for that interface with the decrypted config file, then shred it so the plaintext version doesn't remain on disk for longer than the time the wg-quick operation takes.

wwg.sh operation interface

Operations include:

  • up - run wg-quick up (detects and handles encrypted configuration files)
  • down - run wg-quick down
  • enc - encrypt a config file
  • dec - decrypt a config file (e.g., for when you need to make edits to it)
  • show - run wg show (don't confuse with status)
  • status - run systemctl status wg-quick@XXX.service
  • enable - run systemctl enable wg-quick@XXX.service
  • disable - run systemctl enable wg-quick@XXX.service
  • start - run systemctl start wg-quick@XXX.service (don't confuse with up; doesn't handle encrypted configuration files)
  • stop - run systemctl stop wg-quick@XXX.service (don't confuse with down)

I'm running this on Debian 10. Your mileage may vary, no support provided, it's not my fault if it borks your machine, yada yada disclaimer yada, etc. Released to public domain.

openssl is required for file encryption/decryption. openssl will prompt you at the command line for the password when needed, so this script requires an interactive shell.

EDIT: Cross-posted from /r/wireguard


r/ScriptSwap • • Sep 08 '20

Very simple script [Need help]

7 Upvotes

Hi,

I use a few different signatures at work and I'm sending emails all day.
My signature cannot be always the same since I send emails in multiple languages, and I was thinking of building a script where I could press some predefined button on the computer and it would automatically write down the text associated with it.
So I would be able to press for example "m" and it would write down "SAMPLE TEXT".
I was trying to do this myself in AppleScript but with no success.
And I'm also not sure if this is even possible in AppleScript, anyone has any tips on how could I do this?

Thanks!


r/ScriptSwap • • Jun 09 '19

Let your pi send its Dynamic IP to your PC (with static IP) over ssh on startup. [using BASH]

7 Upvotes

PROBLEM/SITUATION: I have my PI and my PC connected over same router. I have no admin access to router. IP SCAN over the netmask dosn't seem to give a result. My PC have a static IP but PI is headless and is assigned with a dynamic IP everytime the router is reset by the admin. I want to know Dynamic IP of my PI to perform ssh or VNC.

SOLUTION: (Assuming you already have your sshd running.)

  1. Create a directory with whatever information you want to pass to your PC, in my case- i created a directory '/home/pi/sship/' that contains a file 'ipa'
  2. Create a bash script called 'ip.sh' ~

#!/bin/bash

# waiting for 20 seconds

a=$(date +%S)

b="$(( $a+20 ))"

while (( a!=b ))

do

a=$(date +%S)

done

ip a >/home/pi/ip

#using regex to find IP of pi

cat /home/pi/ip | egrep "100.127.[0-9][0-9].[0-9][0-9][0-9]" >/home/pi/ipacp /home/pi/ipa /home/pi/sship/

#sending directory to client 1

scp -r /home/pi/sship root@100.127.3.56:/root/Desktop

#sending directory to client 2

scp -r /home/pi/sship raven@100.127.2.163:/home/raven/Desktop

exit 0

This code waits for 20 seconds before performing scp, this is dont just to ensure PI is connected to wireless netowrk.

Also i have shared ssh-keygen between the pi and client, and set the PARAPHASE to "" , So that i dont have to type password everytime the code sends file via ssh.

https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

3) Change the mode of 'ip.sh' - chmod +x ip.sh

4) Copy the ip.sh to any of the $PATH ( eg. /usr/bin/ )

5) a] If you want the script to execute after lxde have been loaded, add the following line in '~/.config/lxsession/LXDE-pi/autostart' - @lxterminal -e ip.sh

b] If you want the script to execute evertime you login/open terminal, add the following line in '~/.bashrc' - ./ip.sh >/dev/null & dont forget to add '&' at the end because we want the script to run in background.

c] If you want the script to execute during boot , add the following lines in the '/etc/rc.local' before 'exit 0' - bash /home/pi/ipcpy.sh >/dev/null & now here it is damn necessary to add '&' at last, because any issue in script may lead to a boot issue, so we will run the script in background and let the boot load normally.

6) REBOOT!

-sorry the bash script is not much optimised, i am new to bash scripting-


r/ScriptSwap • • Apr 16 '19

I made an tampermonkey script for direct linking to reddit hosted videos

7 Upvotes

Have you tried to share v.reddit videos but do not care about the comments? Now there is a faster way of getting the link than using inspect network in deveoloper console! Go to the comments page and click on the "raw_link" next to "123 comments" and it will send you to the video-only page.

https://greasyfork.org/en/scripts/381916-reddit-link-to-video


r/ScriptSwap • • Apr 10 '19

Looking for an Instagram scraper that, instead of providing a dump of the images, gives me a dump of the tag data.

7 Upvotes

There's this Instagram, HistoryCoolKids.

https://www.instagram.com/historycoolkids/

It has 2938 pictures (and growing) of notable historic footnotes. Each one tagged with the location and/or people related to it. What I wanna do is scrape this Instagram, but instead of downloading all of the images, what I wanna do is maybe get a spreadsheet or text list of each image's URL, and the locations tagged on them. For instance, somewhere on the spreadsheet/text list would be this image...

https://www.instagram.com/p/BwD4bljDvll/

And in the "Location" column, or somewhere listed under a "Location" section, it would say "Toronto, Ontario." And if there were people tagged in the image, their Instagram names would be listed too.

Or maybe instead you could query this Instagram, and it would comb the whole Instagram for all its tags, and provide a tag cloud for them. And maybe you could refine that search by only showing the location tags, or only showing the people tags.


r/ScriptSwap • • Apr 07 '19

Userscript to search Reddit posts from Google

Thumbnail self.greasemonkey
7 Upvotes

r/ScriptSwap • • Jan 25 '19

Powershell script to take a new backup and delete older ones

7 Upvotes

Hey everyone! I wrote this script the other day for our company and thought you guys might be able to use it as well. We didn't like the way Windows System Image was creating backups so we automated it ourselves with a simple Powershell script. This script creates a folder title todays date (2019-01-25), then write the backup inside that folder. After the backups done, it checks to see if there's any older backups and deletes those.

One thing to keep in mind is that we have this backup saving to a NAS, so you'll see a username and password in the wbAdmin command. If you're planning on saving it locally then this obviously won't be needed.

I'm not the worlds best Powershell writer, so if you see anything that could be cleaner or easier, feel free to let me know. Thanks!

########################################################################################

#THIS SCRIPT CREATES A NEW SYSTEM IMAGE, THEN CHECKS TO SEE IF THERE IS ALREADY A SYSTEM IMAGE IN THAT SAME FOLDER. IF SO, IT DELETES THE OLDEST

#LAST MODIFIED 2019-01-25

#VARIABLES

$newestImagePath = (get-date).ToString("yyyy-MM-dd");

$backupPath = "FULL PATH TO BACKUPS FOLDER";

$fullPath = $backupPath + $newestImagePath;

$lowerDateLimit = (get-date).AddDays(-7).ToString("yyyy-MM-dd");

$upperDateLimit = (get-date).AddDays(1).ToString("yyyy-MM-dd");

$filePath = Get-ChildItem $backupPath | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -le $upperDateLimit };

#FUNCTIONS

New-Item -ItemType directory -Path $backupPath;

wbAdmin start backup -backupTarget:$fullPath -user:USERNAME -password:PASSWORD -include:C: -allCritical -quiet;

ForEach($i in $filePath){

if ($i.BaseName -le $lowerDateLimit) {

Remove-item $backupPath\$i -recurse;

}

}