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.

No comments:

Post a Comment