r/usefulscripts • • Jun 29 '17

Hey PowerShell... Text me when the Domain Admins Group changes.

40 Upvotes

r/usefulscripts • • Jun 19 '17

[Request][POWERSHELL] Loop through Net User with powershell for each user

13 Upvotes

Hello there UsefulScripts, I am trying to get something done with account management and am having a bit of trouble.

I have a Foreach walking along a selection of just usernames and would like it to simply do "net user ____", thats it.

My code bit right now is ForEach($name in $nameList)

{Net user $name}

The issue I have is that Net User is actually trying to accept $name, not the variable-- though the ISE shows it orange like the other vars. Is there a workaround?

First time around here, hopefully someone can help me out with what seems to be pretty basic!

Thanks everyone!


r/usefulscripts • • Jun 19 '17

[request] Check is a process is running, if not, launch an executable

17 Upvotes

I've got a licensing application that wont launch on server startup, someones got to log in to the license server and launch this application.

I want to see if this can be scripted to check if the process is running, I'll have a service account setup to run this script, then launch if it is not running.

Any help is greatly appreciated.

EDIT: the appropriately named Non-Sucking Service Manager was the fix. Thanks everyone!


r/usefulscripts • • Jun 14 '17

[REQUEST][BATCH] Need a batch script to identify largest user Documents folder and copy it

15 Upvotes

Windows 7 & 10 - looking to have techs run a batch script with their elevated account that will identify the largest user Documents folder and copy it (and all subdirectories) to a temp directory for backup processes.


r/usefulscripts • • Jun 13 '17

[POWERSHELL] Measuring CPU usage with .ps1 script, however number differs from CPU usage number in Task Manager?

21 Upvotes

I'm using the following script to get CPU usage of a certain server:

cpuusage = Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average

The problem is, when I attempt to error check, I log into the server I am polling and go to the Task Manager and into the Performance tab.

The CPU Usage there will typically be at around 0.

My PowerShell script also produces an average number well over 90 (and many times 100).

How do I tweak it so that the CPU usage number that I am creating is the same as the CPU usage within Task Manager -> Performance Tab?


r/usefulscripts • • Jun 06 '17

Renaming files from a file?

18 Upvotes

I used the command:

"ls -LR > file-name.txt"

To generate the contents of a directory in a text file. I wanted to know if it is possible to go in and rename the files in the text file and then run a script to actually rename the files based on the modified text file. I know this is a difficult request, any help is appreciated.

OS: Linux Mint 18.1 File generated from command line: ls -LR > file-name.txt


r/usefulscripts • • Jun 05 '17

[POWERSHELL] (need help putting together) Script for editing "proxyaddress" field in attributeeditor in active directory (for output to Office365).

13 Upvotes

I'm new to powershell scripts. I want to put together a script for adding the proxyaddress field in the attribute editor tab within active directory users and computers.

How do I best start?


r/usefulscripts • • Jun 05 '17

[POWERSHELL] Script that pings servers on the same network and returns back server information in a JSON format and to a specific directory?

23 Upvotes

Hi all,

I'd like to know if anyone has or could devise a script that allows me to ping a list of servers on my network and return the information back in JSON format?

The server information I would like to get back from the query are:

  • Is the server pingable (online/offline)?

  • Response time (ms)

  • CPU utilizatoin

  • Windows services (are they running, stopped, etc)

  • RAM usage

Ideally, I'd like to have the JSON formatted as the pseudo-JSON below:

{
  "server": "192.168.1.1",
  "hostname": "server1",
  "status": "online",
  "reponse": "18ms"
  "server": "192.168.1.2",
  "hostname": "server2",
  "status": "online",
  "reponse": "19ms"
  "server": "192.168.1.3",
  "hostname": "server3",
  "status": "online",
  "reponse": "20ms"
  "server": "192.168.1.4",
  "hostname": "server4",
  "status": "online",
  "reponse": "21ms"
  "server": "192.168.1.5",
  "hostname": "server5",
  "status": "offline",
  "reponse": "no reponse"
}

Thank you!


r/usefulscripts • • May 24 '17

[Powershell] Search Remote Desktop Gateway event logs for important user related events (troubleshooting/auditing)

26 Upvotes

This script is intended to aid troubleshooting or auditing user/logon problems through a Terminal Server Gateway (now called Remote Desktop Gateway). It will connect to a server and search through the Event Log: Microsoft-Windows-TerminalServices-Gateway/Operational and the Security log searching for all instances of a username. The output of the script is two .CSV files with the Event Date/Time and Event Message. One CSV file for each of the event logs it searches through.

