Search This Blog

Sunday, May 19, 2024

PowerShell: Check Admin Status, Self-replication and AutoRun

How to check if the script is run as administrator

It can be helpful to stop a script if it is not being run as an administrator, as some actions require administrative rights. You can use the check to trigger an informative window that the user instead should run the script as an admin.

# Check admin status #

$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator);

If ($isAdmin) {"Do the main part of the script"} else {"Inform the user that admin rights are missing"}

Simple self-replication

Sometimes we want a script to be able to replicate itself, for example, you might want the script to backup itself to a certain destination.

This code offers a simple way to replicate the script from itself.

First we define the path, $p, to be the script path itself.

Secondly, we test the path and if successful we extract the entire content from the script and send it to a destination that we also have specified. You can also include a simple error message.

This piece of code is formatted as a ternary operator, instead of a classic if-statement. The function is the same.

$p = "C:\Temp\testcopy.ps1"; 

(Test-Path $p) ? {Get-Content $p | Set-Content "C:\Temp\testcopy.txt"} : {"operation failed"};

It is possible to write the code to something else, you can for example append it to another file, or replace the content entirely.

AutoRun

AutoRun used to be a functionality, especially in older versions of Windows, where there was a file called AutoRun.inf located in the root folder of a CD or USB. This would tell the computer which file on the storage media to automatically start upon detection (when you plug in the USB / place the CD in the reader).

It is simple to make, create a text file with the following content:

[AutoRun]
open=your_program.exe
icon=your_program.ico

This is more like a legacy code, but you can still enable it. Here are two ways.

Reg file:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
"NoDriveTypeAutoRun"=dword:000000FF

PowerShell:
# Enable AutoRun
$path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer'
Set-ItemProperty $path -Name NoDriveTypeAutoRun -Type DWord -Value 0xFF

# 0x0 instead of 0xFF would let you disable it instead.

Hardware: Optimize SSD & HDD

As an owner of multiple computers it also comes with many disks to maintain. Physically checking them from time to time, recycling trash files and doing software checks for example.

I asked Bing for some additional tips for maintaining my SSD's and the HDD in my Minecraft server.

Optimizing SSDs

Overprovisioning your SSD
Usually done with tools from the manufacturer or during the partition size configuration during the SSD setup. You can also shrink a partition using Disk Management, found in the Computer Management. You end up with "unallocated space" and recommendations for the size of this area vary between 5-10%. Confirm the change by simply going to the file explorer and checking the drive size.
Basically you want to leave the rest for normal user data. Overprovisioning can increase performance by helping with the garbage collection and wear-leveling (spreading the use of the blocks). It increases lifespan and also gives room for error correction.

TRIM:
First tip was about the TRIM command, which essentially helps your computer keep track of where data is located that you want to move or delete.
Open PowerShell and run fsutil behavior query DisableDeleteNotify and if it returns 0 on your results everything is fine. If you instead need to activate it, run fsutil behavior set DisableDeleteNotify 0 which then should optimize erasure and writing speeds on your SSD.

Disable disk defragmentation:
When left on default settings, your computer will optimize and defragment your drives on a weekly basis for example. This wears the SSD out more than necessary, the computer should be left to handle this on its own. Defragmentation is really best for HDD (spinning disks), as they operate functionally different from SSDs. Enter the defragmentation program and turn it off, this require administrative rights.

Disable indexing service?
To some small degree you can get benefits from disabling indexing, as it increases wear on the SSD. Usually indexing takes place when there isn't much load on the CPU anyway. The consequence is that you now manually have to find files or that search is slower. In theory you increase the lifespan, especially with older hardware. Search becomes slower and general system performance remains pretty much the same, but the SSD might live longer. So it is up to you.

Enable cache writing:
Go to the device manager and then go to your disk drives, select the SSD, click "change settings" and then policies. Make sure the write cache is enabled. Do not check the other box that mentions Windows write-cache buffer, this is for devices that has uninterrupted power supply.

