Tag Archives: powershell

AD Extractor – Extract members of AD group with a simple tool!

Morning everyone!

With the basic code from Vikas Sukhija i created this GUI around Vikas code. Mainly to help more people utilize his code (that aren’t comfortable around code), but also so that i could reduce the amount of clicks.

The full source is available here if you don’t want to download the .exe

 

What does AD Extractor do?

AD Extractor is using ADSI to search the AD. You can extract members from both security and distribution groups. There is also no problem with extracting computers and/or users from a group. I added a simple GUI so that you could export a complete list with just 2 clicks. You obviously need the appropriate permissions to run this program. As for now you can only export a list to .txt, but in the future i will add .csv support (if there is a demand for that)

 

Download

 

If you have any questions or feedback you are more than welcome to post that in the comments below.

Have a great day! ūüôā

How to Reset the Color of the Command Prompt in Windows 10

Hi everyone!

Recently bumped into an issue regarding the classic command prompt (CMD).

 

Problem:

CMD colors are changed so that you are unable to see the text, and cannot change back (for whatever reason)

 

Solution:

Change the REG_DWORD DefaultColor to “7

HKEY_CURRENT_USER\Software\Microsoft\Command Processor
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Command Processor' -Name DefaultColor -Value "7"

 

Voila!

Procmon saves the day!

 

[Azure] Automation Runbook – Retrieve total cost of resourcegroup or subscription

Hello geeks!

 

What this script/runbook achieves:

This script retrieves all resources in a resourcegroup, sums up the values of each resource, and emails the total cost via gmail SMTP.

What i get in the mail once a day:

The script:

(I recommend that you download the script, instead of copy/paste)

Download script


<# .SYNOPSIS
Displaying the cost of an Azure resourcegroup or subscription and email the total cost
via gmail smtp.

.DESCRIPTION
This script captures all resources in a resourcegroup
and calculates the cost based on the last x days.
After the cost is retrieved an email will be sent.
Don't forget to configure the SMTP settings in the bottom of the script.
If you're using Gmail's 2-factor authentication you must create an app-specific password,
more info about this here https://support.google.com/mail/answer/185833?hl=en 

If you want to calculate the cost of all resources in a subscription
simply remove "-ResourceGroup $rsgrp" from line $SubConsumptionUsage. 

Required modules: 
AzureRM.Automation 
AzureRM.Consumption 
AzureRM.Profile 
AzureRM.Resources 
AzureRM.Storage 
AzureRM.Compute 

This script couldn't be possible if i haven't read Lawrence Wilsons article
on octopus.com 
https://octopus.com/blog/saving-cloud-dollars 

A big thanks to him!

.LINK 
More information about this script and more can be found on my website
http://paegelow.se
.NOTES
Version: 1.0 
Author: Robert Paegelow 
Creation Date: 2019-02-13 
Contact: robert.paegelow@hotmail.com #>

###################################
## Connect to Azure via your RunAsAccount
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint | Out-Null
###################################

###############################
###### S E T T I N G S ######
## Paste your subscription ID here:
$SubscriptionId = "subscription ID"
###############################

###################################
# If you set this to 30, the script will only show the cost of the last 30 days 
$days = "30"
###################################

###################################
<# Resourcegroup is not mandatory
if you want to show the cost of ALL resources,
simply remove "-ResourceGroup $rsgrp" from line $SubConsumptionUsage #>
$rsgrp = "group1"
###################################

$now = get-Date
$startDate = $($now.Date.AddDays(-$days))
$endDate = $($now.Date)

$SubConsumptionUsage = Get-AzureRmConsumptionUsageDetail -StartDate $startDate -EndDate $endDate -ResourceGroup $rsgrp
$SubIdPrefix = "/subscriptions/" + $SubscriptionId
$RgIdPrefix = $SubIdPrefix + "/resourceGroups/"
$resourceGroupName = @()
$resourceGroups = @()

