r/usefulscripts • • Mar 22 '17

[POWERSHELL] Enable Unified Audit Logging for all Office 365 Customers

22 Upvotes

Unified Audit Logging is a feature that really should be on by default, though I understand it probably carries a lot of overhead for Microsoft.

Here's a set of scripts you can run to enable it across your customers tenants - provided you have delegated admin access.

I've run this on our customers without issue, though you may want to double and triple check this to make sure you're happy with it. It works by temporarily creating admins in your customer tenants with a standard password. Unfortunately I couldn't find a better way - The Unified Audit Log isn't something that can be enabled using the standard Exchange Online Delegated Administration method.


r/usefulscripts • • Feb 07 '17

[POWERSHELL] Jenkins, Powershell, AWS and Cloudflare Automated Deployment. (Part2 Configure AWS)

22 Upvotes

Since the last post I have updated the github The full export of the Jenkins Job is in there (The Zip file) with the Plugins list and the build code so if you like you can probably get it working off of that.

But if you go to my blog it walks you through building the whole thing from scratch, and will save you some time figuring out the AWS configuration.

In the next few weeks I'll post the final part that covers the cloudflare integration. Though that should be a very short post.


r/usefulscripts • • Aug 17 '16

[POWERSHELL] since there's no native 'watch' command, you can do: while ($true) {rasdial; sleep 1; clear}

22 Upvotes
while ($true) {rasdial; sleep 1; clear}

r/usefulscripts • • Jul 19 '16

Harvest all Microsoft Office updates to slipstream into install folder easily.

22 Upvotes

I found this gem and wanted to share.

https://technet.microsoft.com/en-us/library/cc178995(v=office.14).aspx

Save this as collectupdates.vbs on a system, install office and all updates for that version, and then run the script. A folder will pop up with all the office update install files. Copy that to your office installer\updates folder and every install after that will be completely up to date. Repeat periodically to refresh updates.

This does not discriminate between office versions, so in my case having moved from office 2010 to 2013 on my test system I saw the folder populated with both 2010 and 2013 updates. I recommend using a freshly installed system to harvest from.

[code] Dim oMsi,oFso,oWShell

Dim Patches,SumInfo

Dim patch,record,msp

Dim qView

Dim sTargetFolder,sMessage

Const OFFICEID = "000-0000000FF1CE}"

Const PRODUCTCODE_EMPTY = ""

Const MACHINESID = ""

Const MSIINSTALLCONTEXT_MACHINE = 4

Const MSIPATCHSTATE_APPLIED = 1

Const MSIOPENDATABASEMODE_PATCHFILE = 32

Const PID_SUBJECT = 3 'Displayname

Const PID_TEMPLATES = 7 'PatchTargets

Set oMsi = CreateObject("WindowsInstaller.Installer")

Set oFso = CreateObject("Scripting.FileSystemObject")

Set oWShell = CreateObject("Wscript.Shell")

'Create the target folder

sTargetFolder = oWShell.ExpandEnvironmentStrings("%TEMP%")&"\Updates"

If Not oFso.FolderExists(sTargetFolder) Then oFso.CreateFolder sTargetFolder

sMessage = "Patches are being copied to the %Temp%\Updates folder." & vbCrLf & "A Windows Explorer window will open after the script has run."

oWShell.Popup sMessage,20,"Office Patch Collector"

'Get all applied patches

Set Patches = oMsi.PatchesEx(PRODUCTCODE_EMPTY,MACHINESID,MSIINSTALLCONTEXT_MACHINE,MSIPATCHSTATE_APPLIED)

On Error Resume Next

'Enum the patches

For Each patch in Patches

If Not Err = 0 Then Err.Clear

'Connect to the patch file

Set msp = oMsi.OpenDatabase(patch.PatchProperty("LocalPackage"),MSIOPENDATABASEMODE_PATCHFILE)

Set SumInfo = msp.SummaryInformation

