Search This Blog

Sunday, December 11, 2022

Windows: Clearing cache, temp files and logs

As a follow up to my previous maintenance post here are a few more advice that will help you clear out some cache primarily, it's not a way to clear much space. You might save up to a gigabyte depending on how long your computer has run without maintenance. Also check out my other post about maintenance.

The script goes as following and can be run by a normal user, it does not force the computer to delete anything that requires admin permissions in other words. So if an admin runs the script it will be even more powerful.

It will clear up logs and temp files, and then also clear the recycling bin. After which it will also clear up some cache.

$ErrorActionPreference = "SilentlyContinue"

Write-Output "Clearing DISM log..."
Get-ChildItem -Path C:\Windows\Logs\DISM | Remove-Item -Recurse

Write-Output "Clearing CBS log..."
Get-Childitem -Path C:\Windows\Logs\CBS | Remove-Item -Recurse

Write-Output "Clearing C:\Windows\Temp"
Get-ChildItem -Path C:\Windows\Temp | Remove-Item -Recurse

Write-Output "Clearing C:\...\AppData\Local\Temp"
$User = $env:username
Get-ChildItem -Path C:\Users\$User\AppData\Local\Temp | Remove-Item -Recurse

Write-Output "Clearing recycle bin"
Clear-RecycleBin -Force

Write-Output "Clearing DNS cache"
Clear-DnsClientCache

Write-Output "Resetting Microsoft Store"
wsreset
Start-Sleep -Milliseconds 700
Stop-Process -name "WinStore.App"

At the end of the script, Microsoft Store will pop up, I've included a line in the script that closes the app again, to leave the user with a more hands off execution.

You can also delete these items manually. For a manual cleanup you can also go to C:\Windows\LiveKernelReports\ and look for big .dmp files. These are dump files and can be investigated in case of a system crash for example. If you have no need to inspect these files you can delete them. I would avoid any folders or other files personally.

Enjoy!

Sunday, December 4, 2022

Registry: Show detailed Windows messages

Whenever you turn your computer on or off you can see messages such as "updating, please don't turn your computer off" at the boot screen.

Sometimes your computer can get stuck here or it takes a long time and you might wonder what is happening. Using the registry you can enable more detailed status messages at the boot up or restart.

Create a .reg-file with the following information:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]

“verbosestatus”=dword:00000001

Now you can see what the computer is doing when it previously only would indicate that it was working.

Sunday, November 20, 2022

Review: Xiaomi Redmi 10C

This review covers my early experiences with the Xiaomi smartphone called Redmi 10C. It's the first MIUI based phone that I use, I've used EMUI a few years ago on my Huawei and there are some similarities such as the focus on the battery efficiency and storage.

While the phone offers a lot of battery efficiency tools, the battery life is not as good as my previous Huawei Y6 Pro II. Nor as good as my Motorola G9 Power. It still manages to perform well enough for my taste.

The customization is great, the phone comes with unique settings with the MIUI (Android based OS developed by Xiaomi) that allows you to use old school settings as well. One example is gestures and the available apps. I should add that I activated the developer mode right away.

To activate developer mode on your Xiaomi Redmi 10C you need to go to settings and go to "about phone", then press MIUI version 10 times.
Another topic regarding technology is privacy and surveillance. Who is listening to you? Probably always a nation state actor, company or organization. I don't think the every day consumer can opt out easily, we simply choose who listens in when we pick phone brand. 

When you pick a model, do a search online to see if there are any recent scandals regarding privacy connected to the manufacturer. Also do a clean reinstall before you start using the phone. It is extra important if you buy your phone on the second hand market.

That being said, get some nice accessories from Amazon for example. Like a screen protector or a wallet case.

Wednesday, November 16, 2022

Windows: Maintenance and debloating

Keeping your computer clean on the outside is a good thing, equally important is cleaning up the computer internally as well using software. You might simply not want to go through the steps necessary to reinstall the entire computer so here I list some good commands that you can run in PowerShell as an admin. You can also check my other blog post for some tips and tricks on what you can delete to save space.
 