Modify power plan so that SSD doesn't sleep:
If you plan to keep your PC running for a long time, you can try this setting in the power settings.
Go to "edit plan settings", select change advanced power settings. Under hard disk you can see how quickly the SSD will fall asleep. Try put it to never. This will increase power consumption, so monitor if this choice is right for you.

SSD Alignment:
SSD data is worked with in blocks. If the starting point is off, the SSD might need to work across two blocks. This slows performance and can cause more wear than needed, alignment makes sure that writing is even across the cells who have limited amount of write cycles. We can check for misalignment by opening PowerShell as administrator and writing "msinfo32". This brings up a new window, press components, storage and disk. Take the numbers from "partition starting offsets" and divide the numbers with 4096. If the result is a whole number the SSD is aligned. 


Optimizing HDDs

Defragmenting HDD
Unlike the SSD, the HDD benefits from being defragmented.
If you run an SSD and an HDD at the same time, you need to find a good way to only optimize the HDD, such as using PowerShell or selecting the specific disk.

Scan for errors
By going to your file explorer and right-clicking on your disk, press properties and go to "tools", there you can check for errors.

Adjust power settings
Just as with the SSDs you can adjust the power plan so that the HDD does not power off. This will of course consume more power, so monitor the results to see if it is worth it.

Move stored data to the HDD
By moving big data files that might seldom be used to the HDD and often used programs to your SSD, you may be able to optimize the use a bit more. Use the SSD for the OS and the HDD for storing files.

Update your system and firmware
This goes without saying perhaps, but it is always worth looking for firmware updates, software upgrades and running diagnostics as final touches.

Wednesday, May 1, 2024

PowerShell: Managing your Minecraft Server

My Minecraft server is running on a separate computer, simply to offset the resource requirements to a separate device.

When managing this server I use RDP to access the GUI and while on the management server I have simplified the management through some PowerShell scripts.

Here are the general outline of the scripts I have connected at this stage.

Currently in development:

Minecraft server start, a script that checks if the .exe is existing and if the process is running. If .exe exists but the process is not running, it starts the process.

Minecraft server stop, basically the reverse. It checks if the process is running, and if so, it issues a stop command to the server.

Minecraft server upgrade, this script is more advanced. It brings home the latest version (at this point hardcoded) and then performs a replacement action, making sure the properties and the world is not lost. Finally it inserts the backed up files again. Lastly it performs cleanup.

Scripts that are tried and tested:

Minecraft diagnostics, a script that performs a general health check. Are all files presents? Is the process running? What is the size of the Minecraft folder?

Minecraft backup, stops the server process, performs copies of the properties and the world, places them on a separate drive and then starts the process again. This is a vital component, because you need a regular backup and in theory you could add this to a schedule and include cleanup functionality.


Future script ideas:

Another project I am considering is a restore script, that combines functions from the backup, diagnostic and the upgrade, basically a script that checks for damage to the folder and perhaps compares with a baseline. Then perform basic replacement and cleanup actions to restore the folder to the best of its ability.

You can also use compare-object to check the contents of the properties for example, to check for corruption.

Last but not least, perhaps there is a way to perform a hashing fingerprint of the world.

Monday, April 22, 2024

pnputil: enable and disable device

The topic of today is how you can work with pnputil.exe to enable and disable devices on your computer.

This was some research and experiments I did to find alternative or complimentary ways to the GUI and PowerShell cmdlets.

By using pnputil.exe /? in PowerShell I found out what some of the uses are and the commands that I was interested in are the following.

To enumerate

This command basically lists all your current devices and their unique ID, in this case it is called Instance ID. Let's say you want to disable a speaker, then you need to find the Instance ID for that speaker.

pnputil /enum-devices

Should you need to enumerate classes for some reason, then this is the command.

pnputil /enum-classes

To disable device

Simply take the full Instance ID for the device, brackets and all.

