r/usefulscripts • • Mar 30 '16

Script for taking a screenshot, uploading, and copying the URL to clipboard.

28 Upvotes

I currently use this script, bound to a keybind, to quickly upload and share scrots:

#!/bin/bash
img=$(date '+/tmp/%N.png')
scrot -z "$@" $img >/dev/null 2>&1 || exit
res=$(curl -F c=@$img https://ptpb.pw | awk -F'url:' '{print $2}') && (printf $res | xclip; printf "\a")
notify-send `echo $res`

It works very well, and I highly recommend using it!

I'm wondering if anyone could suggest a way to modify it to copy to the clipboard (secondary selection) rather than primary selection; I keep losing the URL when I accidentally highlight things before pasting.

If you'd like to copy the url to the clipboard instead of x selection, change xclip to xclip -selection clipboard, or xclip -selection c.


r/usefulscripts • • Mar 10 '16

[BATCH] Client Windows Update to WSUS

28 Upvotes

If you are like me you may want a more accurate way to initiate a Windows Update checkin and monitor it's progress with timestamps. This script will do that.

Works / tested on: Windows XP, Vista, 7, 8, 8.1, NT, 2000, 2003, 2008, 2008R2, 2012, 2012R2. I haven't tested on Windows 10 but it should work. Let me know if you test it on Windows 10.

This script must be run as an Administrator to work properly. It will clear your Group Policy cache, perform a Group Policy Update, then Stop & Start the Windows Update/Automatic Updates service (depending on Windows Version), initiate a checkin / resync with your local WSUS, and best feature show you how long it is connected to WSUS and let you know when it has finished.

You will need to edit the first two lines, the UpdateServer should be the IP address of your WSUS. The UpdatePort is the port WSUS is running on (8530 is the current default port, older versions of WSUS used 80).


@ECHO OFF
setlocal
SET UpdateServer=10.0.0.1
SET UpdatePort=8530

ECHO Windows Vista or above: Run command prompt as an administrator
ECHO                         or the service will not be restarted
ECHO Update Server IP Address: %UpdateServer%
ECHO Update Server Port:       %UpdatePort%
nslookup %UpdateServer% | find /i "Name:"

rem ---Find Windows Version
:WinVersion
ver>"%temp%\ver.tmp"
find /i "4.0" "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=WinNT4
find /i "5.0" "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=Win2k
find /i "5.1." "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=WinXP
find /i "5.2." "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=Win2k3
find /i "6.0." "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=Vista2k8
find /i "6.1." "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=W72k8R2
find /i "6.2." "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=W8W2012
find /i "6.3." "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=W8W2012R2
find /i "10.0." "%temp%\ver.tmp">nul
if %ERRORLEVEL% EQU 0 set WinVersion=Win10

if "%WinVersion%" EQU "" set WinVersion=UNKNOWN


REM ---Batch file will connect to the local Windows Update server, then continously check to see when complete
REM UpdateServer is the IP address of the WSUS

:GPUP
ECHO Deleting Group Policy Cache and refreshing from %LOGONSERVER%
DEL /S /F /Q "%ALLUSERSPROFILE%\Application Data\Microsoft\Group Policy\History\*.*" >NUL
gpupdate >NUL

:RestartSVC
ECHO Windows version detected: %WinVersion%
ECHO Restarting Windows Update Service...
TIMEOUT/T 5
IF %WinVersion%==WinNT4 GOTO RestartXP
IF %WinVersion%==Win2k GOTO RestartXP
IF %WinVersion%==WinXP GOTO RestartXP
IF %WinVersion%==Win2k3 GOTO RestartXP

GOTO RestartVista

:RestartXP
net stop "Automatic Updates"
net start "Automatic Updates"
GOTO BeginUpdate

:RestartVista
net stop "Windows Update"
net start "Windows Update"
GOTO BeginUpdateVista

:BeginUpdateVista
wuauclt /detectnow /reportnow
ECHO Downloading Windows Updates, please be patient.
TIMEOUT /T 10 /NOBREAK >NUL
netstat -an | find "%UpdateServer%:%UpdatePort%" >NUL
IF %ERRORLEVEL% ==1 GOTO ERROR
TIMEOUT /T 30 /NOBREAK >NUL
GOTO CHECKVISTA

:BeginUpdate
wuauclt /detectnow
ECHO Downloading Windows Updates, please be patient.
ping -n 10 127.0.0.1 >NUL
netstat -an | find "%UpdateServer%:%UpdatePort%" >NUL
IF %ERRORLEVEL% ==1 GOTO ERROR
ping -n 30 127.0.0.1 >NUL
GOTO CHECK

:CHECKVISTA
TIMEOUT /T 20 /NOBREAK >NUL
TIME /T && (ECHO Still downloading...)
netstat -an | find "%UpdateServer%:%UpdatePort%" >NUL
IF %ERRORLEVEL% ==0 GOTO CHECKVISTA
IF %ERRORLEVEL% ==1 GOTO COMPLETE

:CHECK
ping -n 20 127.0.0.1 >NUL
TIME /T && (ECHO Still downloading...)
netstat -an | find "%UpdateServer%:%UpdatePort%" >NUL
IF %ERRORLEVEL% ==0 GOTO CHECK
IF %ERRORLEVEL% ==1 GOTO COMPLETE

:ERROR
ECHO Error, not connected to update server: %UpdateServer%
ECHO   This computer may not be configured to connect to the local
ECHO   WSUS server, ensure the proper Group Policy is configured.
PAUSE
GOTO END

:COMPLETE
TIME /T && (ECHO --------------- Download Complete ---------------)
ECHO Please check for the Automatic Update tray icon to install updates
PAUSE

:END
endlocal
GOTO:EOF

r/usefulscripts • • Nov 17 '15

[CSV File] FCC Telemarketer and RoboCall Blacklist for Google Contacts (11/16/2015)

Thumbnail
pastebin.com
28 Upvotes

r/usefulscripts • • Aug 03 '15

[POWERSHELL] Set-Wallpaper: Setting wallpaper and scaling mode from Powershell

Thumbnail
github.com
28 Upvotes

r/usefulscripts • • Apr 09 '13

[BATCH] Remove all printers, unused drivers, and unused IP ports

28 Upvotes

Pretty simple really. This checks the version of the OS (XP or 7) and then proceeds to remove ALL printers, their unused drivers (but not the OS's default printer drivers), and unused IP ports. Batch probably isn't the easiest or best way to do this, but it's what I know.

Pastebin link here. Knock yourself out with it.

First submission, so be kind.


r/usefulscripts • • Nov 15 '12

[CMD] Logon script I use to audit servers

28 Upvotes

I use this as a logon script in a Windows server environment to create some very basic documentation on the fly.

I find it useful for flicking through the generated audit files every now and again just to make sure there aren't people added to the administrators group that have been forgotten about...etc.

set outputfile=\\servername\audit\%computername%.txt

date /t > %outputfile%
echo %computername% >> %outputfile%
systeminfo >> %outputfile%
net localgroup administrators >> %outputfile%
net user >> %outputfile%
net share >> %outputfile%

r/usefulscripts • • Aug 05 '21

SharePoint Online External Users- Get all of them quickly now.

27 Upvotes

I have created a script to get all the external users in SharePoint Online sites to assist all the SharePoint administrators. I have used two PowerShell cmdlets to get all the external users in the organization. The cmdlets are "Get-SPOExternalUsers" and "Get-SPOUser".

You can see the script to understand,

  1. How I have iterated the 'Get-SPOExternalUsers' cmdlet to return all external users as you can get only 50 users by default.

  2. To get external users who have logged-in via share links - It will list you sitewise external users report (Used 'Get-SPOUser' cmdlet, as 'Get-SPOExternalUser' will not show this data)

  3. How frequently are external users added to your organization? - You have an option to give the number of days to know the recently added guest users.

Download the script using the link.

https://o365reports.com/2021/08/03/get-all-external-users-in-sharepoint-online-powershell/

Kindly drop your questions in the comment, if any.


r/usefulscripts • • Aug 28 '20

[PowerShell] Restoring (Recovering) PowerShell Scripts from Event Logs

27 Upvotes

Here's a small blog post, and a small PowerShell module at the same time. With just one command you can extract full PowerShell scripts/modules that you or someone else run on the computer. Its goal is to allow you to understand how important is to not store plain text passwords in scripts or any other sensitive data if you don't control your environment (and even then it's risky). I built it to analyze malware that was running on a computer but it can be also used to recover deleted scripts - as long as the logs are big enough of course. It has the ability to scan logs in parallel so you can query multiple machines at the same time. Enjoy

https://evotec.xyz/restoring-recovering-powershell-scripts-from-event-logs/


r/usefulscripts • • Oct 20 '19

[BATCH] Ever wondered how long it takes to execute a script/executable? I have a small script to give you the precise execution time.

27 Upvotes

This is a small script I wrote for myself a few years back to benchmark the execution time for a given batch script (or executable). Script is available here: https://pastebin.com/U9QkSCQL

Usage:

bench.bat "command" [parameters]

Examples:

bench.bat timeout /t 3

(yes it's not exactly 3 seconds, and sometimes it's as low as almost 2 seconds)

Example output:

Waiting for 0 seconds, press a key to continue ...
-----------------------------------------------------------------------
  COMMAND LINE:  timeout /t 3
  ELAPSED TIME:  2.54 sec
-----------------------------------------------------------------------
C:\>

The script works by grabbing the %TIME% environment variable just before launching your command and then grabbing it again right after. This env var has a resolution of 1/100th of a second. Then it calculates the time difference with some bat pseudomath :) Yeah, it's not exactly rocket science, but there are some clever tricks there to convert the human-readable time format to actual integers that can be used for this.

Lemme know if you have any suggestions. I've been using it for a long time now, and it's been quite a while since I came across any bugs/flaws with it, but there might still be some hidden. It might be of interest to coders that have large scripts and want to see if their optimizations are giving any results. I'm also slightly unsure if different system localization settings (got 12h AM/PM clock? too bad) might interfere with the parsing of %TIME%.

EDIT: I realize some of you might wonder why I'm not using timestamps in WMI to get integer "timeticks" to use for the math. WMI calls takes a very long time to execute, and it will be impossible to do a call fast enough to get feasible results.




As a bonus, I also have a variant that allows you to repeatedly loop a script/executable X number of times. It is used to show the average execution time after X number of repetitions, or for example to monitor how much of an impact your script/program has on processor usage while it repeats. Download here: https://pastebin.com/8dDTxWDW

It has the same usage as the script above....

Usage:

benchX.bat "command" [parameters]

Examples:

benchX.bat timeout /t 3

Example output (after 6 repetitions):

Waiting for 0 seconds, press a key to continue ...
-----------------------------------------------------------------------
  COMMAND LINE:  timeout /t 3
  This run: 3.0300 sec        +0.1267 sec avg      +4.36%
  Minimum:  2.5400 sec
  Average:  2.9033 sec         17.4200 sec total       6 times
-----------------------------------------------------------------------

ENTER/Q/R/#:_

After launching your command, it shows a small menu:

  • ENTER = immediately run the command again, the average time will be adjusted accordingly

  • Q = quit

  • R = reset all values, and immediately run the command again

  • = number of additional times you want the command looped

Note: if you enter any other value at the prompt it will be executed as a new command, so take care because unexpected things might happen. I just haven't bothered fixing issues around that "feature" because I am fully capable of keeping my fingers on the correct keys :)


r/usefulscripts • • Jul 15 '19

[Batch] Looking for feedback on my Windows cleaner. Very rough beta so far

Thumbnail
github.com
27 Upvotes

r/usefulscripts • • Oct 24 '18

[PowerShell] PowerShell Module SysInfo

Thumbnail
sconstantinou.com
27 Upvotes

r/usefulscripts • • Nov 15 '17

Simple PC backup script with USMT.

27 Upvotes

Get the user state migration toolkit from the Windows ADK

https://developer.microsoft.com/en-us/windows/hardware/windows-assessment-deployment-kit#winADK

I wrote this for the helpdesk guys a few months ago. Saves them a lot of time.

SET /p user=Enter the username to backup...

net use * /delete /yes
net use u: \\svr01\E$\EasyTransferFiles /user:contoso\admin

IF NOT EXIST u:\"%user%"  GOTO BEGIN
ELSE GOTO END
:BEGIN
xcopy /S/E/F/I/Q U:\USMT\Tools\USMT\amd64 C:\USMT
mkdir U:\%user%
cd C:\USMT

scanstate.exe /genmigxml:U:\%user%\genMig.xml /l:U:\%user%\genMigLog.log

scanstate.exe U:\%user%\ /i:U:\%user%\genMig.xml /l:U:\%user%\migLog.log

net use * /delete /yes
:END
echo end
net use * /delete /yes
pause

r/usefulscripts • • May 03 '17

[BASH] movelink: Move a file from dir "A" to dir "B" and create a link that points from "A" to the new location in "B"

27 Upvotes

Ok. I'm new to github, I'm new to bash scripting, so be easy on me.

I download stuff via torrent to a zfs pool. zfs and torrent don't get along and the files end up very VERY fragmented. The solution I found was, once the file is downloaded, I would organise it and move it to a different dataset, but still, I wanted to keep sharing this file on the original location.

Since the torrent programs sometimes have an utility to move the storage elsewere BUT, you canno't do it selectively (AFAIK), i created this little bash script to move a file from an initial directory to a desired directory and create a reference link on the initial location so the torrenting app could still use the file for seeding.

https://github.com/JonAnder83/scripts/blob/master/movelink

Suggestions/corrections are welcome: I want to learn more :)

Only dependency is rsync.

Happy to share!!!


r/usefulscripts • • Mar 10 '17

Windows, make a backup file. powershell

27 Upvotes

Ok, so I modify a lot of config files and scripts from time to time. so I made a small and simple script, after getting tired of copy-paste-rename. on windows systems.

Ps script: (Save as: C:\scripts\shell_cp_backup.ps1, or modify the registry file): http://pastebin.com/1TGwPzNU

Registry explorer shell integration (Save as "something.reg" and merge to registry): http://pastebin.com/P6T021ST

With this, you can right-click at a file, and select "Make a backupfile" which will basically just copy the file you right-clicked and save it as "filename".YEARMonthDay.bak

Hope you like it. :)


