r/usefulscripts • • Sep 16 '18

[PowerShell] PSWinReporting - monitoring Active Directory Events and sending to Email, Excel, CSV, MS Teams, Slack and SQL

44 Upvotes

For those who don't know this module it's purpose is simple - monitoring Active Directory for events such as creating new users, adding users to groups, deleting users and so on. If you've ever wondered who added this guy to Domain Admins this tool can tell you. By default (the old version) it was only able to send it to Email with nice reports. New version adds:

  • Support for Event Forwarding – monitoring one event log instead of scanning all domain controllers

  • Support for Microsoft Teams – Sending events as they happen to Microsoft Teams (only supported when forwarders are in use)

  • Support for Slack – Sending events as they happen to Slack (only supported when forwarders are in use)

  • Support for Microsoft SQL – Sending events directly to SQL (some people prefer it that way) - including create table, alter table and insert rows with table mapping in place

  • Support for backing up old archived logs (moves logs from Domain Controllers into chosen place)

  • Support for re-scanning logs from files – a way to recheck your logs for missing information The last one is still in progress but should be usable soon.

Blog about new release (how to and so on): https://evotec.xyz/pswinreporting-forwarders-microsoft-teams-slack-microsoft-sql-and-more/

Module page: https://evotec.xyz/hub/scripts/pswinreporting-powershell-module/

Sources are on GitHub, and installable from PowershellGallery (preferred way). It utilizes following modules for different functionalities (available on github/powershellgallery)


r/usefulscripts • • Mar 08 '18

[POWERSHELL] Use LetsEncrypt for Plex and RDP

44 Upvotes

After generating my LE certificate, I decided I wanted to set it for Plex and RDP. Then I didn't want to have to mess around with it again, so I just run this script when my LE cert expires. It can probably be optimized to sort by latest expiration date at some point, but it's a start :)

$domain = "your.le.cert.domain"
$plexcert = "C:\Program Files (x86)\Plex\Plex Media Server\cert.pfx"
$pwd = ConvertTo-SecureString -String "yourplexcertpassword" -Force -AsPlainText


$cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object {$_.Subject -match "CN=$domain"}
Export-PfxCertificate -Cert $cert -Password $pwd -FilePath $plexcert
$tp = (ls Cert:\LocalMachine\my | WHERE {$_.Subject -match $domain } | Select -First 1).Thumbprint
wmic /namespace:\\root\CIMV2\TerminalServices PATH Win32_TSGeneralSetting Set SSLCertificateSHA1Hash="$tp"

r/usefulscripts • • Mar 23 '25

Add the Unix touch command to [Powershell]

Thumbnail
medium.com
43 Upvotes

TL;DR, paste the following into your Powershell $PROFILE:

function touch {
    param([string]$file)

    if (Test-Path $file) {
        # Update the timestamp if the file exists
        Set-ItemProperty -Path $file -Name LastWriteTime -Value (Get-Date)
    }
    else {
        # Create a new file if it doesn't exist
        New-Item -Path $file -ItemType File
    }
}

Reload, and voilà, you can use touch like normal.


r/usefulscripts • • Jun 28 '19

[PowerShell] All your HTML Tables are belong to us

43 Upvotes

What I wanted to show you today is a new version of PSWriteHTML and Dashimo. I've spent time working on something I always wanted to have in my reports but always thought it's just too hard to achieve. Hopefully, this makes it easy for you.

You can now, among other new features control headers in a way it was not possible before. Best of all it's ultra easy (according to me ;p).

$ProcessesAll = Get-Process | Select-Object -First 30
Dashboard -Name 'My title' -FilePath $PSScriptRoot\Example03.html -Show {
    Section -Name 'Show basic way to merge column names, giving title on top of it' {
        Panel {
            Table -DataTable $ProcessesAll -HideFooter -DisableResponsiveTable {
                TableHeader -Names 'Name', 'ID' -Title 'Process Information' -BackGroundColor Green
                TableHeader -Names 'PagedMemorySize', 'PrivateMemorySize', 'VirtualMemorySize' -Title 'Memory' -Color White -BackGroundColor Gainsboro
                TableHeader -Names 'Name', 'ID' -Color Red
            }
        }
    }
}

Overview of new features and know/how: https://evotec.xyz/all-your-html-tables-are-belong-to-us/

GitHub sources: https://github.com/EvotecIT/PSWriteHTML


r/usefulscripts • • Oct 15 '17

Copy all OneDrive files to another user via PowerShell

43 Upvotes