Commands to run in PowerShell

Run system file checker, this sometimes finds and fixes corrupt system files:
SFC /Scannow

Run the tool for Deployment Image Servicing and Management. Basically these are three levels, the last does a bit of repairing. Run SFC before you run any of the DISM commands:
Dism /online /cleanup-image /checkhealth

Dism /online /cleanup-image /scanhealth

Dism /online /cleanup-image /restorehealth

This command can help you recalibrate your system clock. I found it helpful when syncing the clock on computers with a bad battery when internet access have been stopped either by a VPN or because the web browser notices an all too big of a time change. 
Simply run this command to fix the clock:

W32tm /resync /force

In order to fix basic network issues you can run the following commands in this order, the second will disconnect your from the internet usually.

Ipconfig /flushdns

Ipconfig /release

Ipconfig /renew

When changes have been made to the group policy you can try this command to force an update. Pay attention to what settings that override which as well so that you aren't waiting for an update that might not show up.

Gpupdate /force

Running this command let's you check the health of your harddisk.
Chkdsk /f

This command will help you to scan your memory for issues (this command is a program that you can call upon):
mdsched.exe

Some programs to run

Apart from these commands that you can run as admin in the PowerShell window, there are a few built-in programs that you find by searching in your start menu. These are just a good habit to run once in a while to do some cleaning:

Disk cleanup
Disk defragmentation
Storage settings (it will list items you can delete as well)
Full Windows virus scan
 

Debloating script

I've also put together a script that runs through basic pre-installed software and removes it. Sometimes I've tried removing every AppxPackage that I could find, but I found things to get a bit buggy. So this script contains apps that you can live without, all in the name of more resources to what you think is important.

# Run as admin

# Silence errors
$ErrorActionPreference = 'SilentlyContinue';

# App list
$applist = "*3dbuilder*","*windowsalarms*","*windowscommunicationsapps*","*windowscamera*",
"*officehub*","*skypeapp*","*getstarted*","*zunemusic*","*windowsmaps*","*solitairecollection*",
"*bingfinance*","*zunevideo*","*bingnews*","*onenote*","*people*","*bingsports*","*soundrecorder*",
"*bingweather*","*xboxapp*","*xbox*","*Microsoft.MixedReality.Portal*","*GetHelp*","*Microsoft.Messaging*",
"*sketch*","*sticky*","*phone*","*sticky*","*photos*","*calc*","*gethelp*","*camera*"

foreach ($app in $applist) {Get-AppxPackage $app | Remove-AppxPackage}
 
The script works by creating a list where every item is a search word related to apps that can be installed in Windows. If it doesn't find the app it will continue to the next object. When it finds an object it passes it through the pipeline to the removal cmdlet.
 
 

Monday, November 14, 2022

PowerShell: Password generating function

Passwords - the basics

Having a long password is usually better than just a complex short password. When attackers attempt to crack your password they will try different techniques such as brute forcing. That is when they have a dictionary of common passwords that they try to use to get into your account. Sometimes they will try one sequence of characters after another.

AAAA... AAAB.... ABCC....ABCD... and eventually the account goes "pop".

Just like a padlock there is a fixed amount of combinations.

A padlock has 0-9 per wheel usually. Which is ten characters per wheel. You can calculate the total amount of combinations like Characters per wheel to the power of the number of wheels.

Four wheels with 10 numbers (0 through 9) is 10 x 10 x 10 x 10. Which also is written as 10^4. When scripting in PowerShell you write [math]::Pow(10,4). Here is the answer, 10000 combinations.

Let's say that the brute forcing computer can guess 1000 passwords per second. That leaves your account safe for 10 seconds if you have a 4 character long password.

By increasing the variation of characters (increasing the numbers per wheel on your padlock) and increasing the amount of characters in your password (increasing the amount of wheels on your padlock) your password will take longer time to crack. 

