r/usefulscripts • • Feb 18 '24

PowerCSR Tool - A GUI tool to quickly do CSR requests for SSL certificates using Powershell on Windows

26 Upvotes

Introducing a tool that helped me to bring down my frustration levels with SSL cert generation for embedded or non IIS related webserver.

I've been doing SSL updates for my role for just over a year now and after banging my head againt the wall quite a lot with the command line version freezing or just force closing. I created a tool in Powershell to create the initial CSR and a 2048 bit key.

There are some pre-requisites that are outlined in the GitHub which are having OpenSSL installed on Windows and the environmental variables set already.

Enter your details for the domain, organisation and the rest then click Generate CSR and you'll get a CSR and private key

Hope it helps you get those services secure, faster

https://github.com/reprodev/PowerCSR


r/usefulscripts • • Aug 13 '21

CTF Socket IO, Pwntools Tips/Tricks!

Thumbnail
youtube.com
26 Upvotes

r/usefulscripts • • May 14 '21

[PowerShell]Enjoy an exciting game of PowerShell Yahtzee!

Thumbnail self.powershell
26 Upvotes

r/usefulscripts • • Feb 28 '19

[PowerShell] Run Command across multiple PC/Server

26 Upvotes

Gets a list of Computers from AD and then run a command across all of the systems i was able to open a sesson with.

Used it today to find and remove a Scheduled Task from our servers that was causing them to reboot.

#Import-Module ActiveDirectory

$session = New-PSSession -computerName DC1

Invoke-Command -scriptblock { Import-Module ActiveDirectory } -session

$sessionImport-PSSession -module ActiveDirectory -session $session

#Load a list of all computers from Active Directory

#$Computers = Get-ADComputer -Filter * | Select -ExpandProperty Name

$Servers = Get-ADComputer -Filter * -ResultPageSize 3000 | where {$_.DistinguishedName -like "*OU=Domain Controllers*" -or $_.DistinguishedName -like "*OU=File Servers*" } | Select -ExpandProperty Name

#Attempt to open a remote sessions

$Sessions = New-PSSession -ComputerName $Servers

#Run command on systems that we could connect to

$Report = Invoke-Command -Session $Sessions {Get-ScheduledTask}


r/usefulscripts • • Sep 07 '18

[PowerShell] Office 365 Inactive Distribution List Report

Thumbnail
self.sysadmin
26 Upvotes

r/usefulscripts • • Aug 02 '18

[Request] I'm writing a Powershell script to pull specific SMART values from a HDD. If you could run this PS command and post the output it would be helpful in my troubleshooting.

26 Upvotes

I have a use-case for a PS script that can get SMART data from a drive without any external tools or libraries like smartctl. SMART data is horribly standardized so without a decent sample of output from various hard drives it's difficult to make this script universal.

To anyone willing to help, I need the output of two commands run in an admin Powershell prompt.

Get-WmiObject -Namespace root\wmi MSStorageDriver_ATAPISMartData | Select -ExpandProperty InstanceName

This will output your HDD vendor and model number.

Get-WmiObject -Namespace root\wmi MSStorageDriver_ATAPISMartData | Select -ExpandProperty VendorSpecific

This will dump a seemingly nonsensical list of numbers that when properly parsed makes up a table of SMART attributes that report the number of errors, power on hours, temperature, and other data recorded by your hard drive firmware. There's no personal information and it's all read-only but as always don't go copy/pasting random commands you don't understand from the internet.

For easy copy/pasting, run the the second command piped to your clipboard so you don't have to scroll:

Get-WmiObject -Namespace root\wmi MSStorageDriver_ATAPISMartData | Select -ExpandProperty VendorSpecific | clip

Then you can just ctrl+V the output into your comment.


r/usefulscripts • • Aug 03 '17

[PowerShell] Script for TroubleShooting Exchange/O365 ActiveSync Devices

Thumbnail
practical365.com
26 Upvotes

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 • • Nov 14 '16

[POWERSHELL] Cloudflare Api and syncing with Active directories DNS.

26 Upvotes

r/usefulscripts • • Sep 09 '16

Python script to create and extend LVM partiton on ext4 and xfs filesystems

26 Upvotes
#!/usr/bin/python

__author__ = "Anirudh Srinivasan "
__copyright__ = "Copyright 2015"
__version__ = "1.0"
__maintainer__ = "Anirudh Srinivasan"
__email__ = "[email protected]"
__status__ = "Production"

