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.