If Err = 0 Then

    If InStr(SumInfo.Property(PID_TEMPLATES),OFFICEID)>0 Then

        'Get the original patch name

        Set qView = msp.OpenView("SELECT `Property`,`Value` FROM MsiPatchMetadata WHERE `Property`='StdPackageName'")

        qView.Execute : Set record = qView.Fetch()

        'Copy and rename the patch to the original file name

        oFso.CopyFile patch.PatchProperty("LocalPackage"),sTargetFolder&"\"&record.StringData(2),TRUE

    End If

End If 'Err = 0

Next 'patch

oWShell.Run "explorer /e,"&chr(34)&sTargetFolder&chr(34) [/code]


r/usefulscripts • • Jun 14 '16

[POWERSHELL] AWS Report Script

22 Upvotes

I created a multiple account report script. I set it up to run as a scheduled tasks and can pull the Ec2 instance from several different AWS accounts. The script covers all regions in the account and can out puts information like:

Environment, Region, Instance Name, Instance ID, Instance Type, Powered State, Private Ip Address, Public Ip Address, Security Groups

An example of the output html page can be found here and the csv file here

If you're interested in a walk through on how to setup the script you can find it on my blog.

If you're just interested in the script it can be found on pastebin or on my my github.

The aws plugin is here


r/usefulscripts • • Apr 04 '16

[HTA/VBScript] Password Expiration Notification Identification Screen

22 Upvotes

Hello,

Below you will find a script that we have found to be very helpful at reminding users to reset their passwords before they expire.

The password reminder is run from a network location and ideally launched from a logon script. This way the script is often the first window a users sees as they log on to a machine. As the number of days to password expiration declines the notification will grow in size and change colors, increasing the helpfulness of the utility.

We determine the argument for the password reminder directly on our logon script before calling the password reminder. There are many ways to calculate this number so use whatever you like. Once this number is calculated simply add it to the command to launch the script with a hyphen (ex. PWreminder.hta -10).

Enjoy!

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Password Reminder</title>
<hta:application
  border="thin"
  borderstyle="normal"
  caption="Password Reminder"
  contextmenu="yes"
  maximizebutton="Yes"
  minimizebutton="no"
  navigable="yes"
  scroll="no"
  selection="yes"
  showintaskbar="yes"
  singleinstance="yes"
  sysmenu="Yes"
  WINDOWSTATE="normal"
  id="objPasswordHTA">

<script language="vbscript">
  Sub Window_onLoad
    strArg = 15

    arrCommands = Split(objPasswordHTA.commandLine, "-")
    If UBound(arrCommands) > 0 then
      strArg = arrCommands(Ubound(arrCommands))
    End If

    'setup the window size depending on how many days remain
    strArg = strArg * 1
    If strArg <= 5 then
      self.MoveTo 200,50
      window.resizeTo 1000,850

      Set wshShell = CreateObject("Wscript.Shell")
      wshShell.AppActivate "Password Reminder"
      wshShell.SendKeys "% x"  ' ALT+SPACE+X = windows maximize, must be enabled on hta
                               ' ALT+SPACE+N = windows minimize, must be enabled on hta
                               ' ALT+SPACE+R = windows restore
    ElseIf strArg <= 10 then
      self.MoveTo 200,50
      window.resizeTo 900,750
    Else
      self.MoveTo 200,50
      window.resizeTo 750, 575
    End If
  End Sub

</script>

</head>
<body>

<table cellspacing="0" cellpadding="0" width="100%" bgcolor=Silver>
  <tbody>
    <tr>
      <td valign="top" width="80%">
        <p style="PADDING-TOP: 8px; PADDING-LEFT: 8px; margin-top: 0px">
        <font face="Verdana" color="White" style="font-size: 11pt"><strong>Your Company Name</strong></font><br />
        <font face="Verdana" color="Black" size="5"><strong>Password Reset Reminder</strong></font>
        </p>
      </td>
      <td valign="bottom" width="20%">
        <!---<img src="Icon.png" style="vertical-align:bottom;"> -->
      </td>
    </tr>
  </tbody>