from optparse import OptionParser
from subprocess import Popen, call, PIPE
from shlex import split
from commands import getstatusoutput
from os import mkdir
from os.path import basename , normpath
import time

parser = OptionParser()
parser.add_option('-d', '--drive', dest='drive', help='this is the name of the drive like sda, hdd etc..')
parser.add_option('-f', '--folder', dest='folder', help='this is the name of the directory like /data or /var/log')
parser.add_option('-t', '--fstype', dest='fstype', help='this is the type of filesystem you need like ext4 or xfs')
(opts, args) = parser.parse_args()

class FormatDrive(object):
'''This is a class that does end to end create partition, deal with lvm, make filesystem, extend filesystem, write      to fstab and resize filesystem'''

def __init__(self, drive, folder, fstype):
    self.drive = str(drive)
    self.folder =str (folder)
    self.fstype = str(fstype)

def fdisk(self):
    '''This is a definition to perform fdisk the drive in the argument'''
    before_pipe_cmd = 'echo -e "n\np\n1\n\n\nt\\n8e\nw"'
    before_pipe_args = split(before_pipe_cmd)
    after_pipe_cmd = "fdisk /dev/%s" %self.drive
    after_pipe_args = split(after_pipe_cmd)
    p1 = Popen(before_pipe_args, stdout=PIPE)
    p2 = call(after_pipe_args, stdin=p1.stdout)

def partprobe(self):
    '''This function performs the partprobe'''
    #pprobe = "partprobe /dev/%s" %self.drive
    pprobe = "partprobe"
    pprobe1 = split(pprobe)
    part = call(pprobe1)

def pvcreate(self):
    '''This function creates the physical volume '''
    pvcreate = call(["pvcreate", "/dev/%s1" %self.drive])

def volgroup(self):
    '''This function creates the physical volume and also created the volume group'''
    vgcreate = 'vgcreate -v vg_%s /dev/%s1' % (basename(normpath(self.folder)), self.drive)
    status,output = getstatusoutput(vgcreate)

def lvm(self):
    '''This function creates the logical volume'''
    lvcreate ='lvcreate -v -l "100%FREE" -n lv_{0} vg_{1}' .format(basename(normpath(self.folder)), basename(normpath(self.folder)))
    #lvcreate = 'lvcreate -v -l "100%FREE" -n lv_{0} vg_{1}' .format(self.folder, self.folder)
    status,output = getstatusoutput(lvcreate)
    print status
    print output

def makefs(self):
    '''This functions creates the filesystem on the /dev/mapper LVM device'''
    if self.fstype == 'ext4':
    	mkfs = call(["mkfs.ext4", "/dev/mapper/vg_%s-lv_%s" % (basename(normpath(self.folder)),basename(normpath(self.folder)))])
    elif self.fstype == 'xfs':
    	mkfs = call(["mkfs.xfs", "/dev/mapper/vg_%s-lv_%s" % (basename(normpath(self.folder)),basename(normpath(self.folder)))])

def makedir(self):
    '''This function makes directory inthe /root level'''
    path = "%s" %self.folder
    mkdir( path, 0755 )
    print '%s is created' %path

def write_to_fstab(self):
    '''This function appends the filesystem info to the /etc/fstab'''
    if self.fstype == 'ext4':
	string = '/dev/mapper/vg_%s-lv_%s     %s           ext4    defaults        1 1' % (basename(normpath(self.folder)), basename(normpath(self.folder)), self.folder)
    	f = open("/etc/fstab",'a')
    	f.write(string + "\n")
    	f.close()
    elif self.fstype == 'xfs':
    	string = '/dev/mapper/vg_%s-lv_%s     %s           xfs    defaults        1 1' % (basename(normpath(self.folder)), basename(normpath(self.folder)), self.folder)
    	f = open("/etc/fstab",'a')
    	f.write(string + "\n")
    	f.close()

def filesystem_mount(self):
    '''This is a simple function to mount all the drive'''
    fsmount = 'mount -a'
    status,output = getstatusoutput(fsmount)

def resizefs(self):
    ''' This method is to resize an existing filesystem'''
    if self.fstype == 'ext4':
	rs = 'resize2fs /dev/vg_%s/lv_%s' % (basename(normpath(self.folder)),basename(normpath(self.folder)))
	status,output = getstatusoutput(rs)
    elif self.fstype == 'xfs':
	rs = 'xfs_growfs /dev/vg_%s/lv_%s' % (basename(normpath(self.folder)),basename(normpath(self.folder)))
	status,output = getstatusoutput(rs)