r/usefulscripts • • Dec 14 '16

[BATCH] Display all color combinations for back/foreground in command window, useful for determining preferred color scheme for application windows

Thumbnail
pastebin.com
27 Upvotes

r/usefulscripts • • Sep 20 '16

[POWERSHELL] Export Computers from AD OU to separate Excel Worksheet

27 Upvotes

This is a script that loops through an OU of your choosing and outputs all computers in their respective sub-OUs to separate Excel Worksheets.

Specify the Base OU's distinguished name in the $OU_Base variable. Hope this helps someone out there. Some code stolen from here

#Set your OU distinguished name variable
$OU_Base = "OU=YOUR,OU=OUPATH,DC=HERE" 


#Function to create Excel Worksheets
Function Function_CreateWorksheets {
    [CmdletBinding()]
    param (
        [parameter(Mandatory=$true,ValueFromPipeline=$true)][object] $Excel,
        [string[]] $WorkSheets
    )
    ForEach ($Worksheet in $Worksheets) {
        $Script:Excel_Count_Worksheet++
        If ($Excel_Count_Worksheet -gt $Excel.Worksheets.Count) {$Excel.Worksheets.Add([System.Reflection.Missing]::Value, $Excel.Worksheets.Item($Script:Excel.Worksheets.Count)) |Out-Null}
        $Excel.Worksheets.Item($Excel_Count_Worksheet).Name = $Worksheet
    }
    While ($Excel.Worksheets.Count -gt $Script:Excel_Count_Worksheet) {
        $Excel.Worksheets.Item($Excel.Worksheets.Count).Delete()
    }
}