pnputil /disable-device "SWD\PRINTENUM\{283C1D7C-527C-4D85-8FE7-BCFA6768EA32}"

This example disables Microsoft Print to PDF.

To enable device

It is very much like the previous example, you use the Instance ID to enable the device.

pnputil /enable-device "SWD\PRINTENUM\{283C1D7C-527C-4D85-8FE7-BCFA6768EA32}"

If you keep the device manager open at the same time, you will notice it flicker as the device is enabled/disabled.

Additional examples

You need to run this as an administrator, what you can do for example is to create a simple .ps1 file and then point a shortcut on that file. Then right click the shortcut and run as administrator.

Saturday, April 6, 2024

Windows: Microsoft PC Manager

Some time ago I heard about the latest program from Microsoft, called the Microsoft PC manager. A maintenance tool for computers, that combines already existing tools into a GUI.

Download is available from the Microsoft Store, but since I didn't want to log in, I found a so called offline installer, using Bing. The link for the offline installer (beta) is available here: https://aka.ms/PCManagerOFL30101

The functionality that the app contains are the following features:

Updating your system, including drivers that you can find in Windows Update.

Disk clean up, which includes the classic disk cleanup and removing temporary files for example. A function I found interesting was the scan for duplicate files.

Memory freeing activities, such as closing open processes.

You also can fix startup apps that slows up your booting.

Additionally you have a PC boosting button and a health check. You also have access to Microsoft Defender Antivirus scanning. 


Many of these functions are already available in your Windows 11 installation, but this program gathers these tools nicely under one app. A great addition to your home server management.

Thursday, March 21, 2024

Desktop: Upgrading OptiPlex 3070 SFF

Background

Some time ago I bought an old used Dell OptiPlex 3070 SFF to use as a Minecraft server. This computer costed me 1249 SEK.

The computer came with an i3 8100 processor, and 8 GB of ram, using an NVMe with 128gb of storage.

I wanted to focus on budget and performance primarily. 

Upgrades

The first upgrade was actually an ancient HDD from the Windows XP era that I had laying around, it was seated in the computer and it worked just fine. The practical use of this drive is backup storage of my Minecraft world. For doing this backup I have made a PowerShell script.

The second upgrade was two sticks of DDR4 RAM, each using 16GB. They were both designed to run at 2666 mhz. However it turns out that Dell OptiPlex 3070 does not offer Extreme Memory Profiles (XMP) in the BIOS. In other word, you cannot manage the RAM from the BIOS. These ones I bought for 751 SEK.

The third upgrade was an i7 8700k processor, this required me to take out the HDD and the CPU-cooler. During this operation I also noticed a lot of dust build up, so I took the time to vacuum and apply new cooling paste. This one I bought for 1271 SEK.

How to install i7 8700k in the OptiPlex 3070 is pretty straightforward. Open up the side panel, move the HDD, loosen the CPU-cooler by untightening the screws with springs on. Lift the cooler to the side and remove the current CPU. Place the i7 8700k into the CPU holder, apply enough thermal paste and tighten the mechanism. Then put the computer back in the reverse order.

All these upgrades were practically plug and play. The total cost so far has been 3271 SEK.

Future potential upgrades

Next upgrades might be a better NVMe and Low Profile GPU.

Some of the GPUs that has been recommended by Bing AI are:

NVIDIA® GeForce® GT 730 (2GB GDDR5)

AMD® Radeon™ R5 430 (2GB GDDR5)

RX 550 (2GB GDDR5)


Meanwhile this forum recommends these:

RX 6400 Low profile, 4 GB DDR6

GTX 1050 Ti Low profile, 4 GB DDR5

GTX 1650 Low profile, 4 GB DDR5

RTX A2000 Low profile, 6/12 GB DDR6

It is important to look at the power supply as a bottleneck, some of these GPU - albeit low profile - might draw too much power for the PSU to keep the entire setup running. So my focus will be on getting a lower wattage with as much performance as possible, for the lowest price.