def extend_vg(self):
   '''Extending volume group'''
   vgextend = 'vgextend vg_%s /dev/%s1'	% (basename(normpath(self.folder)), self.drive)
   status,output = getstatusoutput(vgextend)

def extend_lv(self):
   '''Extending logical volume'''
   lvextend = call(["lvextend", "-l", "+100%FREE", "/dev/vg_%s/lv_%s" %     (basename(normpath(self.folder)),basename(normpath(self.folder)))])

def main():
x = FormatDrive(opts.drive, opts.folder, opts.fstype)
intake = raw_input("Do you want to extend of create a new filesystem ?")
if intake == 'create':
    print "a new drive has been created"
    x.fdisk()
    x.partprobe()
    x.pvcreate()
    time.sleep(5)
    x.volgroup()
    time.sleep(5)
    x.lvm()
    x.makefs()
    x.makedir()
    x.write_to_fstab()
    x.filesystem_mount()
if intake == 'extend':
    print "a drive has been extended"
    x.fdisk()
    x.partprobe()
    x.pvcreate()
    x.extend_vg()
    x.extend_lv()
    x.resizefs()

if __name__ == '__main__':
if opts.drive == None or opts.folder == None or opts.fstype == None:
	parser.print_help()
		exit(-1)
main()
print 'The root folder is %s' %opts.folder
print 'the drive is %s' %opts.drive
print 'The fstype is %s' %opts.fstype

r/usefulscripts • • Jul 25 '16

[Powershell] Notify when an email is involved in a data breach.

26 Upvotes

Full write up on the blog with expected behavior etc here

Using https://haveibeenpwned.com/'s api it runs a list of emails and notifies the user if there email was included in a data breach.

This is a service the website offers. But if you work with a business that has 100s or 1000s of emails you can't expect every user to sign up.

That is where these scripts come in.

Pastebin link to Active directory version

pastebin to Array list version

There are also various functions as wrappers for the https://haveibeenpwned.com/'s api found on pastebin here


r/usefulscripts • • Dec 14 '15

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

Thumbnail
pastebin.com
26 Upvotes

r/usefulscripts • • Nov 24 '15

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

Thumbnail
pastebin.com
26 Upvotes

r/usefulscripts • • Aug 27 '15

[POWERSHELL] ConfigureExchangeURLs.ps1 - Script to configure the Client Access namespaces for Exchange Server 2013/2016

Thumbnail
exchangeserverpro.com
26 Upvotes

r/usefulscripts • • Nov 13 '14

[BATCH]Set a static IP

26 Upvotes

This was designed for our network layout, where every subnet has a gateway of xxx.xxx.xxx.1. Change it to your needs if not setup the same. Youll need to populate the variables for DNS servers and WINS. This works on Windows 7 and most XP boxes(some might not have netsh).

    @echo off
cls

netsh int ip show interface
ECHO.
set /p _varConName="enter index number (Idx) or name of connection you wish to change: "
set /p _strIP="enter Static IP Address: "
for /f "tokens=1,2,3,4 delims=." %%i  in ("%_strIP%") do (set _varGW=%%i.%%j.%%k.1)
set _varMask=255.255.255.0
set _varDNS1=
set _varDNS2=
set _varWINS1=
set _varWINS2=

 
ECHO Setting IP Address and Subnet Mask and Gateway
netsh int ip set address name = "%_varConName%" source = static addr = %_strIP% mask = %_varMask% gateway = %_varGW% gwmetric = 1
 
ECHO Setting Primary DNS
netsh int ip set dns name = "%_varConName%" source = static addr = %_varDNS1%
 
ECHO Setting Secondary DNS
netsh int ip add dns name = "%_varConName%" addr = %_varDNS2%

ECHO Setting Primary WINS
netsh int ip set wins name = "%_varConName%" source = static addr = %_varWINS1%
 
ECHO Setting Secondary WINS
netsh int ip add wins name = "%_varConName%" addr = %_varWINS2%
 

ECHO Check it: 
netsh int ip show config name = "%_varConName%"

ECHO Press any key to register DNS
pause>nul

ipconfig /registerdns

ECHO Done.
ECHO.
ECHO Press any key to exit.
pause>nul
exit

r/usefulscripts • • Nov 26 '13

[BATCH] Sysinternals and PStools batchscript

26 Upvotes

Created a batch file for easier use of Sysinternals and PStools. Thought i may be of use for you. It was asked of me to re-post it here. My final version combines this with a USB hireen boot CD.