However, store it well and preferably don't store it at all if possible. It doesn't matter if your password is 20 characters long and has a good complexity if it is stored in plain text in a file called "passwords.txt".

Those who store your password often store it "hashed" and "salted", to add extra complexity. Hashing uses a hashing function to scramble the password and salting adds random characters. If the passwords are leaked they will not be in plain text. Therefore some malicious actors will store pre-hashed password lists to match with the leaked hashed list of passwords to then compare the two.

Generating a password using PowerShell

I found myself having to update an old password and I didn't want to come up with a lot of numbers, letters and special characters myself. So I scripted a function that helps me to bring out a password with the requirements of being long and complex. (One difference between a function and a cmdlet is that the latter is compiled C# code.)

First I defined which characters I wanted to use in a string. Each character in a string can be called upon with an index number. The real engine behind this function is "Get-Random" which then returns a number no higher than the length of the string. This way you can get a random character.

The challenge was then stringing together a output string, the password, with the right amount of characters.

Finally I added a parameter that puts the password in my clipboard, one parameter that let's me pick the password length and also an alias for the function.

Here is the code:
 
function New-Password {

<# Parameters with default values #>
[alias("npwd")]
[cmdletbinding()]
    param
    (
    [Parameter()]
    [alias("Length")]
    [int]$DesiredPasswordLength = 15,
    [alias("c", "copy")]
    [switch]$CopyPassword = $False
    )

<# Available characters #>
[string]$AvailableCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!?@#";

<# Random letter from available characters #>
function Get-RandomLetter {
$AvailableCharacters[(Get-Random ($AvailableCharacters.Length))]
}

<# Build string #>
[string]$Password = ""
Do {$Password += Get-RandomLetter;} While ($Password.Length -lt $DesiredPasswordLength)
$PasswordLength = $Password.Length

<# Output #>
[float]$NumberOfCombinations = [math]::Pow($AvailableCharacters.Length,$Password.Length)
Write-Output "Your generated password is $Password and is $PasswordLength characters long. Complexity: $NumberOfCombinations combinations."
if ($CopyPassword) {$Password | Set-Clipboard} else {Break}

}

A few last thoughts


Remember that the code works with passwords in clear text, be mindful of how you implement it. Its purpose is to help you generate randomized strings of defined length.

Test your password security at sites like Passwordmonster or Security.org. I tested a random password with a length of 15 characters and it reached 100+ million years. How passwords will change in the face of quantum computing is for the future to tell. Perhaps password cracking will be faster or perhaps encryption will change fundamentally. Who knows?

Tuesday, November 8, 2022

PowerShell: Send email with attachment

It was when I was working on a hobby project that I did some research on how to send emails using PowerShell.

It wasn't the first time I managed to pull it off but I had forgotten how to script it, so I did some research.

Two parts at least seems to be needed, the credentials for the sender and the necessary variables for the email itself, such as header and content.

In this post I will discuss the credentials first, then the sending part. All this code was tested using PowerShell ISE. Microsoft writes that the cmdlet Send-Mailmessage is a bit outdated, so be wary.

Credentials

Rule number one in scripting: Don't store passwords in plain text, rule number two, don't store it in files that you send to others. Let's break these rules a bit.

We don't need to discuss why storing passwords in plain text is a bad idea, but this is how you can do it.
 
 
$u is your user name, in this case your full legit email address and $p is the plain text password.
Together the make up $c, which is a variable storing your credentials. Make sure to not enclose $p in quotation marks as this causes the code to break.

If you want to store your credentials in another way, you could write $c = Get-Credential; $c but it serves a different purpose than the automation and no sharing idea I had with my project.

Sending the email

This code shows your a cmdlet that takes related parameters (and a lot of them).
 
Send-MailMessage -To $receiver -From $u -Subject “Autoreply” -Body “What the main part of the mail contains.” -Attachments "c:\temp\log.txt" -Credential $c -SmtpServer “outlook.office365.com” -Port 587 -UseSsl

