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 • • Dec 02 '18

[Powershell] check for a list of windows KB# against a list of machines.

25 Upvotes

Its for quickly auditing whether or not a set of machines has a certain set of patches installed. In case you are into doing that kind of thing through powershell.

https://github.com/geekonamotorcycle/Audit-WindowsPatches/blob/master/Audit-WindowsPatches.ps1

any suggestions for improvement that would keep it light weight and on task are welcomed. I dont think I am catching connection errors correctly. Any suggestions there?


r/usefulscripts • • Oct 06 '17

Find Office 365 users that are still using Outlook 2007 in your customers' tenants [PowerShell]

25 Upvotes

With Outlook 2007 not supporting connections to Office 365 by the end of the month, it might be handy to check whether you'll have any affected users in your customer tenants - as well as your own.

Follow this quick guide to get Office 365 users that are still running Outlook 2007 in all customer tenants


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


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 • • Apr 25 '17

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

25 Upvotes

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

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

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


r/usefulscripts • • Dec 01 '16

[BASH] Ubuntu server setup script

Thumbnail
github.com
25 Upvotes

r/usefulscripts • • Aug 26 '16

[BASH]Updated IPTables Script to block by Country

Thumbnail
github.com
25 Upvotes

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 • • Mar 23 '15

Create Shortcuts on User Desktops with Powershell

Thumbnail
adminarsenal.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 • • 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