It assumes the following filedirectory:

.\tools\pstools <-for pstools

.\tools\sysinternal <- for sysinternal

.\Logs\ <- for logfiles

.\software <- for your software

@echo off

REM Main menu
:Start
CLS
@echo *******[Main menu]********************
REM @echo [1] Application installs 
@echo [2] Client remote tools
@echo [3] Client tools
REM @echo [4] Sub menu 4
REM @echo [5] Sub menu 5
REM @echo [6] Sub menu 6
REM @echo [7] Sub menu 7
REM @echo [8] Sub menu 8
REM @echo [9] Sub menu 9
REM @echo [0] Sub menu 0
@echo [E] Exit 
@echo **************************************
set /P Program=What do you want to do?[2-3 or E]:
if /I "%Program%" EQU "1" goto :Submenu1
if /I "%Program%" EQU "2" goto :Submenu2
if /I "%Program%" EQU "3" goto :Submenu3
if /I "%Program%" EQU "4" goto :Submenu4
if /I "%Program%" EQU "5" goto :Submenu5
if /I "%Program%" EQU "6" goto :Submenu6
if /I "%Program%" EQU "7" goto :Submenu7
if /I "%Program%" EQU "8" goto :Submenu8
if /I "%Program%" EQU "9" goto :Submenu9
if /I "%Program%" EQU "0" goto :Submenu0
if /I "%Program%" EQU "E" goto :EOF
Goto :EOF

REM Sub Menu1 Applications installs
:Submenu1
CLS
@echo *******[Application installs]*********
@echo [1] Install - 
@echo [2] Install -
@echo [3] Install -
@echo [4] Install -
REM @echo [5] application 3
REM @echo [6] application 3
REM @echo [7] application 3
REM @echo [8] application 3
REM @echo [9] application 3
REM @echo [0] application 3
@echo [B] Back to main menue
@echo **************************************
set /P Program=What do you want to do?[1-4 or B]:
if /I "%Program%" EQU "1" goto :Visio2010
if /I "%Program%" EQU "2" goto :Install Project 2010 
if /I "%Program%" EQU "3" goto :EOF
if /I "%Program%" EQU "4" goto :EOF
if /I "%Program%" EQU "5" goto :EOF
if /I "%Program%" EQU "6" goto :EOF
if /I "%Program%" EQU "7" goto :EOF
if /I "%Program%" EQU "8" goto :EOF
if /I "%Program%" EQU "9" goto :EOF
if /I "%Program%" EQU "0" goto :EOF
if /I "%Program%" EQU "B" goto :Start
Goto :EOF

REM Sub Menu2 Client tools
:Submenu2
CLS
@echo *******[Client remote tools]*********
REM @echo [1] Test Whoami?
@echo [2] Check model and service tag of remote computer 
@echo [3] Connect to remote computer
@echo [4] Check what KMS server remote computer is using
@echo [5] Force KMS licence activation
@echo [6] View remote System information
@echo [7] Show Processes running on remote computer (and kill).
@echo [8] Who is logged on on remote computer, or where is user logged on.
@echo [9] Check eventlogs on remote computer
REM @echo [0] Option 0
@echo [B] Back to main menu
@echo **************************************
set /P Program=What do you want to do?[2-9 or B]:
if /I "%Program%" EQU "1" goto :Whoami
if /I "%Program%" EQU "2" goto :servicetagdell
if /I "%Program%" EQU "3" goto :remoteconnect
if /I "%Program%" EQU "4" goto :KMSserver
if /I "%Program%" EQU "5" goto :KMSserveractive
if /I "%Program%" EQU "6" goto :remotesysinf
if /I "%Program%" EQU "7" goto :remoteprocess
if /I "%Program%" EQU "8" goto :PsLoggedOn
if /I "%Program%" EQU "9" goto :eventlogs
if /I "%Program%" EQU "0" goto :EOF
if /I "%Program%" EQU "B" goto :Start
Goto :EOF