Here's a script that will copy a user's entire OneDrive folder into a subfolder in another user's OneDrive via PowerShell.

Hopefully it'll help speed up the off-boarding process


r/usefulscripts • • Apr 22 '15

[BATCH] TempFileCleanup

43 Upvotes

This script runs at startup (or when manually run) and cleans out various areas of Windows that accumulate temporary files. Make sure to read the comments to see exactly what it removes.


Download

LATEST (v3.7.1 // 2017-12-18)

  • Changelog on the github link above


Writes a log file to C:\Logs\<computername>_TempFileCleanup.log (this is configurable) of run time, what was deleted, and what user ran the script.


r/usefulscripts • • Aug 29 '21

[PowerShell] Easy way to connect to FTPS and SFTP

42 Upvotes

Hello,

I've been a bit absent from Reddit the last few months, but that doesn't mean I've been on holiday. In the last few months I've created a couple of new PowerShell modules and today I would like to present you a PowerShell module called Transferetto.

The module allows to easily connect to FTP/FTPS/SFTP servers and transfer files both ways including the ability to use FXP (not tested tho).

I've written a blog post with examples: https://evotec.xyz/easy-way-to-connect-to-ftps-and-sftp-using-powershell/

Sources as always on GitHub: https://github.com/EvotecIT/Transferetto

# Anonymous login
$Client = Connect-FTP -Server 'speedtest.tele2.net' -Verbose
$List = Get-FTPList -Client $Client
$List | Format-Table
Disconnect-FTP -Client $Client

Or

$Client = Connect-FTP -Server '192.168.241.187' -Verbose -Username 'test' -Password 'BiPassword90A' -EncryptionMode Explicit -ValidateAnyCertificate
# List files
Test-FTPFile -Client $Client -RemotePath '/Temporary'

More examples on blog/Github. Enjoy


r/usefulscripts • • Jul 11 '19

[PowerShell] Getting Bitlocker and LAPS summary report with PowerShell

42 Upvotes

On Facebook PowerShell group, one of the guys was looking for a way to find encrypted computers. I thought it was a cool idea to actually have a bit of summary report that tells you if a computer has LAPS enabled, is encrypted, when was the last key exported to AD, when laps password changed.

https://evotec.xyz/getting-bitlocker-and-laps-summary-report-with-powershell/

It's one command giving you a full overview of all computers. As an added bonus it gives you Windows 10 version it has installed. I often enable LAPS, have a process for Bitlocker but never actually verify this. I'll use this one to review my projects.


r/usefulscripts • • May 01 '18

[BASH] Script to send push notifications to mobile devices from the command line using Pushover

42 Upvotes

I'm in the midst of a RAID array rebuild after an imminent device failure that went unnoticed because nobody configured postfix on the server so smartd could send email notifications. Instead of going through the trouble of setting up an SMTP server I decided to try to integrate push notifications into smartd. I realized how useful it would be to have one easy command to send a push notification to a mobile device so I turned it into its own script. This is the result.

The script takes a user and application key from Pushover.net and sends a request to the API with a text notification and optionally a title. The script will use user and app keys in env variables (PU_USER and PU_TOKEN) if they're not passed to the script, for easy repeat use on a machine using the same Pushover app. The script will take a single line of stdin in lieu of the message field. If no title is specified, it defaults to user@hostname as the message title.

Example uses:

Download a large file and get a notification with the HTTP status code when it completes: curl -w "%{http_code}" -O http://ipv4.download.thinkbroadband.com/1GB.zip | pushover

Wipe a large disk with dd and get a ping when it's done: dd if=/dev/zero of=/dev/sdb bs=1M && pushover "Format of sdb complete"

And the reason I made it, get SMART failure notifications from smartd. Add the following lines to the script smartd uses for notifications (/usr/libexec/smartmontools/smartdnotify on RHEL, /usr/share/smartmontools/smartd-runner on Debian) to get SMART errors sent immediately to your mobile device (or an entire team, in the case of Pushover group IDs) at the first sign of disk failure for quick action.

# Send push notification using pushover
APP_TOKEN=""
USER_TOKEN=""

pushover -u $USER_TOKEN -k $APP_TOKEN -t "SMART error detected on $HOSTNAME" "$SMARTD_MESSAGE"

https://github.com/Fantastitech/pushover-messenger/blob/master/pushover

#!/bin/bash

# Pushover push notification script
# This script will send messages to your mobile devices
# using the Pushover service at Pushover.net.
# To use it, create an account on Pushover.net
# and get a user and app key. You can pass them
# directly or set them as env variables. Then run
# the script with a message in quotes to send a
# push notification to your devices from the command line

while getopts "u:k:t::h" OPTION
do
        case $OPTION in
                u)
                        PU_USER=$OPTARG
                        ;;
                k)
                        PU_TOKEN=$OPTARG
                        ;;
                t)
                        PU_TITLE=$OPTARG
                        ;;
                h)
                        echo "Pushover messenger"
                        echo -e "\tThis script sends push notifications to mobile devices using the Pushover service"
                        echo -e "\tYou must create an account at https://Pushover.net then create an application for your messages."
                        echo -e "\tPushover will accept a string, a URL, or a single line of input from stdin.\n"
                        echo -e "Usage: pushover [OPTIONS] message \n"
                        echo -e "\tOptions:"
                        echo -e '\t\t-u,               Pushover user key (Can be exported as $PU_USER).'
                        echo -e '\t\t-k,               Pushover application token/key (Can be exported as PU_TOKEN).'
                        echo -e '\t\t-t,               Message title. If left blank, user@hostname will be used.'
                        exit
                        ;;
        esac