Sunday, March 10, 2024

PowerShell: File backup script

This simple script allows you to backup a chosen folder to a set destination.

This script contains the main engine so to speak, but you can build further using this as a base. Some suggestions might be to add failsafe features or a GUI.

You can also add options to delete/manage existing backups as they exists as simple .zip-files.
Another option you might want to look into is how to revert to an older backup.

I used this script for backing up my Minecraft world, on my MC server. Basically I customized the base script to stop the bedrock_server service as well, as it was blocking the compression. Then it saved the world as a .zip file on a separate disk. This script checks if there was a backup already made today, but of course you can change this to perhaps create a more granular filename to avoid collisions 

Param(

  [string]$Path = 'C:\Temp\App',

  [string]$DestinationPath = 'D:\Backup\'

)

If (-Not (Test-Path $Path)) 

{

  Throw "The source directory $Path does not exist, please specify an existing directory"

}

$date = Get-Date -format "yyyy-MM-dd"

$DestinationFile = "$($DestinationPath + 'backup-' + $date + '.zip')"

If (-Not (Test-Path $DestinationFile)) 

{

  Compress-Archive -Path $Path -CompressionLevel 'Fastest' -DestinationPath "$($DestinationPath + 'backup-' + $date)"

  Write-Host "Created backup at $($DestinationPath + 'backup-' + $date + '.zip')"

} Else {

  Write-Error "Today's backup already exists"

}

Monday, February 12, 2024

Arc Browser: Initial testing on Windows

It all begun with me seeing looking for the best web browser and going through a couple of videos on Youtube, I stumbled upon a new name in the scene called Arc browser. It looked quite clean and modifiable so I wanted to test it out. Unfortunately it wasn't available on Windows yet so they offered a waitlist, with nothing to lose I signed up and the wait begun.

What feels like ages of waiting since I signed up for the beta testing of Arc on Windows has now resulted in an installation of an early beta version of the Arc browser. First thing I did was to open process explorer and check how much resources it consumes. 

This is a sample of having one Youtube video running in the Arc browser. Not too bad, compared with an even more resource consuming Microsoft Edge.


What the Arc browser intends to do uniquely

Their idea is to combine browser, search engine and webpages. You type your question, it goes out and gets the information for you and builds your own page. "A browser that browses for you" is the way that The Browser Company explains it in a video, and they also want it to anticipate your needs as well.

It is available on Mac and iOS and this is their website: Arc from The Browser Company

How to join the waitlist

Joining the wait list was simple, I signed up on this link and then I waited. Today the download link and some basic instructions arrived in the email. Nothing too complicated really.

The instructions tell you to create and use a login for the browser, much like Mozilla Firefox, this account helps you sync your data. You are also asked not to share the download link or your login. 

Installation was simple, a regular app installer was downloaded which you then could execute.

Initial experience of Arc browser on Windows 11

Keep in mind that it is an early beta version so there are functionalities missing and not entirely chiseled out. On the side you have your tabs, folders/groups of pages, and access to your Gmail and Google Calendar.

The tab system on the left seems really clean at the beginning, I am curious to see how it will work when the amount of pages ramps up however.

Entering text into the search bar will Google it for you like usual, I wasn't able to intuitively get it to perform the Arc magic, the search bar was also a bit smaller than the Edge search bar I am used to so it was less easy to click.

So the first impressions is that it looks modern, feels clean but I am lacking a bit of the intuitive aspect and functionality.
Let's keep our eyes on the browser for what more is to come in the future.

Wednesday, January 24, 2024

Raspberry Pi: How to mine Monero

As I was looking for projects for Raspberry Pi I found a video on Youtube that NetworkChuck had posted. One project that I wanted to try for a few days was to mine cryptocurrency on the device, mostly to see if it was possible and learn what the process looks like. While the Pi 5 is the most powerful yet, it does not compare to dedicated mining machines. Simply put, it was interesting to learn but not a profitable venture in the slightest.