foreach ($line in $SubConsumptionUsage) {
if ($line.InstanceId -ne $null ) {
$thisRgName = $($line.InstanceId.ToLower()).Replace($RgIdPrefix.ToLower(),"")
$toAdd = $thisRgName.Split("/")[0]
$toAdd = $toAdd.ToString()
$toAdd = $toAdd.ToLower()
$toAdd = $toAdd.Trim()

if ($resourceGroups.Name -notcontains $toAdd) {
$resourceGroupName = [PSCustomObject]@{
Name = $toAdd
}
$resourceGroups += $resourceGroupName
}
}
}

$currentResourceGroups = Get-AzureRmResourceGroup
$rgIndexId = 0

foreach ($rg in $resourceGroups) {
#$thisRg = $null
$RgIdPrefix = $SubIdPrefix + "/resourceGroups/" + $rg.Name
$ThisRgCost = $null
$SubConsumptionUsage | ? { if ( $_.InstanceId -ne $null) { $($_.InstanceId.ToLower()).StartsWith($RgIdPrefix.ToLower()) } } | ForEach-Object { $ThisRgCost += $_.PretaxCost }
$toaddCost = [math]::Round($ThisRgCost,2)
$resourceGroups[$rgIndexId] | Add-Member -MemberType NoteProperty -Name "Cost" -Value $toaddCost
if ($currentResourceGroups.ResourceGroupName -contains $rg.Name) {
$addingResourceGroup = Get-AzureRmResourceGroup -Name $($rg.Name)
$resourceGroups[$rgIndexId] | Add-Member -MemberType NoteProperty -Name "NotifyCostLimit" -Value $($addingResourceGroup.tags.NotifyCostLimit)
}
$rgIndexId ++
}
$ActualCost = $resourcegroups.Cost

###########################
### SMTP Settings
$email = "email"
$pass = "password"
$smtpServer = "smtp.gmail.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $true
$msg.From = "$email"
$msg.To.Add("$email")
$msg.BodyEncoding = [system.Text.Encoding]::Unicode
$msg.SubjectEncoding = [system.Text.Encoding]::Unicode
$msg.IsBodyHTML = $true
$msg.Subject = "[Azure] Cost Report"
$msg.Body = "Azure cost last 30 days: $ActualCost USD"
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$email", "$pass");
$smtp.Send($msg)

 

Information about the Runbook

In my last post, i shared with you my Azure-hosted Pihole DNS-server.

Since Azure doesn’t cost monopoly money, i wanted to get a daily mail of the total cost of all my pihole-resources in a specific resourcegroup. That’s why this script was made.

This script retrieves all resources in a resourcegroup, sums up the values of each resource, and simply emails the total cost via gmail SMTP.

This script authenticates with your Azure RunAsAccount, if you want to run this script on your PC instead of in an Azure Automation Runbook, simply replace the authentication part of the script (line 41-42) with something like this:


if ([string]::IsNullOrEmpty($(Get-AzureRmContext).Account)) {Login-AzureRmAccount}

Required modules:

  • AzureRM.Automation
  • AzureRM.Consumption
  • AzureRM.Profile
  • AzureRM.Resources
  • AzureRM.Storage
  • AzureRM.Compute

Guide on how to create an azure runbook:

https://docs.microsoft.com/en-us/azure/automation/automation-quickstart-create-runbook

Just want to point out that i am not a professional in any way, and there could be plenty of improvements made to this script. So if you have any ideas of what could be improved, don’t hesitate to comment that down below.

 

[PS] Get Microsoft Office 2016 Version

This time we’re retrieving Microsoft Office 2016 Version with¬†Get-ItemProperty

This is the fastest way i know to retrieve this value. You could also use Get-WmiObject win32_product but it will probably not be as fast.


$Version = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration"
$Version.ClientVersionToReport

[PS] Add Java exceptions to a remote computer

Hi! Another simple script i use quite often is the “Java-exception-adder”. The script adds URL exceptions to a remote computers Java exception list. (exception.sites) You obviously need to be local admin at the remote computer.