done
shift "$((OPTIND - 1))"

if ! [[ -t 0 ]]; then
        read  input
        PU_MESSAGE=$input
elif [[ -n $1 ]]; then
        PU_MESSAGE=$1
fi

if [[ -z $PU_TOKEN ]]; then
        echo 'App key missing. Pass your app token/key with -k or export it as $PU_USER.'
        echo 'Use -h for a full list of options.'
elif [[ -z $PU_USER ]]; then
        echo 'User key missing. Pass your user key with -u or export it as $PU_TOKEN.'
        echo 'Use -h for a full list of options.'
elif [[ -z $PU_MESSAGE ]]; then
        echo 'Message can not be empty. Enter a message or run pushover with stdin.'
        echo 'Use -h for a full list of options.'
else
        if [[ -z $PU_TITLE ]]; then
                PU_TITLE="`whoami`@${HOSTNAME}"
        fi
        curl -s \
        --form-string "token=$PU_TOKEN" \
        --form-string "user=$PU_USER" \
        --form-string "title=$PU_TITLE" \
        --form-string "message=$PU_MESSAGE" \
        -o /dev/null \
        https://api.pushover.net/1/messages.json
fi

r/usefulscripts • • Jan 22 '17

[Python] script that checks server list if on/offline, generates nice html report.

42 Upvotes

https://github.com/circa10a/Device-Monitor-Dashboard

Hey guys, few months back I posted a python script that pinged a list of servers from a text file and gave a color coded excel report if they we're on/offline.

I've been learning web stuff and revamped it. Now it generates a nice html report with tables/charts. Check it out! Could be used for checking up on a network lab or IOT devices in your home.

Here are some examples hosted on github pages:
https://circa10a.github.io/monitor/
https://circa10a.github.io/monitor/fail.html

Edit: any ideas for improvements?
Edit: Now has an easy install script!
Edit: Now supports docker!


r/usefulscripts • • Jan 24 '22

[PowerShell] Difference between GetTempFileName() and GetRandomFileName() that got my ass kicked

41 Upvotes

Here's a short story between [System.IO.Path]::GetRandomFileName() and [System.IO.Path]::GetTempPath() and when to use it, and when not to use it - unless you're me - then you use it all the time!

Blog post: https://evotec.xyz/difference-between-gettempfilename-and-getrandomfilename-that-got-my-ass-kicked/

Moral of the story [System.IO.Path]::GetTempPath() doesn't just provide a path to a temporary file. It actually creates it!


r/usefulscripts • • Sep 12 '21

[PowerShell] Encrypting and decrypting PGP

41 Upvotes

Today I would like to introduce you to my small PowerShell module that helps to encrypt/to decrypt files using PGP.

To find more about it: https://evotec.xyz/encrypting-and-decrypting-pgp-using-powershell/

To get started:

Install-Module -Name PSPGP -AllowClobber -Force

Creating public/private keys

New-PGPKey -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -FilePathPrivate $PSScriptRoot\Keys\PrivatePGP.asc -UserName 'przemyslaw.klys' -Password 'ZielonaMila9!'

Encrypting:

Protect-PGP -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -FolderPath $PSScriptRoot\Test -OutputFolderPath $PSScriptRoot\Encoded

Source codes: https://github.com/EvotecIT/PSPGP


r/usefulscripts • • Oct 05 '20

[TERRAFORM] Automatic Deployment of Pihole in AWS

Thumbnail
github.com
41 Upvotes

r/usefulscripts • • Jun 16 '20