You need to find the right port and smtp server for your email provider. In this example I used Outlook. I couldn't send the mail without the "-usessl". Instead of a storing credentials in a variable, you can supply the "-credential" parameter with (Get-Credential) instead. The parenthesis helps prioritize the credentials.
 

Conclusion

Using the above code my script managed to send a file to the receiving email address.
However the script does not let you spoof the sender address provided in the send-mailmessage cmdlet. It has to be the same as the credential. I did not experience any trouble receiving the mail or attachments.


Friday, November 4, 2022

Registry: Modifying the context menu

Whenever you are right-clicking in your explorer or on your desktop you bring out what is called the context menu.

After doing some research and testing I found ways to add programs of my liking to this menu by editing the registry.

In this example, I used pestudio, a program that you can investigate .exe-files with. You can download it from this page for free. I wanted to add this program to the menu in order to open other files with it.

Step one is to navigate to HKEY_CLASSES_ROOT\*\shell\ 

Then you create a subkey called whatever you want the menu to display, such as "Open with PE". Within this key you then create another key called command, and this is something you do regardless of what program you are going to add.

Step two is to edit the default file located in "command". Set the value to the file path within quotation marks, followed by space, followed by %1 in quotation marks. For example:

"C:\Program Files (x86)\pestudio\pestudio.exe" "%1"

Step three is to add an icon. Enter the parent key this time, by clicking on "Open with PE". Within this key you create a string named Icon with the file path as data. Make sure to put a comma and a 0 at the end to retrieve the built in icon:

Now you should be able to see the icon, the menu name and the program you linked should be able to open the files that you right click.

If you want to turn this into a .reg-file you can use this code:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\Open with PE\command]
"(Default)"="\"C:\Program Files (x86)\pestudio\pestudio.exe\" \"%1\""

[HKEY_CLASSES_ROOT\*\shell\Open with PE]

"Icon"="C:\Program Files (x86)\pestudio\pestudio.exe,0"


Thursday, November 3, 2022

Registry: Customize Windows 10

The registry in Windows keeps track of many program specific settings that you make changes to. In some way it is where the state of many things gets documented

You can change settings either through the regular Windows 10 GUI, or in the registry. Always be careful when editing within the registry itself.

To change settings through the registry you can either use "regedit.exe", use .reg-files or by using PowerShell. PowerShell gives you the ability to browse and edit like any other file structure.
 

Registry Editor (regedit.exe)

Regedit.exe takes you to a registry browser, that shows you what looks like folders and files. The top level of the registry contain HKEY_CURRENT_USER for example which is a "hive". The structure with folders under the hives are keys and subkeys respectively. The things looking like files are the values that have names and types.
 


Using .reg-files

The .reg-files use a simple syntax, they will add the "folders" that doesn't already exist and then they add the key with the desired value.
 
Create a notepad .txt file, enter code and rename it to .reg afterwards. You get a clickable and shareable file. 
 

 
Below is an example on how to disable Bing search in your Windows 10 start menu. Syntax looks like this:
 
Windows Registry Editor Version 5.00
 
[HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Windows\Explorer]
"DisableSearchBoxSuggestions"=dword:00000001 
 
The first part is what version of regedit your OS runs, then a necessary blank line, followed by an entry (hive, key, subkeys). It is possible to stack multiple edits in one file.

Another tweak I use to take me to the login page right away is the following:

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Personalization]
"NoLockScreen"=dword:00000001 
 
To show seconds in the clock on Windows 10 I use this tweak:
 
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
"ShowSecondsInSystemClock"=dword:00000001

Editing the registry with PowerShell

Using PowerShell to edit the registry is shown in this blog post I made earlier. The essential cmdlet that you work with is New-ItemProperty  
 
Followed by various parameters:
-path, where in the registry
-name the key/folder
-PropertyType whether it is a string or dword for example
-Value if there is text or perhaps a 1

Last but not least, in order for most things to take effect, you need to restart your computer.