Some things to consider are the following:

- You are part of a miner pool, since your hardware might be weak you pool your resources with others and thus share the rewards with the pool

- There is a minimum payment threshold before the currency is sent to your wallet, I mined for 4-5 days straight and did not see any results in the wallet.

Download and install the wallet

I used the basic GUI wallet from Monero, they have a regular installer for Windows.

You install it like any other app, keep in mind that you can avoid the 90gb storage by running it in simple mode. It will take a while to sync the so called blockchain when starting up the wallet, but you avoid having to deal with 90gb of storage. A server somewhere else will be handling this for you, so it is also less anonymous if that is important for you.

Pro tip: Store your account recovery details, passwords etc. safely.

In your wallet you can find your wallet address under the account tab, use this when you start your Monero miner on the Raspberry Pi 5 later.

To install the miner

First I created a folder called monero.

Then went into the folder, ran the following code from the terminal:

sudo apt install git build-essential cmake libuv1-dev libssl-dev libhwloc-dev -y

git clone https://github.com/xmrig/xmrig.git

cd xmrig

mkdir build && cd build

cmake ..

make

To start the miner 

Be in the build folder and enter the command below. You define which pool, which address and what you want to name your miner in case you have several computers mining at the same time.

./xmrig -o gulf.moneroocean.stream:10128 -u <wallet adress goes here> -p pi5

While it is mining you can press H to check your hashrate, higher is better. To see what you have contributed press S. Press C to check your connection, such as your difficulty.

To stop the miner

Ctrl + C, like any other command in a terminal

Friday, January 19, 2024

Raspberry Pi 5: Ubuntu server installation

Prerequisites

To get Ubuntu Server on Raspberry Pi it was actually as easy as just getting the Raspberry Pi imager from the official website.

Install it and run it directly.

Choose device (raspberry pi 5), choose OS (other general-purpose OS -> Ubuntu -> Ubuntu Server)

Choose a device to flash it to.

You will have options to include into your file, these are important. You want to set up wifi, make sure SSH is active and set an admin login, this is used later when you SSH in with PowerShell and when you login to the server with RDP. 

Flash the OS to the SD card, you are now done with the first step.

First time booting Ubuntu Server on Raspberry Pi 5

Put the SD card in the device. Keyboard, mouse and monitor is optional as you can manage the device wirelessly and remotely right away if you performed the options detailed in part 1.

Go to your router and find the IP address of the device, this is used in next step.

Open PowerShell and write ssh admin@192.168.0.X where admin is the user name and X is the last part of the IP address. Confirm with password. SSH is a secure alternative to Telnet.

You will then be taken to an admin prompt that takes linux commands.
You might want to start with the following command:

sudo apt-get update && sudo apt-get upgrade

Make sure to confirm if it prompts you.  

GUI and RDP to Ubuntu Server

The last step was to configure a desktop experience and RDP.

For the deskop experience I simply ran two commands, it would seem that the first one is required.

sudo apt install ubuntu-desktop-minimal

sudo apt-get install xfce4

If prompted, I went with the option lightdm and I restarted all serviced that asked me too, some which also disconnected me from the internet.

For the RDP I first ran the following command:

sudo apt install xrdp -y

Followed by this command that shows you if the installation went alright.

sudo systemctl status xrdp

After that I could RDP using the built-in solution on Windows. Some sources claim you need to fix ssl certs and restart the service, but I could start it right away.

Configure your RDP from your Windows computer

Configure a RDP link on your desktop with the following steps:

1. Open remote desktop connection from your start menu

2. Pick "show options"

3. Computer should be the IP address, user name is the one you entered at the flashing of the image

4. Save as, place it in a good location. Now you can use it and just entering your password.

When you login using RDP you will be greeted with a more familiar desktop experience.


Enjoy!