Get-Variable Excel_* |Remove-Variable -Force

#Create Excel Com Object
$Excel = New-Object -com Excel.Application

# Make the Excel Application Visible
$Excel.visible = $True

# Create a WorkBook inside the Excel application that we can start manipulating.
$Excel_Workbook = $Excel.Workbooks.Add()
$Action_CreateWorksheet = 

#The OUs - friendly and distinguished name
$OUS = Get-ADOrganizationalUnit -SearchBase "$OU_Base" -filter * -SearchScope OneLevel | select -ExpandProperty name
$OU_with_dist_Name = Get-ADOrganizationalUnit -SearchBase "$OU_Base" -filter * -SearchScope OneLevel | select -ExpandProperty DistinguishedName


#Loop through the OUs and export each OU to Excel Sheet
$counter = 0
$Final_OU_List = @(0..100) #increase this number if you have more that 100 sub OUs
foreach ($Dist in $OU_with_dist_Name){
    $Final_OU_List[$counter] = $Dist
    $counter = $counter + 1
}


$counter = 0
foreach ($OU in $OUS){
Function_CreateWorksheets -Worksheets $OU -Excel $Excel
$PCs = Get-ADComputer -Filter * -Properties * -SearchBase $Final_OU_List[$counter] -SearchScope Subtree | select -ExpandProperty name

$ExcelWorkSheet = $Excel.WorkSheets.item("$OU")
$ExcelWorkSheet.activate()

$lastrow = $ExcelWorkSheet.usedrange.rows.count + 1
    foreach ($PC in $PCS){
$ExcelWorkSheet.cells.item($lastrow++,1) = "$PC"
}
    $counter = $counter + 1

$PCS = $NULL
}

