r/usefulscripts • • Aug 16 '17

[REQUEST] Notification if a specific user is locked out of AD

25 Upvotes

our office is currently windows admin-less and were all trying to pick up the slack. Personally im decent with windows server, but never got far enough for powershell/batch scripting. We have a certain service account, that gets locked out sometimes, lets call it svc-appdev what i need is a check and email notification for when svc-appdev gets locked out.

there is software running on a "tools"server that emails the IT team when ANYONE gets locked out, but it does not have options to email a specific address when a specific user gets locked. basically here is what i need:

user svc-appdev gets locked out > send email to [email protected]

thanks for any help in advance


r/usefulscripts • • Jul 11 '17

[Powershell][Citrix 7.x]Script to autokill empty and stale VDIs

25 Upvotes

I have this set as a scheduled task for 4am on our delivery controller. It essentially searches for all VDIs with disconnected sessions over 24 hours old and all machines with no logged in users and shuts them down. Pretty basic, but very handy for preventing locked up VDIs, unregistered machines and stuck sessions.

Add-PSSnapin citrix*
###::: add your desktop delivery group name here
$DeliveryGroupName = 


###::: 24 hours ago
$time = (Get-Date).AddDays(-1)
$dayago = Get-Date $time -format s


###::: checks for empty machines and shuts them down
Get-BrokerMachine -Filter "(((DesktopGroupName -eq `"$DeliveryGroupName`") -and (PowerState -eq `"On`") -and (-not (AssociatedUserName -contains `"*`"))) -and (SessionSupport -eq `"SingleSession`"))" -MaxRecordCount 500 -Property @("MachineName") -ReturnTotalRecordCount -Skip 0 -SortBy "+AssociatedUserNames" | Foreach-object { New-BrokerHostingPowerAction -Action "TurnOff" -MachineName $_.MachineName }


###::: checks for disconnected sessions over 24 hours old and shuts them down
Get-BrokerMachine -Filter "(((DesktopGroupName -eq `"$DeliveryGroupName`") -and (SessionState -eq `"Disconnected`") -and ((SessionStartTime -lt `"$dayago`"))) -and (SessionSupport -eq `"SingleSession`"))" -MaxRecordCount 500 -Property @("MachineName") -ReturnTotalRecordCount -Skip 0 -SortBy "+AssociatedUserNames" | Foreach-object { New-BrokerHostingPowerAction -Action "TurnOff" -MachineName $_.MachineName }

r/usefulscripts • • Jan 03 '17

[PowerShell]Remove-VMwareSnapshots • x-post

Thumbnail
reddit.com
25 Upvotes

r/usefulscripts • • Aug 26 '16

[BASH]Updated IPTables Script to block by Country

Thumbnail
github.com
25 Upvotes

r/usefulscripts • • Jul 09 '16

[BATCH]Moving up directory N number of times by typing "up N" where N is the number of times

25 Upvotes

A bash batch script called up so that if I'm in /a/very/deeply/nested/path/somewhere and I want to go "up" N directories, I can type up N:

/a/very/deeply/nested/path/somewhere> up 4

/a/very>

----up.bat----
@ECHO OFF
SET arg1=%1
for /L %%i in (1,1,%1) do (
cd..
)

Inspiration/Source, also has the code for BASH

Put the up.bat file in a directory thats also in your system variable path, like System32 or something


r/usefulscripts • • Sep 08 '15

[Powershell] Find certificates about to expire on domain

Thumbnail
bug-man.org
25 Upvotes

r/usefulscripts • • Apr 13 '15

[Power Shell] Inventory Monitors with PowerShell - Pastebin.com

Thumbnail
pastebin.com
25 Upvotes

r/usefulscripts • • Oct 30 '14

[PowerShell] New PC setup - Is there a way to automate this stuff?

25 Upvotes

I'm going blind trying to find the tool or script that will allow me to run updates on a Windows PC, reboot, auto login, run updates, reboot and keep doing that until updates are compete.

I'm cobbling together a list of scripts that will allow us to prep PCs that our user's buy. The stuff I'm using/testing now:

  • PowerShell: The basis of the entire script

  • Chocolatey: amazing. Using it to install Boxstarter and basic app set. (Read: ninite pro without paying)

  • Boxstarter/Winconfig - Turning off windows settings like UAC, power settings configs

  • Wuinstall: I had high goes to this but the documentation is not that great. I'm still trying to get reboot/recycle to work.

The list of tasks I'm trying to turn into a "click and walk away" process.

  • Basic Windows configurations, power, UAC, RDP, enable-windowsupdates, explorer settings, etc

  • Uninstall bloatware

  • Run Updates to completion!

  • Install a set of MSI files to install a GFI app

  • Write it all to a log file

  • Change something to let us know it's done e.g. change desktop color