</table>

<span id=DataArea></span>


<script language="vbscript">
'Name:    Password Reminder
'Desc:    This script is launched from the Logon Script from a Domain Controller
'Author:  SysAtMN
'Date:    01/22/2014
'Usage:   "\\DC\...\PWReminder.hta" -[DaysUntilExpire]
'Updates: 1.00 - Original for Reddit
'         1.01 - Updated for /r/usefulscripts

'=================================================
'==============Global Variables===================
'=================================================
'WMI Stuff
Set wshNetwork    = CreateObject("WScript.Network")
Set wshShell      = CreateObject("Wscript.Shell")

'TableMsgs:
strDaysLeftMsg1 = "We have detected that your password will expire in"
strDaysLeftMsg2 = "day(s) or less."
strPWCriteriaMsg = "<BR>Password criteria:" & _
                   "<BR> - 6-8 characters" & _
                   "<BR> - At least one alpha and one numeric character" & _
                   "<BR> - Cannot be an old password" & _
                   "<BR> - Passwords ARE CaSe SeNsItIvE!!!" & _
                   "<BR> - Restricted: ~`!%^&*()_+-={}|[]&rdquo;\:;&rsquo;<>?,./{space}" & _
                   "<BR>"

'=================================================
'==============Main Processing====================
'=================================================
  strArg = 15
  arrCommands = Split(objPasswordHTA.commandLine, "-")
  If UBound(arrCommands) > 0 then
    strArg = arrCommands(Ubound(arrCommands))
    strArg = strArg * 1
  End If
  intDaysLeftonPW = strArg

  'Generate the HTML for the table
  strTableHTML = "<TABLE align=center width=75%>"

  If intDaysLeftonPW <= 5 then
    strTableHTML = strTableHTML & "<font size=5>"
    strTableHTML = strTableHTML & "<TR bgcolor=Red><TD>&nbsp;</TD></TR>"
    strTableHTML = strTableHTML & "<TR><TD><font size=5>" & strDaysLeftMsg1 & "<font color=Red><b> " & intDaysLeftonPW & _
                   "</b></font> " & strDaysLeftMsg2 & "</font>" & _
                   "<BR>" & _
                   "<BR>Please reset your password now to avoid getting locked out or expiring. " & _
                   "The only way to unlock an expired password is to contact Help Desk. " & _
                   "A typical expired password request takes 15-20 minutes.</TD></TR>"
    strTableHTML = strTableHTML & "<TR bgcolor=Red><TD>&nbsp;</TD></TR>"
    strTableHTML = strTableHTML & "<TR><TD>" & strPWCriteriaMsg & "</TD></TR>"
    strTableHTML = strTableHTML & _
                   "<TR><TD><BR><font color=red>To reset password:</font>" & _
                   "<BR>1. Press CTRL+ALT+DELETE" & _
                   "<BR>2. Select " & chr(34) & "Change a Password..." & chr(34) & _
                   "<BR>3. Complete the password reset wizard." & _
                   "<BR>" & _
                   "<BR>Caution: There are no grace logons. Expired passwords will not be allowed onto " & _
                   "the network.</TD></TR>"
    strTableHTML = strTableHTML & "</font>"
  ElseIf intDaysLeftonPW <= 10 then
    strTableHTML = strTableHTML & "<TR bgcolor=yellow><TD>&nbsp;</TD></TR>"
    sTRTableHTML = strTableHTML & _
                   "<TR><TD>" & strDaysLeftMsg1 & "<font color=Red><b> " & intDaysLeftonPW & _
                   "</b></font> " & strDaysLeftMsg2 & "</TD></TR>"
    strTableHTML = strTableHTML & "<TR bgcolor=Yellow><TD>&nbsp;</TD></TR>"
    strTableHTML = strTableHTML & "<TR><TD>" & strPWCriteriaMsg & "</TD></TR>"
    strTableHTML = strTableHTML & _
                   "<TR><TD><BR>To reset password:" & _
                   "<BR>1. Press CTRL+ALT+DELETE" & _
                   "<BR>2. Select " & chr(34) & "Change a Password..." & chr(34) & _
                   "<BR>3. Complete the password reset wizard." & _
                   "<BR>" & _
                   "<BR>Tip: Try to avoid resetting passwords on Friday and reset early in " & _
                   "the week. This will give you more opportunities to sign in and get used to the new password " & _
                   "so you do not forget over the weekend.</TD></TR>"
  Else
    strTableHTML = strTableHTML & "<TR bgcolor=Green><TD>&nbsp;</TD></TR>"
    strTableHTML = strTableHTML & _
                   "<TR><TD>" & strDaysLeftMsg1 & "<font color=Red><b> " & intDaysLeftonPW & _
                   "</b></font> " & strDaysLeftMsg2 & "</TD></TR>"
    strTableHTML = strTableHTML & "<TR bgcolor=Green><TD>&nbsp;</TD></TR>"
    strTableHTML = strTableHTML & "<TR><TD>" & strPWCriteriaMsg & "</TD></TR>"
    strTableHTML = strTableHTML & _
                   "<TR><TD><BR>Please press CTRL+ALT+DELETE and select Change a Password..." & _
                   "</TD></TR>"
  End if

  'Add the dynamic HTML to the table/HTA
  strTableHTML = strTableHTML & "</TABLE>"
  DataArea.InnerHTML = strTableHTML