r/usefulscripts • • Apr 04 '16

[CSV File] FCC Telemarketer and RoboCall Blacklist for Google Contacts 04/04/2016

27 Upvotes

Full Primary List (184 contacts) - https://pastebin.com/QKrQuScS

Deltas 20160404 (9 new contacts) - https://pastebin.com/F7cgsur0

Deltas 20160328 (8 new contacts) - https://pastebin.com/YzkcSiyv

Deltas 20160321 (5 new contacts) - https://pastebin.com/yRS26G5c

Deltas 20160314 (7 new contacts) - https://pastebin.com/u2ueD6Cv


!WARNING!

Some Android apps will have issues!

Here are the ones that are known:

  • Telegram

  • WhatsApp

  • Hangouts (from /u/bugalou, but need another to confirm)

If an app checks the status of ALL contacts (not just app specific), you'll be in for a bad time.


  1. Copy & paste the pastebin content to notepad

  2. Save As .csv

  3. Go to www.google.com/contacts

  4. Import (might complain, and switch you to the "old" interface)

  5. Select the .csv you made, and upload!

If you don't see them immediately, refresh the page, don't try to upload again!


Options to Block:

  1. Use Google Voice to redirect the Spammers group directly to voicemail

  2. Use Root Call Blocker to reject calls from the Spammers group (Thanks to /u/Toribor)

  3. Like #1, but instead of voicemail, redirect them to Lenny! (Thanks to /u/Enxer)

  1. ....Suggestions?