Am I nuts or is this doable as 1 tool?


r/usefulscripts • • Aug 23 '14

[BATCH] One-liner to detect full, complete Windows version and store it in a variable

25 Upvotes

I've been going crazy (like many others) trying to find a good one-liner to get the FULL Windows version string (not just the generic kernel code e.g. 6.1) into a variable for detection in scripts.

Thanks to UJSTech on Spiceworks forums for this.

Each version (below) stores the detected Windows version in a variable called WIN_VER.


Code

:: Version for running directly from a command-prompt:
for /f "tokens=3*" %i IN ('reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName ^| Find "ProductName"') DO set WIN_VER=%i %j

:: Version for inside of a batch file:
for /f "tokens=3*" %%i IN ('reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName ^| Find "ProductName"') DO set WIN_VER=%%i %%j

Here are some values I've personally tested and observed:

Actual Windows VersionDetected String
Windows XP Professional SP3Microsoft Windows XP
Windows Server 2003 EnterpriseMicrosoft Windows Server 2003
Windows Vista Home PremiumWindows Vista (TM) Home Premium
Windows Vista UltimateWindows Vista (TM) Ultimate
Windows 7 Home PremiumWindows 7 Home Premium
Windows 7 ProfessionalWindows 7 Professional
Windows 7 EnterpriseWindows 7 Enterprise
Windows 8.1 ProfessionalWindows 8.1 Pro
Windows Server 2008 R2 StandardWindows Server 2008 R2 Standard
Windows Server 2012 R2 StandardWindows Server 2012 R2 Standard

Hope this helps others out.


r/usefulscripts • • Jun 10 '21

[Question] Trying to switch between monitors and changing sound output in one place

24 Upvotes

Hello Everyone

Not sure if this is the right community to ask, but maybe you can help me out.

I just got my PC hooked up to my Television which is in the same room, via HDMI. Now I would like to be able to switch between the two screens from my PC to the Television as my main output. Additionally I would also like to change the Audio output source to my TV.

Currently, I have to have 3 monitors on all the time and switch the audio output when needed. Since I do this most days and I have chronic hand pain, I would like to avoid the hassle. I also don't like that I have 3 monitors running at the same time, even if I don't need them.

Maybe there is a program for that, maybe someone has an Idea how to script it. I wasn't able to find anything in this direction so far.

So If anyone knows where I could find such a program, or maybe just have a better Idea where to post this question, please let me know. Much appreciated.


r/usefulscripts • • Sep 22 '20

[Bash] Docker Alias Goodies

24 Upvotes

I was an ops guy for a long while, which means that Docker was a constant presence in my life.

Frustrated with actually using the CLI and being an overall lazy programmer, I've created a set of aliases (that use each other inside themselves!) to prevent the need to enter them constantly, multiple dozens of times a day (literally got there one day, I counted).

This is intended to go inside your .bashrc so these puppies will be evaluated and available in each new terminal session.

https://github.com/TomGranot/useful-snippets/blob/master/docker-bashrc/docker-bashrc.sh


r/usefulscripts • • Mar 14 '20

[VBScript] DeDup. Convert duplicate files into hardlinks or symlinks to save disk space.

Thumbnail
pastebin.com
24 Upvotes

r/usefulscripts • • Apr 04 '19

[PowerShell] Dashimo - Conditional Formatting for HTML Tables and more

24 Upvotes

Hi guys,

After a few days of work, I'm releasing an updated version of Dashimo.

New blog post with examples/screenshots and how to: https://evotec.xyz/dashimo-easy-table-conditional-formatting-and-more/

If you never have seen this before: https://evotec.xyz/meet-dashimo-powershell-generated-dashboard/ is an overview of what Dashimo is.

What's new:

  • conditional formatting

  • more exposed parameters to Table

  • description of Autorefresh

  • Show parameter for dashboard

Conditional formatting in action...

$Process = Get-Process | Select-Object -First 30

Dashboard -Name 'Dashimo Test' -FilePath $PSScriptRoot\DashboardSimplestTableConditions.html -Show {
    Table -DataTable $Process -HideFooter {
        TableConditionalFormatting -Name 'ID' -ComparisonType number -Operator gt -Value 10000 -Color BlueViolet -Row
        TableConditionalFormatting -Name 'Name' -ComparisonType string -Operator eq -Value 'chrome' -Color White -BackgroundColor Crimson -Row
        TableConditionalFormatting -Name 'PriorityClass' -ComparisonType string -Operator eq -Value 'Idle' -Color White -BackgroundColor Green
    }
}