[ISO] A comprehensive HP bloatware removal script

41 Upvotes

I've got one for Dell, and so of course the business pivots to HP, so now I need one for them.


r/usefulscripts • • Jul 21 '19

[PowerShell] Instant Replication between Active Directory sites with PowerShell - Evotec

41 Upvotes

This article https://evotec.xyz/active-directory-instant-replication-between-sites-with-powershell/ show how to enable Instant Replication between AD Sites with PowerShell. It contains useful bits of knowledge on how to make it work in a couple of minutes without manual work involved.


r/usefulscripts • • Nov 29 '21

[PowerShell] Enhanced HTML reporting with Fuzzy Search and PSWriteHTML

40 Upvotes

In the last few days, I've worked on updating PSWriteHTML. One of the few cool features that I've added is fuzzy search.

This means that with just one little change to code your HTML-based tables can get fuzzy search in them.

get-aduser -Filter * | Out-HtmlView -FuzzySearchSmartToggle

Fuzzy search makes sure that typing 'przemlaw' or 'maboy' will potentially get you MadBoy or Przemyslaw anyways.

Get-Process | Out-htmlview -First 5 -FuzzySearchSmartToggle

A short blog post showing a small comparison between ConvertTo-HTML, Out-HTMLView and New-HTMLTable and how to use Fuzzy Search in them: https://evotec.xyz/solving-typo-problems-with-fuzzy-search-in-pswritehtml/

GitHub Sources: https://github.com/EvotecIT/PSWriteHTML


r/usefulscripts • • Apr 09 '21

[Batch] Remove all Outlook profiles from all users on this computer

40 Upvotes

Pastebin here: https://pastebin.com/b1Qkvjpf

Note that this does not remove any ost or pst files; you'll have to work that out yourself. I chose not to address that in this script to avoid potentially erasing anyone's important archives, but feel free to modify it for your own use!

Also note that this only works for Office 2016 and 2019


r/usefulscripts • • Jan 07 '20

[PowerShell] Printer cleanup

40 Upvotes

Was looking for a cleanup script to exclude things the way I needed them excluded, and couldn't find one. Necessary as we move from manual installs of printers everywhere to mass PaperCut adoption with a handful of GPO-deployed printers, it has deleted over 4000 printers so far. It does 3 slightly different methods of removing them to provide examples.

Printer names under KeepNames just need to match the name output by the Get-Printer command with how the script is done below.

$KeepNames = @('\\legacy-svr\check-printer', 'network-printer-1', 'special-secret-printer', 'waffle-printer')

$Printers = Get-Printer | Select -Property Name,Type,PortName

ForEach ($Printer in $Printers) {
  Write-Host $Printer.Name
  If ($Printer.Name.ToLower().StartsWith("\\new-print-server")) {
    Write-Host "Keep this one because it's on the new print server"
  } ElseIf ($Printer.PortName.StartsWith("USB")) {
    Write-Host "Keep this one because it's a local USB printer"
  } ElseIf ($KeepNames.Contains($Printer.Name)) {
    Write-Host "Keep this one because it's on the list of do-not-touch printers"
  } Else {
    Remove-Printer -Name $Printer.Name
    Write-Host "REMOVED"
  }
}

r/usefulscripts • • Oct 08 '18

[PowerShell] PSWinDocumentation - Audit your Active Directory Passwords has been added

40 Upvotes

Blog: https://evotec.xyz/pswindocumentation-audit-active-directory-passwords/

I have worked last few days on adding ability to provide Password Quality Report for AD. Now that it's kind of ready ... you can enjoy it as well. If you don't know this module at all read: https://evotec.xyz/hub/scripts/pswindocumentation-powershell-module/ But in short this module allows to create documentation in automated (always up to date) way for AD, AWS, Office 365 (to small degree) and deliver it straight to Microsoft Word and Excel and SQL without those even being on machine. Here's couple of new screens from it.