NOTICE

I'm going to only make a new thread once a month, so make sure to watch my Pastebin account for your deltas every week (the new numbers)!


The list has grown to 36,647 numbers, in 184 contacts (200 numbers per contact). That's an additional 5,102 numbers over the last month!

Don't stop reporting these numbers! You can find out more, and file a complaint with the FCC here: https://consumercomplaints.fcc.gov/hc/en-us/articles/202916660

For those who want the raw data from the FCC, you can get it from here: https://consumercomplaints.fcc.gov/hc/en-us/articles/205239443

You can also watch my Pastebin account for updates: https://pastebin.com/u/Harshmage/

Keep the comments coming!


Edit 4/18/2016: Added Lenny to the Options to Block section!

Edit 5/24/2016: The FCC is changing up the game, and now offering an API into these numbers! Of course, they added an extra line to the CSV, so it broke my PS script a bit, but now with the new API, I should be able to rework this fairly quickly. Look for a new post next week!


r/usefulscripts • • Dec 04 '15

[POWERSHELL] Conjoined Twins - IFTTT-style application actions using auditing and scheduled tasks under Windows

Thumbnail
gist.github.com
27 Upvotes

r/usefulscripts • • Oct 05 '15

[BATCH] One-liner to get Windows date into ISO format (yyyy-mm-dd)

27 Upvotes

for /f "delims=/ tokens=1,2,3" %%G in ('echo %date:~4%') do set current_date=%%I%%G%%H


r/usefulscripts • • Jun 18 '15

[POWERSHELL] GUI Script that creates an arbitrary number of AD computer objects in a specified container and makes them joinable by members of a specified group.

Thumbnail
pastebin.com
27 Upvotes

r/usefulscripts • • Apr 29 '15

[Powershell]USUS - Gets the latest installers from the source, then packages them up in various ways.

Thumbnail
github.com
27 Upvotes

r/usefulscripts • • Apr 28 '15

Hactar – incremental daily backup using rsync

Thumbnail
blog.no-panic.at
27 Upvotes

r/usefulscripts • • Jan 03 '14

[BATCH] Add event logging to your scripts.

27 Upvotes

sheet airport crown doll cagey deliver ask cautious marry school

This post was mass deleted and anonymized with Redact


r/usefulscripts • • Nov 06 '13

[VBSCRIPT] Detecting CryptoLocker Infection

Thumbnail
pastebin.com
27 Upvotes