REM Sub Menu3 Client tools
:Submenu3
CLS
@echo *******[Client tools]******************
@echo [1] DiskView, graphical map of your disk
@echo [2] Process Monitor, advanced taskmanager
REM @echo [3] SMS Trace, advanced Logfile viewer
REM @echo [4] Option 4
REM @echo [5] Option 5
REM @echo [6] Option 6
REM @echo [7] Option 7
REM @echo [8] Option 8
REM @echo [9] Option 9
REM @echo [0] Option 0
REM @echo [B] Back to main menu
@echo **************************************
set /P Program=What do you want to do?[1-3 or B]:
if /I "%Program%" EQU "1" goto :DiskView
if /I "%Program%" EQU "2" goto :procmon
if /I "%Program%" EQU "3" goto :Trace32
if /I "%Program%" EQU "4" goto :EOF
if /I "%Program%" EQU "5" goto :EOF
if /I "%Program%" EQU "6" goto :EOF
if /I "%Program%" EQU "7" goto :EOF
if /I "%Program%" EQU "8" goto :EOF
if /I "%Program%" EQU "9" goto :EOF
if /I "%Program%" EQU "0" goto :EOF
if /I "%Program%" EQU "B" goto :Start
Goto :EOF



REM **************************Application installs************************************************************

REM **************************Client remote tools******************************************************************************************************************

:servicetagdell
set /P Computer=Please enter computer name or IP-adress:
wmic /node:"%Computer%" csproduct get vendor,name,identifyingnumber
@echo Press any key to go back to menu...
@pause
Goto :Start
Goto :EOF

:remoteconnect
@echo *******[Remote connect]*************************************************************
set /P Computer2=Please enter computer name or IP-adress:
@echo *******[Type exit to disconnect]****************************************************
.\Tools\PStools\psExec \\%computer2% cmd
Goto :Start
Goto :EOF

:KMSserver
@echo *******[Check what KMS server computer is using]************************************
@echo *******[Close window that pops up to return to menu]********************************
set /P KMSserver=Please enter computer name or IP-adress:
slmgr.vbs %KMSserver% /dlv
Goto :Start
Goto :EOF

:KMSserveractive
@echo *******[Force KMS licence activation]***********************
@echo *******[Close window that pops up to return to menu]********
set /P KMSserver2=Please enter computer name or IP-adress:
slmgr.vbs %KMSserver2% /ato
Goto :Start
Goto :EOF

:remotesysinf
@echo *******[View remote System information]*********************
set /P remotesys=Please enter computer name or IP-adress:
set /P remotesys2=Do you want to export information to TXT file? [Y/N]:

if /I "%remotesys2%" EQU "N" goto :remotesys2no
if /I "%remotesys2%" EQU "Y" goto :remotesys2yes
Goto :Start
Goto :EOF

:remotesys2no
.\Tools\PStools\PsInfo \\%remotesys% -d -s -h 
pause
Goto :Start
Goto :EOF

:remotesys2yes
.\Tools\PStools\PsInfo \\%remotesys% -d -s -h >> .\logs\%remotesys%.txt
Goto :Start
Goto :EOF

:remoteprocess
@echo *******[Show Processes running on remote computer]*********
set /P remoteproc=Please enter computer name or IP-adress:
.\Tools\PStools\pslist \\%remoteproc% -t
@echo ***********************************************************
set /P remoteprocq=Do you want to kill a process on %remoteproc%?[Y/N]:
if /I "%remoteprocq%" EQU "N" goto :remoteprocessno
if /I "%remoteprocq%" EQU "Y" goto :remoteprocessyes
Goto :Start
Goto :EOF
:remoteprocessno
Goto :Start
Goto :EOF

:remoteprocessyes
set /P remoteprocid=Please enter process id (PID):
.\Tools\PStools\pskill -t \\%remoteproc% %remoteprocid%
@echo *******[Killing process....]*******************************
.\Tools\PStools\pslist \\%remoteproc% -t
@echo ***********************************************************
set /P remoteprocq2=Do you want to kill another process on %remoteproc%?[Y/N]:
if /I "%remoteprocq2%" EQU "N" goto :remoteprocessno
if /I "%remoteprocq2%" EQU "Y" goto :remoteprocessyes
Goto :Start
Goto :EOF

:PsLoggedOn
@echo *******[Who is logged on on remote computer, or where is user logged on.]*******
@echo Do you want to search for a user or,
set /P PsLoggedOnq=check who is logon on a computer [Search/Computer]?:
if /I "%PsLoggedOnq%" EQU "Search" goto :PsLoggedOns
if /I "%PsLoggedOnq%" EQU "Computer" goto :PsLoggedOnc
Goto :Start
Goto :EOF

:PsLoggedOns
@echo ***********************************************************
@echo Search for where user is logged on
@echo (warning may take a while, press CTRL+c to abort) 
@echo ***********************************************************
set /P PsLoggedOnuser=Please enter username to search for:
.\Tools\PStools\psloggedon %PsLoggedOnuser%
Pause
Goto :Start
Goto :EOF