In this version I basically added support for DSInternals (https://github.com/MichaelGrafnetter/DSInternals) module which provides ability to compare plain text passwords and Have I Been Pwned Database against your Active Directory. I just kind of wrap it around to deliver nicely formatted documents for your management ;-)

I have also expanded couple of other Active Directory types. I really need to update github/main webpage documentation to cover everything... for now.. you can work with what's given in the blogs... or you can help writing docs for others to use. Please notice running this against huge password database will take hours or days for some domains... and I've not spent a lot of time verifying everything. So please REPORT BUGS on GITHUB. Feel free to do PR's as well. Feature requests are also welcome!


r/usefulscripts • • Sep 20 '17

Powershell Active Directory: Show treeview of User or Group memberof hierarchy

Thumbnail
vcloud-lab.com
40 Upvotes

r/usefulscripts • • Jun 29 '17

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

40 Upvotes

r/usefulscripts • • Aug 24 '15

[BATCH] Inject your self signed certificate into Firefox certificate store

40 Upvotes

So, we had a need to inject our self signed root CA into everyone's browser. For Chrome and IE, they both reference Window's cert store, easy GPO, done. Firefox doesn't like enterprise, so they keep a per-user cert store in appdata. I found a couple of scripts to do this when set as logon scripts, but I wanted something I could just package and deploy once.

dependencies

you'll need certutil and it's dlls from nss tools. I got mine here

You'll also need a cert8.db with your cert already included, and your cert.

Put them all in the same directory as this script, and it should probably work, injecting the cert into trusted for all users on that machine, including new ones. It's pretty janky in some spots, but it works.

@echo off
::Written by ITSX. Overwrites default cert8.db and Injects REDACTED Root CA into default and user's profiles' certificate store.





::User defined variables


set _varCertCommonName="REDACTED"
set _varCertName=exportedCertificateFromWindows.cer
set _varWorkingDir=%windir%\FFRoot








set _appDataSubDir=%APPDATA%
set _profileDir=%USERPROFILE%

call set _appDataSubDir=%%_appDataSubDir:%userprofile%=%%
call set _profileDir=%%_profileDir:\%username%=%%

echo %_profileDir%
echo %_appDataSubDir%

IF NOT %_profileDir%\%username%%_appDataSubDir%==%appdata% (echo Uh oh. it's broke.&& pause && goto :eof)


IF NOT EXIST %_varWorkingDir% md %_varWorkingDir%

echo Copying cert to staging directory in windows.
copy *.* %_varWorkingDir%\

echo Propagating to all firefox profiles.
pushd %_profileDir%
for /f "delims=" %%g in ('dir /b /AD /O-D') do (call :subthing "%%g")  
goto check

:subthing
if exist "%~1%_appDataSubDir%\Mozilla\Firefox\Profiles" (cd "%~1%_appDataSubDir%\Mozilla\Firefox\Profiles") else (exit /b)
echo Injecting into %~1's certificate database

for /f %%i in ('dir /b /AD /O-D') do (%_varWorkingDir%\certutil.exe -A -n %_varCertCommonName% -i %_varWorkingDir%\%_varCertName% -t "TCu,TCu,TCu" -d "%cd%\%%i")

echo.
cd %_profileDir%
exit /b 

:check
::check OS bit version
FOR /F "skip=2 tokens=*" %%a IN ('wmic os get osarchitecture /value')  DO (
    IF NOT DEFINED osString SET osString=%%a
)
IF %osString:~15,2%==32 (set _programdir=C:\Program Files)
IF %osString:~15,2%==64 (set _programdir=C:\Program Files ^(x86^))


popd
echo Copying to default Firefox Profile for new users.
IF EXIST "%_programdir%\Mozilla Firefox\defaults\profile\" (
copy %_varWorkingDir%\cert8.db "%_programdir%\Mozilla Firefox\defaults\profile\" /y
) ELSE (
md "%_programdir%\Mozilla Firefox\defaults\profile\"
copy %_varWorkingDir%\cert8.db "%_programdir%\Mozilla Firefox\defaults\profile\" /y)

r/usefulscripts • • Mar 13 '15

[POWERSHELL] Get-IPGeolocation.ps1 script to retrieve the geolocation data for an IP address

Thumbnail
exchangeserverpro.com
40 Upvotes

r/usefulscripts • • Jan 05 '26

[PowerShell] Get-WorkTime: PowerShell module to summarize work time from Windows event logs

39 Upvotes

Hi all,

Maybe it is useful for others as well:

Since I track my work time, I often can’t remember on Friday how I actually worked on Monday, so I needed a small helper.

Because my work time correlates pretty well with my company notebook’s on-time, I put together a small PowerShell module called Get-WorkTime.

It reads boot, wake, shutdown, sleep, and hibernate events from the Windows System event log and turns them into simple daily summaries (start time, end time, total uptime). There’s also an optional detailed view if you want to see individual sessions.

In case of crashes, it uses the last available event time and marks the inferred end time with a *. The output consists of plain PowerShell objects, so it’s easy to pipe into CSV or do further processing.

The code is on GitHub here: https://github.com/zh54321/Get-WorkTime

Feedback or suggestions are welcome.

Cheers