</script>

</body>
</html>

r/usefulscripts • • Oct 04 '15

[BASH] Check currently installed Firefox versions on Windows hosts in your network

22 Upvotes

I use this script from a Linux host to check if the installed Firefox versions in the Windows hosts in our network are up-to-date. You must have a file named pclist in the same directory in which all Windows boxes in your network are listed (one per line). Requires the winexe program. The script show the installed firefox versions and writes them in the file firefox-hosts

Of course the script can be adapted to check for many other installed software. I release it here under the conditions of GPL v3

#!/bin/bash

echo -n "Type password for Adminstrator: "
read -s pw
echo ""
for n in $(cat pclist); do
  if ping -c 1 $n >/dev/null ; then

# 64 bit
  IsInst=$(winexe -U "Administrator%${pw}" //${n} 'reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mozilla\Mozilla Firefox ESR"'|grep Current)
  if [ "$IsInst" == "" ]; then
     IsInst=$(winexe -U "Administrator%${pw}" //${n} 'reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mozilla\Mozilla Firefox"'|grep Current)
  fi
# 32 bit
  if [ "$IsInst" == "" ]; then
    IsInst=$(winexe -U "Administrator%${pw}" //${n} 'reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox ESR"'|grep Current)
  fi
  if [ "$IsInst" == "" ]; then
     IsInst=$(winexe -U "Administrator%${pw}" //${n} 'reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox"'|grep Current)
  fi    
  # nothing
  if [ "$IsInst" == "" ]; then
    IsInst="Unknown or not installed"
    echo "Unknown or not installed: $n"
  fi

  echo "$n: $IsInst";
 echo "$n: $IsInst" >>firefox-hosts;
  else
  echo "$n ist nicht erreichbar"
  fi
done

r/usefulscripts • • May 26 '15

[PowerShell] Script that runs a health check of Exchange Databases. If an issue is detected, it builds a report and emails the file to your Exchange admins. It exits with a condition (0/1) so that we can integrate it with monitoring software (Hyperic, in our case).

Thumbnail
pastebin.com
22 Upvotes

r/usefulscripts • • May 19 '15

[POWERSHELL] Nearly silent install of Prey Anti-Theft.

Thumbnail
gist.github.com
22 Upvotes

r/usefulscripts • • Apr 17 '15

[PowerShell] Log all after-hours users that connect to a terminal server broker

22 Upvotes

There are 2 scripts: One that is run Tuesday-Saturday (first one below) and the other is run Sunday-Monday. All are run at 7am to retrieve the previous day's data and append to a CSV file. The store hours for the business I wrote it for were 7am-5pm, Mon to Fri.

Tuesday-Saturday

get-winevent -computername TS01 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(17);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp1.csv -notypeinformation
get-winevent -computername TS02 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(17);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp2.csv -notypeinformation
get-winevent -computername TS03 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(17);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp3.csv -notypeinformation
get-winevent -computername TS04 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(17);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp4.csv -notypeinformation
Remove-item -path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp1.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp2.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp3.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp4.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv | Sort-Object { $_."TimeCreated" -as [datetime] } | Export-Csv -Path C:\AfterHoursUsersScriptedLog\AfterHours\OutputLog.csv -NoTypeInformation -Append

Sunday-Monday

get-winevent -computername TS01 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(7);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp1.csv -notypeinformation
get-winevent -computername TS02 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(7);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp2.csv -notypeinformation
get-winevent -computername TS03 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(7);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp3.csv -notypeinformation
get-winevent -computername TS04 -FilterHashtable @{logname='Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational'; id=1301; StartTime=[DateTime]::Today.AddDays(-1).AddHours(7);EndTime=[DateTime]::Today.AddDays(0).AddHours(7);} | Select TimeCreated,@{Expression={$_.Message -replace '^[^\\]*\\',""};Name="User"} | Select TimeCreated,@{Expression={$_.User -replace '\s*RDP Client Version : [0-9]',""};Name="User"}| Export-Csv C:\AfterHoursUsersScriptedLog\Temp4.csv -notypeinformation
Remove-item -path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp1.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp2.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp3.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\temp4.csv | Export-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv -NoTypeInformation -Append
Import-Csv -Path C:\AfterHoursUsersScriptedLog\Unsorted\Unsorted.csv | Sort-Object { $_."TimeCreated" -as [datetime] } | Export-Csv -Path C:\AfterHoursUsersScriptedLog\AfterHours\OutputLog.csv -NoTypeInformation -Append

This script should work in any environment with an active log AND powershell 3.0 or higher (because of the CSV append function). Honestly it's the first thing I've ever written in PowerShell, so I'm sure that there's probably a better way to do it, but it works.


r/usefulscripts • • Feb 28 '14

[Batch] Inventory Logon Script

22 Upvotes

Logon Script to gather inventory info (Station Name, Serial Number, last user to logon and date) and places it into a CSV. The script will check for the serial number in the CSV and will update all other info. No need to schedule scans and let your users do the work for you! I suggest changing the CSV to a network drive location. You can also get insight as to which stations are frequently used if that's a concern.

@echo off

FOR /F "usebackq" %%i IN (`hostname`) DO SET STATION=%%i

FOR /F "tokens=2 delims==" %%A IN ('WMIC csproduct GET Name /VALUE ^| FIND /I "Name="') DO SET model=%%A

for /F "skip=2 tokens=2 delims=," %%A in ('wmic systemenclosure get serialnumber /FORMAT:csv') do (set "serial=%%A")

for /f "tokens=3 delims=\" %%i in ("%USERPROFILE%") do (set user=%%i) 2>&1

set mydate=%date:~4,2%/%date:~7,2%/%date:~10,4%   %time:~0,2%:%time:~3,2%:%time:~6,2%

find /v /i "%serial%" < "Serial Numbers".csv > 2.txt
copy 2.txt "Serial Numbers".csv >NUL & del 2.txt >NUL

echo %STATION%, %serial%, %model%, %mydate%, %user%  >> "Serial Numbers".csv

r/usefulscripts • • Jan 21 '14

[Powershell] Find Java 6 and 7 versions across AD

22 Upvotes

This is a rework of /u/jefffrey32's script from yesterday. Not meant to show him up, just meant to be faster and not make use of win32_product.

Some limitations:

Can currently only test for one type of Java installation, per major version, per platform.

Java 7u51 x86 and Java 6u36 x86 and Java 7u47 x64 and Java 6u47 x64 is ok.

Java 7u51 x86 and Java 7u40 x86 will not be reported accurately.

Some good things:

Took 7 minutes to run against 650 virtual and physical machines.

To do:

Add parameters to change AD filter to OU, server/workstation, single PC

Will add in e-mail capabilities later.

Get-Java.ps1

EDIT

All changes made and features added. New link: Get-Java.ps1

Usage: Get-Java.ps1 -f <AD filter> -e <If -e is present, email will be sent with the report as attachment>

Produces a colorized HTML report with the Java installations on the workstation


r/usefulscripts • • Jun 08 '23

Get top 10 users with successful radius authentications.

21 Upvotes

This will check windows event viewer for the top ten accounts that have successfully authenticated against radius in the last 5 hours and send an email with the results. This is helpful where I work because the students try to get staff credentials to get on the staff wifi and this helps identify accounts that have been compromised.

Invoke-Command -ComputerName radius.contoso.com -ScriptBlock {

$StartTime = (Get-Date).AddHours(-5)

$data = Get-WinEvent -FilterHashtable @{LogName='Security'; ID=6272; ProviderName='Microsoft-Windows-Security-Auditing'; StartTime=$StartTime} |

ForEach-Object { [pscustomobject] @{ UserName = ([System.Security.Principal.SecurityIdentifier]($_.Properties[0].Value)).Translate([System.Security.Principal.NTAccount]).Value } } |

Group-Object -Property UserName |

Select-Object -Property Name, Count |

Sort-Object -Property Count -Descending |

Select-Object -First 10

$data = $data | Out-String

Send-MailMessage -From '[email protected]' -To '[email protected]' -Subject 'Top ten radius auth success in last 5 hours' -Body $data -SmtpServer 'smtpserver.contoso.com'


r/usefulscripts • • Jul 21 '21

Script sharing: Get Teams' SharePoint site URL

Thumbnail self.office365
21 Upvotes

r/usefulscripts • • Feb 18 '21

[REQUEST] [Powershell] script to split CIDR address into smaller with differentiating masks

21 Upvotes

I have constantly a need to calculate new virtual networks and usually I check from our IPAM tool that I can use for example: "192.168.0.0/22" and I want to split that into subnets with /23 and 4x /25, or 2x /24, 2x/25 and 2x/26 or any other combination that fits in.

So far I have been using the Indented.Net.IP powershell module for splitting but it only splits with one masks and from there on I need to do some manual work


r/usefulscripts • • Jun 01 '19

[Request] A script to convert mkv files to mp4 while keeping the subtitle or choosing the subtitle tracks.

21 Upvotes

r/usefulscripts • • Dec 28 '18

[Powershell] Script to zip multiple folders / zip by date

21 Upvotes

Hi all I wrote this very simple script a while ago for my workflow. Basically all it does is scan through a list of directories you want to zip and zip them all, with some extra options.

As I do a lot of web scraping I need to archive the data and log files regularly so I wrote this in my free time to feed it to the Windows task scheduler and organise everything.

Here's the script and I hope you guys find it useful too!

ZipSchedule


r/usefulscripts • • Sep 25 '18

[PowerShell] Get-PasswordCombination

Thumbnail
sconstantinou.com
21 Upvotes

r/usefulscripts • • Dec 06 '17

[PowerShell]Advanced Auditing with PowerShell Desired State Configuration Manager

21 Upvotes

r/usefulscripts • • Oct 25 '17

Folder Creation and Restrictions

Thumbnail
pastebin.com
21 Upvotes

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 • • May 19 '16

[Powershell] Convert IE favorites GPP to Chrome managed bookmarks code

21 Upvotes

My org recently started deploying chrome out in parallel with IE11 and using the GPO adnin templates from Google to manage some things, including bookmarks. If you've not done this before you are likely unaware of how annoying setting up the formatting for a large list of bookmarks that contain folders can be.

After having our managed bookmarks string up and running for a few months I got tired of manually making changes to it and wrote a script to read our ie11 GPP favorites, get all of the relevant info, and create the archaic string the chrome setting needs.

You'll need to make a few edits to fill in items relevant to your env, these are noted in comments. I know my code isn't the cleanest or most efficient but this works and takes seconds to run in my environment. Hope it helps!

 

#Convert GPP based IE Favorites to Chrome 'Managed Bookmarks' format

 

#Change the GPO name in the next line to suit your environment

#

$gpo = get-gpo "Your IE Favorites GPO Name Goes Here"

 

[xml] $report = get-gporeport -guid $gpo.id -reporttype xml

$extensions = $report.gpo.user.extensiondata

$objOutput = @()

 

foreach($extension in $extensions)

{

             if($extension.name -eq "Shortcuts")

             {

                          $shortcuts = $extension.extension.shortcutsettings.shortcut

             }

}

 

foreach($shortcut in $shortcuts)

{

             $name = $shortcut.name

             $path = $shortcut.properties.shortcutpath

             $url = $shortcut.properties.targetpath

            

             # The path below will need to be modified to suit your environment. 

             # In mine, all managed favorites are configured into one folder so as not to mix with user added favorites

             # If your IE favorites are just lumped into the 'root' level, trim the folder name and trailing \\

             #

             $folder = $path -replace "%FavoritesDir%\\Folder Name\\",""

 

             $folder = $folder -replace $name,""

             $folder = $folder -replace "\\",""

 

             if($folder -eq "")

             {

                          $folder = "zzz"

             }

 

             $myobj = [pscustomobject]@{name=$name; url=$url; folder=$folder}

             $objoutput += $myobj

            

             $path = ""

             $url = ""

             $name = ""

             $folder = ""

}

 

$links = $objoutput | sort-object folder, name

 

$prefix = ""

$lastfold = ""

$suffix = ""

$table = @()

$index = 0

 

# Change the folder name below as needed.

#

$string = '[{"name": "Top Level FOlder Name Goes Here", "children": ['

 

foreach($link in $links)

{

             if($link.folder -eq "zzz")

             {

                          $link.folder = ""

             }

 

             $table += $link

             $index++

}

 

for ($i=0; $i -le $index-1; $i++)

{

             $temp = ""

             $prefix = ""

             $suffix = ""

             $j = $i+1

 

             $fold = $table[$i].folder

             $next = $table[$j].folder

             $name = $table[$i].name

             $url = $table[$i].url

            

             if($fold -eq $next)

             {

                          $suffix = ", "

             }

             Else

             {

                          $suffix = "]}"

             }

 

            

             if($lastfold -eq $fold)

             {

                          $prefix = ""

             }

             elseif($fold -eq "")

             {

                          $prefix = ", "

             }

             else

             {

                          if($i -eq 0)

                          {

                                      $prefix = '{"name": "' + $fold + '", "children": ['

                          }

                          else

                          {

                                      $prefix = ', {"name": "' + $fold + '", "children": ['

                          }

             }

 

             $lastfold = $fold

 

             $temp = $prefix

             $temp += "{"

             $temp += '"url": "' + $url + '", "name": "' + $name + '"}' + $suffix

             $string += $temp

}

 

$string += "]"

 

# Change the output path below.  This output file will contain a giant string, copy that entire string into the 'Managed Bookmarks' GPO setting's field.

#

$string | out-file -filepath "\\myserver\myshare\myfile.txt"


r/usefulscripts • • May 07 '16

Batch script that re-installs Edge browser

21 Upvotes

Something I made a while back, figured I would share on here. This is just a batch script to assist with re-installing the Edge browser on Windows 10 if its broken or plagued with hijacks. Hope this helps someone. More info on the page: http://fatt.xyz/programs/reinstall-microsoft-edge/


r/usefulscripts • • Apr 23 '16

Create admin account and hide from login screen

21 Upvotes

Hi guys,

I'd love a script that creates an admin account on a workgroup based computer and hides the account from the login screen. Possible?