:PsLoggedOnc
@echo *******[Who is logged on to specific computer]******************
set /P PsLoggedOncomp=Please enter computer name:
.\Tools\PStools\psloggedon \\%PsLoggedOncomp%
Pause
Goto :Start
Goto :EOF


:eventlogs
set /P eventlogsc=Please enter computer name:
set /P eventlogsd=how many days back?:
set /P eventlogse=Do you want to only show errors? [Y/N]:
if /I "%eventlogse%" EQU "Y" goto :eventlogsyes
if /I "%eventlogse%" EQU "N" goto :eventlogsno
Goto :Start
Goto :EOF

:eventlogsyes
@echo Creating %eventlogsc%_Eventerror.log.....
.\Tools\PStools\psloglist -d %eventlogsd% -f w -S \\%eventlogsc% >> .\logs\%eventlogsc%_Event_error.log
@echo I am done now...
pause
Goto :Start
Goto :EOF

:eventlogsno
@echo Creating %eventlogsc%_Event_all.log.....
.\Tools\PStools\psloglist -d %eventlogsd% -S \\%eventlogsc% >> .\logs\%eventlogsc%_Event_all.log
@echo I am done now...
Pause
Goto :Start
Goto :EOF




REM **************************Client tools******************************************************************************************************************
:DiskView
.\Tools\sysinternal\DiskView.exe
Goto :Start
Goto :EOF

:procmon
.\Tools\sysinternal\procmon.exe
Goto :Start
Goto :EOF

r/usefulscripts • • Aug 26 '24

[PowerShell] Cleaning up Active Directory computer objects

25 Upvotes

Hi Everyone,

I wrote a PowerShell module that helps cleaning stale/dead computer objects in Active Directory. Dead servers, clusters, workstations -> all of it.

CleanupMonster (as that's it's name) has the following features:

  • Ability to disable, disable and move, move and disable, move or delete computers

  • All five actions from above can have different rules when a given task happens

  • It's able to check when the object was created and prevent the deletion of objects younger than X days

  • It's able to check LastLogonDate and LastPasswordSet and requires it to be certain days old to consider for disabling, moving, or delete

  • If LastLogonDate or LastPasswordSet is empty, it is treated as never used; therefore, it applies the maximum number of days to it.

  • It can check Intune data for LastLogonDate for a given computer, providing the ability to improve data with cloud data for those non-connected machines.

  • It can check Entra ID data (Azure AD) for LastLogonDate for a given computer to improve the assessment of deletion.

  • It's able to check Jamf PRO for LastLogonDate for macOS devices.

  • You can target whole forest, or include/exclude specific domains from this process

The source code is here: https://github.com/EvotecIT/CleanupMonster

The module is available on PowerShellGallery:

Install-Module CleanupMonster -Force -Verbose

I've also prepared the blog post about it that talks about it a bit more: https://evotec.xyz/mastering-active-directory-hygiene-automating-stale-computer-cleanup-with-cleanupmonster/

The module has many options and features that allow you to customize your cleanup needs. It can gather data from AD and enhance it with Azure AD/Intune LastLogon information, along with Jamf Pro information if you use macOS devices. It has builtin reporting to HTML to be able to know what was done now, what will be done in future and basically provides you one stop overview of all your devices.

Hope you enjoy this one :-)


r/usefulscripts • • Feb 28 '22

[PowerShell] Comparing advanced PowerShell objects

25 Upvotes

Today's blog post https://evotec.xyz/powershell-comparing-advanced-objects/ is about comparing advanced PowerShell objects.

With a simple command, one can compare two or multiple objects together

Compare-MultipleObjects -Objects $Object1, $Object2 -FlattenObject | Format-Table

With objects that are more advanced, I'm using ConverTo-FlatObject (described here: https://www.reddit.com/r/PowerShell/comments/t2p5w1/converting_advanced_object_to_flat_object/) internally to allow for comparing of objects with nested objects within.

Compare-MultipleObjects -Objects $Object1, $Object2 -FlattenObject -Summary -ObjectsName 'Object1', 'Object2' | Format-Table *

I've also added this ability to PSWriteHTML which allows for Visual comparison of two or more objects:

$Object19,$Object20 | Out-HtmlView -Compare -HighlightDifferences -Filtering -WordBreak break-all -FlattenObject

Both commands are available as part of PSWriteHTML and PSSharedGoods modules.

Install-Module PSWriteHTML -AllowClobber -Force
Install-Module PSSharedGoods -AllowClobber -Force