(Don’t get confused, this is with Swedish language)
  1. Run the script
  2. Enter the computername that you want to add the Java exception to (exception.sites)
  3. Enter the URL (with http:// or https:// before) that you want to add
  4. Press enter

 


$pc = Read-Host "Enter a computername "
$exception = Read-Host "Input URL that you want to add to the JAVA exception list "

Invoke-Command -ComputerName $pc -ScriptBlock {
Set-Content -Value "deployment.system.config=file\:\\C\:\\Windows\\Sun\\Java\\Deployment\\deployment.properties" -Path C:\Windows\Sun\Java\Deployment\deployment.config
Set-Content -Value "deployment.system.config.mandatory=True" -Path C:\Windows\Sun\Java\Deployment\deployment.config
Set-Content -Value "deployment.user.security.exception.sites=C\:\\Windows\\Sun\\Java\\Deployment\\exception.sites" -Path C:\Windows\Sun\Java\Deployment\deployment.properties
Add-Content -Value "$Using:exception" -Path C:\Windows\Sun\Java\Deployment\exception.sites
}

 

[PS] Add/Remove Sticky Notes

Hello world!

This script might be useful if access to Microsoft Store is blocked for all users, then the only way to retrieve apps that have been removed or is missing, is to add them using Powershell. This is specifically for Sticky Notes.

In order to install Sticky Notes, you must first know the full name of the package, and to retrieve that, you have to have Sticky Notes installed. It’s a catch-22, i know. But you could probably run the retrieve-command at another computer to get your PackageFullName. Anyway, here’s how it’s done…



 

Install Sticky Notes: (new method)


$PackageFullName = (Get-AppxPackage | Where-Object {$_.PackageFullName -Like "*MicrosoftStickyNotes*"}).PackageFullName
Add-AppxPackage -register "C:\Program Files\WindowsApps\$PackageFullName\appxmanifest.xml" -DisableDevelopmentMode

 

Remove Sticky Notes:

Get-AppxPackage *stickynotes* | Remove-AppxPackage

 

Must be run as currently signed in user, not with an elevated admin account.

Verified to work on Windows 10 1703, 1709 & 1803 – comment down below if you get any errors.

 

Check out my new article

[PS] Top Ten Simple Powershell commands every IT-admin should know

[PS] Retrieve default PDF-reader registry value

Until now, i only knew one way of retrieving the default app-association for a specific file extension (.pdf, .xlsx, .docx) and that is by using DISM and exporting an .xml file. But this can only be done with an elevated prompt (as far as i know).

This is where my problem started, if you elevate an cmd prompt, you will only export the standard app-associations for that particular user (admin user). I wanted to display the standard app-associations for the user on that specific computer.

Long story short, i found the registry value where you can see this, it’s probably not a good idea to change this value here, for that you will have to use DISM i think, correct me if i’m wrong. If you want to retrieve the standard app-association for another file extension, just change .pdf to whatever you want to retrieve.

Registry path:


HKEY_USERS\YOUR-SID-HERE\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.pdf\UserChoice

And what i uses this for is just running it on remote computers through a PS-session with this script:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$sid = ([System.DirectoryServices.AccountManagement.UserPrincipal]::Current).SID.Value
$path = "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.html\UserChoice"
(Get-ItemProperty -Path $path -Name ProgId).ProgId

 

 

 

 

[PS] Simple Powershell script to ping multiple computers

Hello world!

Simple script i wrote just to ping (test-connection to) multiple servers/computers. It uses a textfile as an input. Make sure to put one server/computer on each line in the textfile. Could probably be written 10 times cleaner, but it works.

Edit:

Modified the first script so that you could add the servers/computers directly into the script.



Computers/servers is located in a txt-file:

$path = "C:\computernames.txt"
do{
$pclist = Get-Content $path
foreach ($pc in $pclist) {
if (test-Connection -ComputerName $pc -Count 2 -Quiet ) {
Write-Host $pc is online -ForegroundColor Green
} else {Write-Host $pc is offline -ForegroundColor Red}
}
} until($forever)

 

Computers/servers are located in the script:


$pclist = "computer1", "computer2", "computer3", "computer4", "computer5"
do{
foreach ($pc in $pclist) {
if (test-Connection -ComputerName $pc -Count 2 -Quiet ) {
Write-Host $pc is online -ForegroundColor Green
} else {Write-Host $pc is offline -ForegroundColor Red}
}
} until($forever)

 

If you want more beginner-friendly commands, check out my new article

[PS] Top Ten Simple Powershell commands every IT-admin should know

 

6 1