Easy example:

$Process = Get-Process | Select-Object -First 30

Dashboard -Name 'Dashimo Test' -FilePath $PSScriptRoot\DashboardSimplestTable.html -AutoRefresh 15 -Show {
    Table -DataTable $Process -DefaultSortIndex 4 -ScrollCollapse -HideFooter -Buttons @()
}

Complicated, still easy example:

$Process = Get-Process | Select-Object -First 30
$Process1 = Get-Process | Select-Object -First 5
$Process2 = Get-Process | Select-Object -First 10
$Process3 = Get-Process | Select-Object -First 10

Dashboard -Name 'Dashimo Test' -FilePath $PSScriptRoot\DashboardEasy.html -Show {
    Tab -Name 'First tab' {
        Section -Name 'Test' {
            Table -DataTable $Process
        }
        Section -Name 'Test2' {
            Panel {
                Table -DataTable $Process1
            }
            Panel {
                Table -DataTable $Process1
            }
        }
        Section -Name 'Test3' {
            Table -DataTable $Process -DefaultSortColumn 'Id'
        }
    }
    Tab -Name 'second tab' {
        Panel {
            Table -DataTable $Process2
        }
        Panel {
            Table -DataTable $Process2
        }
        Panel {
            Table -DataTable $Process3 -DefaultSortIndex 4
        }
    }
}

Enjoy and hope you like this one.


r/usefulscripts • • Nov 02 '18

[PowerShell] PSBlackListChecker - Updates with support for MS Teams, Slack. Faster thru Runspaces.

24 Upvotes

Just wanted to give you some update of this little module for the weekend. If this is first time you're reading about this module it's very simple PowerShell module that allows to verify whether your IP address is on blacklist or not.

Information can be found here: https://evotec.xyz/psblacklistchecker-notifications-to-microsoft-teams-slack-of-blacklisted-ips/

Generally there are 3 things:

- email notifications

- microsoft teams notifications

- slack notifications

- manual checks

There's also a comparison done on workflow vs runspaces and NET.DNS vs Resolve-DNS command. It has some surprising results but be aware your results may vary. If you think test methodology is not good enough please let me know :-)


r/usefulscripts • • Feb 18 '18

[python] youtube to mp3 converter script, requires ffmpeg and `pip install youtube_dl`

Thumbnail
gist.github.com
24 Upvotes

r/usefulscripts • • Nov 07 '17

Using powershell to install puppet on windows pc

24 Upvotes

We have recently started using puppet as you know installing an agent on over 100 PC is tedious luckily with the help of reddit i was able to create a script that will help the below script wont take a certname ( i did not need it) if you the cert name look at my other reddit post which will have it

https://www.reddit.com/r/PowerShell/comments/7b7kxs/installing_puppet_using_powershell/

the below script will take a list of machine and run the puppet agent on them i have done this and ran great in my environment maybe someone can use it in the future

$pc= Get-Content "\\dactyo\tony\Infra\NY\Documentation\Puppet_agent_install\pc.txt"
$s=New-PSSession -ComputerName $pc -Credential (Get-Credential)
Invoke-Command -Session $s -ScriptBlock {
# This script installs the windows puppet agent on windows 
# from the master's pe_repo by downloading it to C:\tmp first and then running
# msiexec on it from there.

$puppet_master_server = "ntpuppet01.dactyo"
$msi_source = 'http://puppet01/puppet-agent-5.3.2-x64.msi'
$msi_dest = "C:\dactyo\puppet-agent-5.3.2-x64.msi"

# Start the agent installation process and wait for it to end before continuing.
Write-Host "Installing puppet agent from $msi_source"

Function Get-WebPage { Param( $url, $file, [switch]$force)
  if($force) { 
	[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} 
  }
  $webclient = New-Object system.net.webclient
  $webclient.DownloadFile($url,$file)
}

Get-WebPage -url $msi_source -file $msi_dest -force
$msiexec_path = "C:\Windows\System32\msiexec.exe"
$msiexec_args = "/qn /log c:\log.txt /passive /q /I $msi_dest PUPPET_MASTER_SERVER=$puppet_master_server"
$msiexec_proc = [System.Diagnostics.Process]::Start($msiexec_path, $msiexec_args)
$msiexec_proc.WaitForExit() }

r/usefulscripts • • Aug 22 '17

[Help] Script that will say when the last logon was and who logged on

24 Upvotes

Hello! I have been looking for a script that will tell me when the last person logged onto a computer and also who logged onto it. I would also like to do this to a list of computers and export the results to csv or txt file. So far I have found this script:

$File = 'C:\Users\1525704633A\Documents\test\logtest2.txt'
$computerName = $env:computername
$CurrentUser = $env:username
$date = Get-Date -Format s # or you can use yyyy-MM-dd_HH:mm:ss
$HasNewCmdlet = Get-Command Get-NetIPAddress -ErrorAction 
SilentlyContinue

if (!(Test-Path $File)) {
    New-Object psobject -Property @{
        Date = ''
        ComputerName = ''
        CurrentUser = ''
        IPAddresses = ''
    } | Select-Object Date, ComputerName, CurrentUser, IPAddresses | 
Export-Csv 
C:\Users\1525704633A\Documents\test\Complete.csv -
NoTypeInformation
}

# Command below uses Get-NetIPAddress, this will only work on 
Windows 8.1 machines and 
above to my knowledge.
If ($HasNewCmdlet)
{
    #$IPAddresses = Get-NetIPAddress -IPAddress '172.20.*' | Select-
Object -
ExpandProperty IPAddress
    # using this to test on my machine
    $IPAddresses = Get-NetIPAddress | Select-Object -ExpandProperty 
IPAddress | Where-
Object {$_ -notmatch '^(169|127)|:'}
}
Else
{
    $IPAddresses = Get-WmiObject 
Win32_NetworkAdapterConfiguration | Select-Object -
ExpandProperty IPAddress | Where-Object {$_ -like '*.*'}
}

$IPAddressesCount = $IPAddresses | Measure-Object | Select-Object -
ExpandProperty 
Count

If ($IPAddressesCount -gt 1)
{
    # Concatenate array of IPs into a single string separated by 
commas.
    $IPAddresses = [string]::Join(', ', $IPAddresses)
}

$obj = New-Object psobject -Property @{
    Date = $date
    ComputerName = $computerName
    CurrentUser = $CurrentUser
    IPAddresses = $IPAddresses
} | select Date, ComputerName, CurrentUser, IPAddresses

$data = @(Import-Csv $File | Where-Object {$_.date})
$data += $obj
$data = $data | Group-Object computername, currentuser | 
ForEach-Object {$_.group | 
Select-Object -Last 1} | Sort-Object date

$data | Export-Csv 
C:\Users\1525704633A\Documents\test\Complete.csv -
NoTypeInformation

The only issue so far with this script is that I am testing it with 3 computers. Mine and 2 others. It only shows my computer and I have no clue why.

Any help would be greatly appreciated!

EDIT: This is in Powershell by the way. Forgot to put that in the title.


r/usefulscripts • • Aug 15 '17

Request - AD pull users and PC name + log on/off

24 Upvotes

Hi Guys,

does anyone have or can create one for me that will show the , Username, Computer logged in/last logged in, Log on, log off, OS?

I managed to show Computer name OS but unsure on how to pull in the the username with it or if they need to be done separate then merged etc.


r/usefulscripts • • Nov 03 '15

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

Thumbnail
pastebin.com
24 Upvotes

r/usefulscripts • • Jul 28 '15

[POWERSHELL] Regain SQL Server sysadmin access.

Thumbnail
gallery.technet.microsoft.com
24 Upvotes

r/usefulscripts • • Feb 19 '15

[POWERSHELL]YASIS - Yet another System Info Script!

Thumbnail
gist.github.com
24 Upvotes

r/usefulscripts • • Jan 13 '14

[BATCH] Adobe Flash Removal (purge all versions of Adobe Flash)

24 Upvotes

Purpose: Purges all versions of Adobe Flash Player from a system.

This can be used to clean a box of corrupt/broken/old Flash installations in preparation for a fresh install, or simply to get rid of Flash entirely.


Download

v2.0.0 (2016-09-06)


Saves a log file to C:\Logs\%COMPUTERNAME%_adobe_flash_player_nuker.log


r/usefulscripts • • Apr 08 '13

[POWERSHELL] Unlock Active Directory Account(s)

24 Upvotes

Very basic script I threw together to start learning Powershell. We have a problem where one of our service accounts keeps getting locked out when deploying software, so I wrote up this little script to unlock the account.

Run the script and pass it a list of account names to unlock. e.g.

.\AD_unlock_account.ps1 darth.vader gordon.freeman bender

Download

v1.1 (2014-01-16)

v1.0 (2013-04-08)

In our shop it runs as a scheduled task attached to the event log. It fires whenever it sees Event #4740 occur in the Security event log.


Saves a log to c:\Logs\AD_account_unlock.log (configurable) of when the script ran and what accounts it unlocked.


r/usefulscripts • • May 04 '24

[PowerShell] - PixelPoSH is a PowerShell script designed for generating random backgrounds.

Thumbnail
github.com
23 Upvotes