Sources:


r/usefulscripts • • Jul 13 '21

Who Reports to Whom?- Get manager reports quickly

Thumbnail self.office365
25 Upvotes

r/usefulscripts • • Mar 27 '21

[Request][Powershell] O365 calendar permissions tool

25 Upvotes

Recently got a request to ensure everyone in the company has read access to each others calendars. Access is given by being member of 'security group (countrycode here)' by powershell now.

Thing is there is to be expected that sometimes we will need a function to get all included in one press of a button except users x or group 'security group (other country code).

So i wonder does anyone have a script like this lying around? I have started to build my own user friendly, .net menu based script around these requirements but considering how common this must be i wonder if there is already a script around?


r/usefulscripts • • Aug 04 '20

[PowerShell] Mailozaurr – New mail toolkit (SMTP, IMAP, POP3) with support for oAuth 2.0 and GraphApi

25 Upvotes

Here's my new PowerShell module to send emails via SMTP or Graph API with support for oAuth 2.0. It can also access POP3 and IMAP (in limited form), get MX, SPF, DMARC, DKIM records, and generate some reporting. It's a start, and something I will hopefully build on. I'm looking for feedback (good and bad), and if you have some ideas on features or know how to solve problems I've encountered, please let me know. All development will happen on GitHub, but it should be installed from PSGallery.

Details with history, examples, screenshots: https://evotec.xyz/mailozaurr-new-mail-toolkit-smtp-imap-pop3-with-support-for-oauth-2-0-and-graphapi-for-powershell/

All sources: https://github.com/EvotecIT/Mailozaurr

To install from PSGallery (minimized, signed version)

Install-Module Mailozaurr

To connect to POP3

$Credentials = Get-Credential
$Client = Connect-POP3 -Server 'pop.gmail.com' -Credential $Credentials -Port 995 -Options Auto
Get-POP3Message -Client $Client -Index 0 -Count 5
Save-POP3Message -Client $Client -Index 6 -Path "$Env:UserProfile\Desktop\mail.eml"
Disconnect-POP3 -Client $Client

To connect to IMAP

$UserName = '[email protected]'
$Password = ''
$Client = Connect-IMAP -Server 'imap.gmail.com' -Password $Password -UserName $UserName -Port 993 -Options Auto
Get-IMAPFolder -Client $Client -Verbose
## Not yet sure how to best process messages
#Get-IMAPMessage -Client $Client -Verbose
#foreach ($folder in $client.Data.Inbox.GetSubfolders($false)) {
#    "[folder] {0}", $folder.Name
#}
Disconnect-IMAP -Client $Client

To send SMTP email oAuth 2.0

$ClientID = '939333074185'
$ClientSecret = 'gk2ztAGU'
$CredentialOAuth2 = Connect-oAuthGoogle -ClientID $ClientID -ClientSecret $ClientSecret -GmailAccount '[email protected]'
Send-EmailMessage -From @{ Name = 'Przemysław Kłys'; Email = '[email protected]' } -To '[email protected]' `
    -Server 'smtp.gmail.com' -HTML $Body -Text $Text -DeliveryNotificationOption OnSuccess -Priority High `
    -Subject 'This is another test email' -SecureSocketOptions Auto -Credential $CredentialOAuth2 -oAuth

Sending email via MS Graph

# Credentials for Graph
$ClientID = '0fb383f1'
$DirectoryID = 'ceb371f6'
$ClientSecret = 'VKDM_'
$Credential = ConvertTo-GraphCredential -ClientID $ClientID -ClientSecret $ClientSecret -DirectoryID $DirectoryID
# Sending email
Send-EmailMessage -From @{ Name = 'Przemysław Kłys'; Email = '[email protected]' } -To '[email protected]' `
    -Credential $Credential -HTML $Body -Subject 'This is another test email 1' -Graph -Verbose -Priority High
# sending email with From as string (it won't matter for Exchange )
Send-EmailMessage -From '[email protected]' -To '[email protected]' `
    -Credential $Credential -HTML $Body -Subject 'This is another test email 2' -Graph -Verbose -Priority Low

DNS records verification:

Find-MxRecord -DomainName 'evotec.pl', 'evotec.xyz' | Format-Table *
Find-DMARCRecord -DomainName 'evotec.pl', 'evotec.xyz' | Format-Table *
Find-SPFRecord -DomainName 'evotec.pl', 'evotec.xyz' | Format-Table *
Find-DKIMRecord -DomainName 'evotec.pl', 'evotec.xyz' | Format-Table *
Find-DKIMRecord -DomainName 'evotec.pl', 'evotec.xyz' -Selector 'selector1' | Format-Table *