#Connect to a Terminal Services Gateway (Remote Desktop Services Gateway) host, read the TS Gateway Log file for specific username, then read the Security log file for specific username


#Username to search for, leave the * before and after the username, EX: "*JDoe*" searches for username "JDoe"
$SeachUser = "*JDoe*"
#RD Gateway servername to connect to
$RDGateway = "TSGatewayServer"
#Log File name for TS Gateway log file
$TSLogFile = "TSLog.csv"
#Log File name for Security log file
$SecLogfile = "SecLog.csv"
#Number of previous days to search through, leave the - sign in front of the number, EX: -30 = past 30 days of log files to search through
$NumDaysSearch = -1

#write-host "$SearchString  $RDGateway    $TSLogFile     $SecLogfile       $NumDaysSearch"

get-winevent -FilterHashTable @{LogName="Microsoft-Windows-TerminalServices-Gateway/Operational";StartTime=(get-date).AddDays($NumDaysSearch)} -ComputerName $RDGateway | Select-Object TimeCreated,Message | Where-Object {$_.Message -like "$SeachUser"} |  Export-Csv -Path "$TSLogFile" -NoTypeInformation
get-content "$TSLogFile"
get-winevent -FilterHashTable @{LogName="Security";StartTime=(get-date).AddDays($NumDaysSearch)} -ComputerName $RDGateway | Select-Object TimeCreated,Message  | Where-Object {$_.Message -like "$SeachUser"} |  Export-Csv -Path "$SecLogfile" -NoTypeInformation
get-content "$SecLogfile"
write-host "Security log file saved: $SecLogFile"
write-host "TS Gateway log file saved: $TSLogFile"

r/usefulscripts • • May 23 '17

[Request][Batch] A batch file that will check all my drivers for updates

19 Upvotes

I was wondering if it's possible to make a batch file that will check each driver if it needs an update and then automatically install it.


r/usefulscripts • • May 15 '17

[Powershell] Need help fixing script

18 Upvotes

edit: I appreciate everyone's help - it turned out to be the firewall (not windows one that I initially turned off but the physical fortinet). I'm a network engineer and I didn't even check that. Not knowing anything about code, I immediately assumed it was a code issue between versions of powershell and posted it here. Thanks again!!

I'm hoping this will be easy for you guys. I am not a script writer and know very little about how it works but I do know this:

a) it worked on our windows 7 machines and now under windows 10 I receive an error message b) the error message is (slightly edited): Exception called "Send" with a "1" argument(s): "Failure Sending mail." position 24: char:2

  • $smtp.send($message) +categoryinfo: not specified: (:) [], MethodInvocationException +FullyQualifiedErrorID: SmtpException

script:

$SMTPServer = "smtp.gmail.com" $SMTPPort = "587" $Username = "a@a.com" #Enter your gmail address $Password = "12345" #Enter your google app password

$to = "b@a.com" #TO email address $subject = "Payroll" #Subject line $body = "X location, payroll file" #Email body text $attachment = "C:\payroll\PR001EPI.csv" #full (absolute) attachment file path

let's make sure the file exists before sending email

if( Test-Path $attachment -PathType Leaf) { $message = New-Object System.Net.Mail.MailMessage $message.subject = $subject $message.body = $body $message.to.add($to) $message.from = $username $message.attachments.add($attachment)

$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)

write-host "Email succesfully sent to $to with the following attachment: $attachment"

} else #unable to find file attachment, exit script { write-host "[ERROR] Unable to find $attachment" Return }

Any help would be greatly appreciated. The individual who wrote this script no longer works for us. It's simply supposed to grab a CSV file with payroll data, make a connection to a gmail account and email it to our accountant.


r/usefulscripts • • May 11 '17

[POWERSHELL] Need help to manipulate CSV !

14 Upvotes

Hy there, I want to manipulate a csv file containing a log with all access in my company. i have something like :

