Category Archives: Powershell

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

Welcome everyone!

Today i’m going to share my top 10 (beginner-friendly) Powershell commands that i use quite frequently.

I hope that you will find these commands useful.

 1. Connect to a remote computer:

Enter-PSSession -ComputerName "Computer1"

 

2. Get events from EventViewer:

Get-WinEvent -computername "Computer1" -FilterHashTable @{ LogName = "System"; StartTime = "2020-02-12"}

 

3. Get OS BuildNumber:

Get-WmiObject -Class Win32_OperatingSystem -ComputerName "Computer1" | Select BuildNumber

 

4. Get OS ReleaseID:

(Get-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion’).ReleaseId

 

5. Get values from the registry:

Get-ChildItem -Path 'HKLM:\PATH\TO\KEY'

 

6. Set values in the registry:

New-ItemProperty -Path "Registry::\HKEY_CURRENT_USER\PATH\TO\KEY\" -Name 'Flags' -PropertyType DWORD -Value "1337"

 

7. Show the latest installed updates (KB’s):

(Get-Hotfix | sort installedon)

 

8. Get serialnumber (CimInstance):

(Get-CimInstance -ClassName Win32_BIOS).Serialnumber

 

9. Get Bios version (CimInstance):

(Get-CimInstance -ClassName Win32_BIOS).SMBIOSBIOSVersion

 

10. Get computer model (CimInstance):

(Get-WmiObject Win32_Computersystem).Model

 

Comment down below if you have any questions! 🙂

Office Addin Manager

Hello!

Once again i’ve created another Powershell (XAML) application.

This time i’m releasing Office Addin Manager, which allows you to manage Office addins on your own or a remote computer. As always, changing registry settings on a remote computer requires you to have administrative permissions on that computer.

With this tool you can in a quick manner change the load behavior of Office addins no matter the Office application, no more messing around in regedit or manually open each Office application.

Office Addin Manager uses a number of different values to configure each addin to run with a specific behavior. Read more about load behavior values on docs.microsoft.com

 

Download

If you have any questions feel free to ask them below, i’m more than happy to answer them 🙂

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!

 

[PS] How to remove Windows Hello for Business PIN

Hello internet!

Short story:

I currently work in an organization where we use Windows Hello for Business as an “two-factor” authentication method. In some cases i need to completely remove the PIN-code from the computer (without having to re-install Windows 10). This is the only way i know of that really removes the PIN from the computer. Feel free to comment down below if you know another way.

 

How to remove Windows Hello for Business PIN from a computer:

  1. The first thing we need to do is specifying the path to the NGC-folder (which holds the WHFB-keys)
  2. Next, taking ownership of the folder (make sure that you’re running Powershell as an administrator)
  3. And lastly, remove the folder and all of it’s content.
  4. Now you need to reboot the computer, and the PIN should now be completely removed.
  5. If you’re distributing WHFB using GPO, don’t forget to remove those aswell.

 

Powershell:


$path = "C:\Windows\ServiceProfiles\LocalService\AppData\Local\Microsoft\Ngc"
takeown /f $path /r /D y
Remove-Item -Force -Recurse -Path "$path\*" -erroraction 'silentlycontinue'

 

 

If you don’t want to use Powershell, you can follow this great guide on how to take full ownership of a folder, after that is done you just have to remove the following folder:

C:\Windows\ServiceProfiles\LocalService\AppData\Local\Microsoft\Ngc

 

 

[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