And so on... all cmdlets (POP3, IMAP, SMTP support oAuth, ClearText passwords, and Credentials). There's also some reporting built-in and support for MS Graph emailing.


r/usefulscripts • • Jun 04 '20

[Terraform] AWS Lambda to Update Security Group Egress with O365 Endpoint Networks

Thumbnail
github.com
25 Upvotes

r/usefulscripts • • Dec 08 '19

[PowerShell] Getting Azure Health by parsing HTML using PSParseHTML

25 Upvotes

Long story: https://evotec.xyz/getting-azure-health-parsing-html-website-using-psparsehtml/

Short story:

I neede Azure Health to be available in PowerShell. As there's no Graph API as far as I know, I decided to parse the website to extract it. As part of this exercise you get 2 things today:

  1. PowerShell module that can get Azure Health in a single command

  2. Improved PowerShell module that extracts HTML tables from websites with ease.

PowerShell Modules involved:

You also may be interested in another module:

The last one requires Graph API permissions.

Code example:

$Azure = Get-WinAzureHealth -Formatted

New-HTML {
    foreach ($Region in $Azure.Keys) {
        New-HTMLTab -Name $Region {

            New-HTMLTable -DataTable $Azure.$Region -Filtering {
                foreach ($Column in $Azure.$Region[0].PSObject.Properties.Name) {
                    New-HTMLTableCondition -Name $Column -Value 'Good' -BackGroundColor Green -Color White -Alignment center
                    New-HTMLTableCondition -Name $Column -Value 'Information' -BackGroundColor Blue -Color White -Alignment center
                    New-HTMLTableCondition -Name $Column -Value 'Warning' -BackGroundColor Orange -Alignment center
                    New-HTMLTableCondition -Name $Column -Value 'Critical' -BackGroundColor Red -Color White  -Alignment center
                }
            }
        }
    }
} -FilePath $PSScriptRoot\AzureHealth.Html -UseCssLinks -UseJavaScriptLinks -TitleText 'Azure' -ShowHTML

Code example for standard page parsing:

$Test = ConvertFrom-HtmlTable -Url 'https://www.goal.com/en-us/premier-league/table/2kwbbcootiqqgmrzs6o5inle5'
$Test | Format-Table -AutoSize *
$Test = ConvertFrom-HtmlTable -Url 'https://www.goal.com/en-us/premier-league/table/2kwbbcootiqqgmrzs6o5inle5' -Engine AngleSharp
$Test | Format-Table -AutoSize *

r/usefulscripts • • Sep 01 '17

Powershell [request]

25 Upvotes

We are doing AD cleanup, I have powershell that generates accounts that have not logged in within 120 days. Below is what I'm using.

  1. I will be going through this list and putting the sam account (of service accounts) name into a new excel spreadsheet where I would like a powershell script to read each line and disable those accounts and move them to a certain OU

later on.. after dealing with improper service accounts. I'd like to take that same script (below) and have something in a fashion that disables the accounts, moves those accounts to a certain OU and also writes those accounts to an excel spreadsheet that is datetime stamped for tracking purposes.

if you need further clarification feel free to ask questions, but I'm a little lost on how I need to approach this, basically I have a huge list of people that are no longer there that also contains service accounts I need to move first.

$CurrentDate=GET-DATE

Number of Days to check back.

$NumberDays=120

Organizational Unit to search

Import-Module ActiveDirectory

GET-ADUSER -filter * -properties LastLogonDate | where { $_.LastLogonDate.AddDays($NumberDays) -lt $CurrentDate } |? { ($_.distinguishedname -notlike 'network service accounts') } |? { ($_.distinguishedname -notlike 'W2K SERVERS') } |? { ($_.distinguishedname -notlike 'VMWARE') } |? { ($_.distinguishedname -notlike 'unity') } |? { ($_.distinguishedname -notlike 'vmtest') } |? { ($_.distinguishedname -notlike 'cisco') } |? { ($_.distinguishedname -notlike 'managed service accounts') } |? { ($_.distinguishedname -notlike 'VDI') } |? { ($_.distinguishedname -notlike 'pacs') } |? { ($_.distinguishedname -notlike 'foreignsecurityprincipals') } | Where {$_.Enabled -eq $true} | export-csv -path C:\scripts\notloggedinfor120days.csv -Encoding ascii -NoTypeInformation