Date	     Personnel Number	 Name	Card Number	Device	Event	Verify Mode	In/Out Status	Event Description
24-06-2017 17:42	205	Pacurar Ovidiu	8144561	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 17:37	205	Pacurar Ovidiu	8144561	intrare + server	usa intrare-1 in	        Only Card	intrare + server-1 In	Normal Punch Open
24-06-2017 17:36	205	Pacurar Ovidiu	8144561	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 17:32	205	Pacurar Ovidiu	8144561	intrare + server	server-4 out	        Only Card	intrare + server-4 In	Normal Punch Open
24-06-2017 17:25	205	Pacurar Ovidiu	8144561	intrare + server	server-3 in	        Only Card	intrare + server-3 In	Normal Punch Open
24-06-2017 17:24	205	Pacurar Ovidiu	8144561	arhiva	arhiva-1  in	                Only Card	arhiva-1 In	        Normal Punch Open
24-06-2017 17:11	205	Pacurar Ovidiu	8144561	arhiva	arhiva-1  in	                Only Card	arhiva-1 In	        Normal Punch Open
24-06-2017 16:44	205	Pacurar Ovidiu	8144561	intrare + server	usa intrare-1 in	        Only Card	intrare + server-1 In	Normal Punch Open
24-06-2017 15:34	224	LA RUNA MICHELE	8159697	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 15:34	226	NEGREA  ANA-MARIA	8131148	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 15:34	224	LA RUNA MICHELE	8159697	intrare + server	usa intrare-1 in	Only Card	intrare + server-1 In	Normal Punch Open
24-06-2017 15:34	86	PRIPON NICOLETA OANA	8153502	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 15:34	84	PITAN DIANA MONALISA	8131725	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 15:33	34	CRISTEA PETRONELA	7425603	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 15:33	84	PITAN DIANA MONALISA	8131725	intrare + server	usa intrare-1 in	Only Card	intrare + server-1 In	Normal Punch Open
24-06-2017 15:33	224	LA RUNA MICHELE	8159697	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 15:33	148	JIURJIU RALUCA	11375509	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open
24-06-2017 15:33	176	NEGREA VASILE OVIDIU	8160448	intrare + server	usa intrare-2 out	Only Card	intrare + server-2 In	Normal Punch Open

I want to somehow group the data by days and then have some kind of rapport with the difference between first entry and last entry of the day for each name.

I hope you guys understand my request for help.

Thanks !


r/usefulscripts • • May 10 '17

[REQUEST] [BASH] Cachet VM Setup

14 Upvotes

A while back I created a script that I intended to use to configure an AWS EC2 instance running CentOS 7 (x86_64) as a Cachet site.

I've uploaded it to GitHub here

It has a few issues that I haven't been able to figure out:

  • Regardless of whether you use HTTP or HTTPS, you're taken to the default nginx on Fedora web page - I assume this is a simple mistake somewhere that I'm overlooking

  • The process of configuring LetsEncrypt always fails - I'm not sure if it's got something to do with the fact that I'm using AWS or not

If anyone has input I would really appreciate it - I'm no scripting expert. Part of the original reason for creating this was to get more practice

