r/usefulscripts • • Jul 14 '17

[REQUEST] How to "FIND /V" more than one entry, without having to pipe every entry separately

16 Upvotes

I'm trying to make a one-liner script that displays some basic details of all locally installed printers but does not include virtual printers like CutePDF or Send to OneNote.

So far I have

wmic printer where local=TRUE get name, drivername, systemname, portname, location, description  

I would like to pipe this into a FIND /V to eliminate many common virtual printers from the results, ideally using a text file, but I can't seem to find a way to do this.
I'd really like to avoid having to pipe it separately for each entry, because this would look really ugly and be hard to manage:

wmic printer where local=TRUE get name, drivername, systemname, portname, location, description | find /v "Send To OneNote" | find /v "XPS Document Writer" | find /v "Foxit Reader PDF Printer" | find /v "your mom" | find /v "CutePDF Writer"  

Any ideas on a better way to accomplish this?

(I'm also open to finding a way to do this in Powershell, but I'm still learning it so haven't found a way yet)


r/usefulscripts • • Mar 06 '17

[Request] Merge multiple excel files into one big one

16 Upvotes

I need to script our timesheet system as it is a time drain on the finance department.

So far I am saving all excel attachments from a mailbox to a network storage location. Now what I want to do is merge all these files into one and save in the finance drive.

I have made a few attempts but the formating isn't right. Note, the timesheet is using a formula.


r/usefulscripts • • Jan 12 '17

[Request] export zip files of backups to network drive in Veeam

16 Upvotes

I'm looking for a script that would run down a list of VM backups in Veeam and export zip files of each backup to a network drive using stored credentials. Any help would be appreciated, even if you could just tell me what steps the script would need and I can google how to get it done myself.


r/usefulscripts • • Dec 27 '16

[PowerShell]Show-InputForm • /r/PowerShell x-post

Thumbnail
reddit.com
16 Upvotes

r/usefulscripts • • Dec 15 '16

[REQUEST]Script to RoboCopy user profiles based on AD group

16 Upvotes

I am quite new to PowerShell, but haven't mastered it enough to figure this out.

So, I have a 'Role-Managers' group that has nested groups for the different types of managers that we have. I need to somehow pull all of these usernames from this group, then go out to their PCs to backup their data using RoboCopy or anything else that would copy just the new data. The problem is that the PCs all have generic names, so I will also need to create another group in AD with nothing but the Manager PCs included. I feel like an array of the Role-Manager usernames needs to be created, then cross-referenced with the Manager PCName group, then allow RoboCopy to step in and update as needed. It'd be even better if I could get it to exclude AppData or other folders, but I am not expecting that much.

If anyone has anything like this that is commented to help me through the process, it would be greatly appreciated! I want to learn more of PowerShell, so the more I go through commented scripts, the better off I am for later, but this particular request is far more than I know.


r/usefulscripts • • Nov 29 '16

script to close open files from server (xpost from r/sysadmin)

16 Upvotes

Hello - i was pointed in this direction from r/sysadmin. below is my original post.

hello r/sysadmin - i am hoping you can help me.

I am looking for a way to run a batch script to close all open files from our file server. I have done some googling and found the following fixes:

net session /DELETE

net files [file id] [/close]

this script: from [here] (http://stackoverflow.com/questions/14672479/how-do-i-close-all-open-network-files-in-powershell)

for /f "skip=4 tokens=1" %a in ('net files ^| findstr C:\Apps\') do net files %a /close 

and this powershell script: from [here] (https://social.technet.microsoft.com/Forums/office/en-US/e03753fa-3f93-4677-ae21-3480dce103b7/help-with-powershell-script-to-close-open-files?forum=winserverpowershell)

$results = net file | Select-String -SimpleMatch "D:\Sap_Labels\"
foreach ($result in $results) {
#Get id
$id = $result.Line.Split(" ")[0]

#Close file
net file $id /close

}

However, if you read down the link where i found the second script people start talking about how "the script is closing them, but as they are still open on the destination client the session reopens as the resource is still being used." I can confirm this as I ran the script and checked through Computer Management -> Shared Folders -> Open Files and saw the files were closed, then upon a refresh in the Open Files window, the files would reopen automatically.

Am I correct in thinking that this is because the files are still open on the client side they auto-connect after the cmds/scripts are done running?

I read a bit about the Get-OpenSMBFiles cmdlet and wish that i could use it, but from what i can tell it is only available on Windows Server 2012 and above and our file server is running on Windows Server 2008 R2.

I am crossing my fingers that someone out there has run across this problem and can point me in the right direction.

Edits: because words are hard...


r/usefulscripts • • Oct 18 '16

[REQUEST] Script to copy cells from a column in a systematic order (vertically downwards) and replace them in iterations of a repeated spring in a text document

16 Upvotes

If I have a excel document with list of first names for instance, and I want to copy and paste those into a text file where the place holder value is continually iterated inside snippets of text, how would I do that or can someone assist me in making it.

More verbose example:

the below is just an example Excel: Take values from "A" column in excel, 1 by 1, and paste them into the textfile.txt in order (as if using find and replace and pressing next) and pasting them twice into the text file.

Column A values: matt, john, mary, bill

textfile.txt: is a script in php i wrote, it is very long but the portion in question which i must replace is this

//
// 'replacedvalue(with matt)' => array(
//     'nicename' => 'replacedvalue(with matt)' // optional
//     'price' => 'price here',
//     'description' => 'description here',
//     'not_for_sale' => false,
//     'image' => '' // background override
// ),
// 'replacedvalue(with john)' => array(
//     'nicename' => 'replacedvalue(with john)' // optional
//     'price' => 'price here',
//     'description' => 'description here',
//     'not_for_sale' => false,
//     'image' => '' // background override
// ),
// 'replacedvalue(with mary)' => array(
//     'nicename' => 'replacedvalue(with mary)' // optional
//     'price' => 'price here',
//     'description' => 'description here',
//     'not_for_sale' => false,
//     'image' => '' // background override
// ),
//

r/usefulscripts • • Jul 11 '16

[POWERSHELL] Move Computer Objects based on IP CIDR or based on Sites and Services

16 Upvotes

Two scripts to share.

The first allows you to move computer AD objects by CIDR value and the ou specified. That can be found on pastebin here Or on my github here

The second actually integrates with Sites and services to get the subnets. It can be found on pastebin here or on my github here

If you'd like a full run down on how the configuration works or a break down on some of the useful functions in the script check out my blog here

Thanks!


r/usefulscripts • • Jun 02 '16

[POWERSHELL] Detect if a word is a first name

16 Upvotes

One of the things I don't see done well as companies grow is verifying Ad users/Email Accounts were disabled. This task is often dumped on helpdesk and never completed properly. In order to facilitate fixing this I created a very simple function:

#BehindtheName APi
#Please read api rules: http://www.behindthename.com/api/

function firstname_search($name) {
$local_Name_Storage_File = ".\namestore.txt"
$key = "<read api rules and add key>"
$url = "http://www.behindthename.com/api/lookup.php?name=" + $name + "&key=$key" 
[xml] $content = invoke-webrequest $url | select -expandproperty Content

        if(get-content $local_Name_Storage_File -ea silentlycontinue | select-string "$name") {
        return $true
        } else {
         
        if($content.response.error | select-string "$content.response.error") {
        return $false
        sleep 1
        } else {
        echo "$name" >> $local_Name_Storage_File
        return $true
        sleep 1
        }
    }
}

It ties into the API from www.behindthename.com to verify the username's GivenName/Firstname So using Get-aduser such as:

import-module activedirectory
$lastloginrange = (get-date).adddays(-90)
$user_list = Get-ADUser -properties * -filter {(lastlogondate -le $lastloginrange) -AND (enabled -eq $True) -and (PasswordNeverExpires -eq $false)} | select-object GivenName, Surname, Displayname, Samaccountname, passwordExpired

foreach($user in $user_list) {
$firstName = $user.GivenName
$lastname = $user.Surname

echo "$firstname, $lastname"
    if(firstname_search $firstname) {
    echo "$firstName,$lastname" >> HR.csv
    } else {
    echo "$firstName,$lastname" >> it.csv
    }
}

We are able to generate 2 CSV files. 1 for IT/Helpdesk to review and 1 for HR to review.

You can get your api key by registering with behindthename and going to the api gateway. I urge you to read there usage rules. I also added a local file to search. Set a static path for the variable $local_Name_Storage_File. This lets you add very rare names that are not found on the API and over all decreases your API call count.


r/usefulscripts • • May 17 '16

[REQUEST] Every morning check if the contents of a file are correct. If not, replace the file with a file that contains the correct content.

16 Upvotes

I don't know where to start. I've never done scripting before. I desperately want to learn, however I don't know where to start. I am wondering if this script can be created for me or at least point me in the direction of creating it myself.

I basically want a script that checks a file for certain content in a file. If the file does not have the correct information. It'll replace it all with the correct information. If it has the correct information. It will just do nothing. Or maybe it'll still replace it. Idk what works best.

Here's the deal. Something on this network is causing a Quickbook's .ND file to change itself at least once a week. This breaks the Multi-User mode function of that company file.

Good File //This is QuickBooks configuration File. It exists while users are connected // to a company file. Do not delete this file yourself. QuickBooks may not // operate correctly IF you manually delete this file.

[NetConnect]

ServerIp=192.168.x.x

EngineName=QB_(redacted servername)_26

ServerPort=(redacted)

FilePath=(redacted)

ServerMode=1

FileConnectionGuid=(redacted)

Bad File //This is QuickBooks configuration File. It exists while users are connected // to a company file. Do not delete this file yourself. QuickBooks may not // operate correctly IF you manually delete this file.

[NetConnect]

EngineName=QB_data_engine_26

FilePath=(redacted)

ServerMode=2

FileConnectionGuid=(redacted)

So to sum up. I want the good file to be there every time. If it gets changed, then in the morning or even more routine checks to then replace the bad content with the good content. I am not sure if this will solve the issue. However I have not been able to find exactly where the issue is being caused. So I figured this may be a temporary fix.


r/usefulscripts • • Mar 15 '16

Mella – ownCloud upload in bash via WebDAV using curl

Thumbnail
github.com
16 Upvotes

r/usefulscripts • • Dec 21 '15

[POWERSHELL]Get Access Mask for ACLs - Windows Security-Tab GUI Style

Thumbnail
github.com
16 Upvotes

r/usefulscripts • • Oct 28 '15

[BATCH] Access phone storage over WiFi with WebDAV Server for Android

Thumbnail
gist.github.com
16 Upvotes

r/usefulscripts • • Sep 18 '15

Script Headers

16 Upvotes

What's in yours? Examples, if you want to share.


r/usefulscripts • • Sep 04 '15

Version Control Systems for Scripts

16 Upvotes

What do you use?


r/usefulscripts • • Jul 22 '15

Bash script for vHost creation and SSL Certificate installs

16 Upvotes

Hey guys,

UPDATED: http://pastebin.com/TR7tTS0Z Took the advice from you kind people and made some updates. Only thing I'm still working out is how to get it to do an apache check before breaking. Syntax checks don't work for SSL errors it would seem. Any suggestions?


r/usefulscripts • • Jul 15 '15

looking for a way to AUTO print a log file anytime its created.

16 Upvotes

looking for a way to AUTO print a log file anytime its created.

needs to be running all the time, looking in a directory for a log, when it sees it, needs to print, then delete the log...

any ideas?


r/usefulscripts • • Jul 04 '15

[POWERSHELL]Malicious Microsoft Office Documents: Generate-Macro

Thumbnail
github.com
16 Upvotes

r/usefulscripts • • Jun 03 '15

[Request] [POWERSHELL] Update attributes in AD based on unique attribute (not using SAMAccountName)

16 Upvotes

Hello,

A bit of history to explain why its set up the way it is. Working in higher education student accounts are created from a MIS system which has unique admission numbers for each student. We use this unique number in our AD under the attribute State but as this number is about 16 characters we create the SAMAccountName based on their intake year, surname and firstname to make it easier for the students (although they even forget this! but that's not important).

Tutor groups are also added to the account under Office this is used for dynamic email groups so staff can contact students in their group easy. This can also be used for other attributes but only worried about Office for now.

I am looking for a way so when information is exported from our MIS system into csv it will include the unique admission number and form group. I then pass this csv into a PS script which will

  • Load the records from CSV

  • For each record search for the Admission Number in the attribute State

  • If it finds it then it will update tutor group in the attribute Office

  • Move onto next record.

Is this possible? I know scripts exist similar to this but it requires knowing the SMAccountName. Any help or guides to the right direction will save me a lot of time managing 2000+ users.


r/usefulscripts • • May 19 '15

[Powershell] Bulk user account creation script with some input checking, many automatic features

16 Upvotes

Here it is: http://nonprofittechy.blogspot.com/2015/05/user-account-creation-script.html

Others asked for it in the /r/sysadmin sub, and I have actually been meaning to share it for a couple of years.

Any improvements are welcome, it is a little quick and dirty to get it to meet our needs. Some things I know are not ideal, such as the password saving, but I haven't fixed yet because the solutions I ran into so far have been difficult to adapt to my environment (multiple users need to run the script from different computers, so just locking the credentials won't work, e.g.).

But hopefully this will give people an idea of a real-world user account creation script that does a fair amount of automation.


r/usefulscripts • • Feb 26 '15

.Bat help please

16 Upvotes

Hello. I created a .bat, which will be shown below, to open multiple programs instead of having to click on each one individually. It was quick and easy and everything works, but I am having an issue with 2 of the programs. When the .Bat opens 1 of the programs it automatically creates an Options file on the desktop instead of using the one where the .exe is located. The second problem is similar. When it launches the program it does not pull the files from the directory but instead says they are missing and is going to place them on the desktop. Does anyone know why this would happen? Below you will find the code. With annotations next to the files causing problems.

@echo off

START "Spotify" "C:\Users\Michael\AppData\Roaming\Spotify\spotify.exe"

TIMEOUT 5 > NUL

START "Snip" "C:\Users\Michael\Desktop\Twitch\Overlay\Now PLaying\Snip\Snip.exe"

TIMEOUT 3 > NUL

START "" "C:\Program Files\OBS\OBS.exe"

TIMEOUT 3 > NUL

START "" "C:\Users\Michael\Desktop\Twitch\Spotify ad blocker\Blockify Lite 0.5.exe" This is the one that creates the options file

TIMEOUT 3 > NUL

START "" "C:\Users\Lacey\Desktop\Twitch\SubAlert\subalert.exe" This is the second program that adds directory files to the desktop

TIMEOUT 3 > NUL

Start "Twitch Dashboard" "http://www.twitch.tv/laceinyourspace/dashboard"

Timeout 5 > NUL

START "TWITCH ALERTS" "http://www.twitchalerts.com/dashboard/"

I greatly appreciate everyone help and time on trying to get this resolved.


r/usefulscripts • • Feb 02 '15

[Request] List of user's mailbox limits (Exchange 2010)

16 Upvotes

I'm SUPER new to Powershell. Learning as I go. I'm trying to figure out how to get a list of all user's mail quotas on our Exchange 2010 server. If anyone can help, I'd appreciate it!


r/usefulscripts • • Dec 31 '14

[Bash] Simple file/directory rotation

16 Upvotes

https://github.com/uStackTrace/aTools/blob/master/bash/backupRotate.sh

Notes: I knocked this out for a specific use case, so I didn't do a lot of sanity checking or comments/docs/help/usage/etc.. It's designed to be on a cron and takes three arguments, being:

*-d Working directory,

*-s Source directory. It pulls the newest file (or directory, it doesn't distinguish between the two) from this source directory before trimming down to. . .

*-n Number of files/dirs (again, no distinction) to retain. It deletes all files in the working directory excepting the newest $n files

Example cron:

0 0 * * 0 /root/backupRotate.sh -n 5 -d /backups/weekly/ -s /backups/daily/

Every Sunday this will grab the newest file/dir from /backups/daily and move it into /backups/weekly and trim the resulting /backups/weekly down to 5 files. Seeing it before posting makes me want to make a bunch of changes, but I don't really have the time/will and I may not see any other use for it other than the one for which it was originally written.


r/usefulscripts • • Oct 10 '14

[BATCH] Notify when machine is online

16 Upvotes

I use this to find out when a user has arrived in their office and booted their machine. This is a re-post to comply with the new title guidelines.

@title ipDing
@echo off
    
%======<
This script continuously pings a specified IP or Computer Name
based on an INTERVAL (defined below in seconds).

While the machine is NOT replying, display timestamp of failure
in console window.

If IP Replies, display popup and play notification.
Popup will dismiss after 10 hours.

For sound to work, the program "playwav.exe" must be present
in the working directory.
>======%

setlocal enableextensions enabledelayedexpansion
set interval=600              %=<Interval between pings, in seconds>=%
set /p ipaddr= "Enter Machine Name Or IP: "
:loop
set state=down

for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (      
    if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
    ) %=<Perform single ping; if Received equals 1 then set state to UP>=%

if !state!==up (echo !ipaddr! Online > ipding 
msg /time:36000 %username% < ipding  %=<seconds before popup closes>=%
playwav "C:\Windows\Media\Windows Exclamation.wav"
del /q ipding
exit
)   
echo. > ipding
time /t >> ipding
echo. >> ipding
echo !ipaddr! Offline >> ipding
type ipding
del /q ipding
timeout /t !interval! /nobreak
goto :loop
endlocal

I used code from stackoverflow user "paxdiablo" to parse output from the PING command, referenced here: http://stackoverflow.com/questions/3050898/how-to-check-if-ping-responded-or-not-in-a-batch-file.

You will need to download the program "playwav.exe" (link) for the audio alert (ty saltinecracka)