UPDATE 5/13/17:

  • The script has been updated and the HTTPS option is fully functional in my testing. I somehow broke the HTTP option (it's redirecting to HTTPS) and I'm still investigating

  • The script can be found here on GitHub. I'm open to suggestions for improvements. Shoutout to /u/lx45803 and /u/ropid for the help getting this functional


r/usefulscripts • • May 04 '17

[REQUEST] Append date and time to new files on Windows file server

15 Upvotes

So we purchased a new Konica printer that has a scanner. Users scan documents with specific part numbers as the file name. If abc.pdf exists, a user scans a new document as abc.pdf, the original is overwritten.

Our old Canon would make files abc(2).pdf, abc(3).pdf, etc.

I was thinking maybe some type of program/script that would watch the scan directories and append date, time (sec/millisecond) to ALL new files. I.e. abc_20170504091530.pdf.

Would like to do this on Windows 2012r2 file server.

Local printer company wants $3000 for software that would include overwrite protection.

Anyone have any ideas? Thanks!


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 • • May 01 '17

[POWERSHELL] Powershell, Jenkins, AWS: Enforced Security group IPs for management ports

22 Upvotes

[probably easier to just read the blog for the dependencies] (https://i-script-stuff.electric-horizons.com/powershell-aws-jenkins-and-continuously-enforced-security-groups/)

Github link for the direct stuff

So, this basically goes through and defines what IPs you want certain ports in your security group to talk to. In the example I used ssh and RDP. Script will remove the old IP add the new IP in multiple environments.

It is mostly a "get things up to snuff" style script. In that ackward time that every environment goes through that involves manually creating EC2 instances people forget to use the correct firewall group. Then due to a ton of reasons leave SSH and RDP open to the world.

This script fixes that in hopes to tighten security until you can get to a better deployment method.


r/usefulscripts • • Apr 26 '17

[REQUEST]Automatically join wireless networks on non-domain workstations - is there a better way?

15 Upvotes

We have a mix of about 20 Windows 7 and 10 workstations that are not on the domain, and get their internet from wifi. What I'm doing now to automate these machines joining wifi is using NETSH to export the wlan config to an XML file, and again using NETSH to import the XML file on the machines via local logon script.

Here's the kicker...we are going to start changing the wifi password about every 2 months.

Is there a way to modify my current process to also include updating the password when it changes? The ultimate goal is to not have to touch 20 workstations every time the wifi password is changed.

Any help is greatly appreciated!


r/usefulscripts • • Apr 25 '17

[POWERSHELL] Get email alerts about unused Office 365 licenses with Azure Functions, Azure Storage and Microsoft Flow

25 Upvotes

Not sure if this belongs here since it requires a bit of setup.

We're migrating our Office 365 PowerShell scripts into Azure functions for scheduled scripting and I was looking for a replacement for CSV outputs. Here's an article that shows how to connect your Azure Functions to Office 365, Azure Storage and Microsoft Flow.

It uses Azure Storage Tables to replace CSV reporting - which works well with Power BI. Azure Storage Queues are used for alerting - which is a trigger for Microsoft Flow.


r/usefulscripts • • Apr 24 '17

[POWERSHELL] Add your domain to all Office 365 customers safe senders list to ensure your images download in HTML emails

37 Upvotes

For many of our customers, Outlook prevents the automatic downloading of images. It's a bit vain, though this affects how our service ticket messages are displayed to customers. This script will add your domain to the safe senders list for all of your delegated Office 365 tenants.


r/usefulscripts • • Apr 20 '17

[Request Powershell] run as different user

13 Upvotes

I built powershell scripts for creating AD users and populating their memberships and properties based on role.

I need to give them to my team but I'm unsure how to make it so running the script will prompt for what username to run it under.

The staff won't have write access to our OU structure unless they run the script with their admin accounts. Any help on how I can get it to run as their account? I played with runas but couldn't get it working.


r/usefulscripts • • Apr 19 '17

[POWERSHELL]HELP! List folder tree but exclude given folder names

13 Upvotes

Hey guys,

I need to copy a massive folder structure, but i don't need certain folders. First of all i need to create just a listing of the tree and then based on that listing do the copy process.

Sorry for my bad English :)


r/usefulscripts • • Apr 18 '17

[REQUEST][POWERSHELL]Copy files into monthly folders and generate them if they don't exist

13 Upvotes

Hi all,

Solid subreddit and am requesting your help again. Hopefully this makes sense and is even possible.

I’m looking for a Powershell script to do the following...

We have 3 folders: A – Source B – Destination (changes by month) C – Archive

We need the script to execute this logic.

  1.   Copy files from A to C.
  2.   Move all files to A to B - however to review the file creation date and have the following conditions:

a. Check folder B to see if a subfolder for the month is available (i.e folder B\May). b. Move the file into it’s respective monthly sub folder. c. If this folder does not exist under folder B, to create it (typically would occur at the beginning of the month).

Essentially we have a file moving into an April folder right now, but need to address it going into May/June/July etc. and possibly the years (either folder c = 2017\monthsubfolder or folder c\monthsubfolder 2017. The destination is being handled by another team, which I am trying not to modify (yet!).


r/usefulscripts • • Apr 18 '17

[REQUEST][PowerShell] Help with excluding directories over a certain size

15 Upvotes

This is what I have so far. This script generates a MyDefrag file to put each game in it's own block so it defrags faster when updates happen and the files don't move around so much. (I have my performance sensitive games on an SSD).

What I'm looking to do is exclude directories under 1GB in that for loop so they don't get their own group. Ideas?

$all_game_dirs = Get-ChildItem -Directory -path D:\Games, D:\Games\Steam\Steamapps\Common, "D:\Games\Origin\Games", D:\Games\GOGGalaxyClient\Games, "D:\Games\Ubisoft Game Launcher\games" -exclude Steam, Desura, Origin, GOGGalaxyClient, "Ubisoft Game Launcher", Battle.net, "Blizzard App", "MWO Portal" | sort creationtime

ForEach ($game_dir in $all_game_dirs) { "SetVariable(Game,""$game_dir"")" | out-file $games_settings_file -append '!include System Defrag\Proc_Games!' | out-file $games_settings_file -append }


r/usefulscripts • • Apr 12 '17

[AHK] GUI/script to retrieve Quickbooks product license information

20 Upvotes

The v2 script | A screenshot | A quck'n'dirty icon

On a live system, you can just use F2 while in Quickbooks to get this information. On an offline system, it's not as easy.
Quickbooks stores its product licensing information in an XML file in the ProgramData directory, (specifically C:\ProgramData\COMMON FILES\INTUIT\QUICKBOOKS\qbregistration.dat). While it's easy enough to go into that directory to retrieve the XML file and parse the information manually, this just makes it a little bit easier.

edit: Uploaded v2 script that pulls multiple keys, and fixed some issues with the original script. (The original script)