Windows How To

How to set powershell as a default shell

Note that if you are doing it on a Virtualbox VM, switching the shell will break VirtualBox tools.

# Use C# to leverage the Win32API
$definition = @"
using System;
using System.Runtime.InteropServices;
namespace Win32Api
{
    public class NtDll 
    {  
        [DllImport("ntdll.dll", EntryPoint="RtlAdjustPrivilege")]  
         public static extern int RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool Enabled); 
    } 
}
"@
Add-Type -TypeDefinition $definition -PassThru
$bEnabled = $false
# Enable SeTakeOwnershipPrivilege
$res = [Win32Api.NtDll]::RtlAdjustPrivilege(9, $true, $false, [ref]$bEnabled)
# Take ownership of the registry key
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AlternateShells', [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
$acl = $key.GetAccessControl()
$acl.SetOwner([System.Security.Principal.NTAccount]"Administrators")
# Set Full Control for Administrators
$rule = New-Object System.Security.AccessControl.RegistryAccessRule("Administrators","FullControl", "Allow")
$acl.AddAccessRule($rule)
[void]$key.SetAccessControl($acl)
# Create Registry Value
[void][Microsoft.Win32.Registry]::SetValue($key,"40000",'powershell.exe -noexit -command "& {set-location $env:userprofile; clear-host}"')

How to prevent screensaver from starting

Simulate user activity.
Powershell

param($minutes = 0) 
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 60
  $myshell.sendkeys("{SCROLLLOCK 2}")
}

VBScript

Set objShell = WScript.CreateObject("WScript.Shell")
Do
  objShell.sendkeys("{SCROLLLOCK 2}")
  Wscript.Sleep(60000) ' a minute
Loop

Kick it off on boot with a script like this

@echo off
rem cscript for command line, 
rem cscript.exe C:\bin\simulate-activity.vbs
rem wscript to keeps it running in the background even when the parent cmd is closed
echo Safe to close the window, it will keep running in the background
wscript.exe C:\bin\simulate-activity.vbs

How to stop numloc etc osd notifications

They might be displayed by hpCaslNotification that is run by QLBController.exe. Uninstall HP hotkey support, or stop the hpHotkeyMonitor service or
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Hewlett-Packard\HP HotKey Support
Create any of the values listed to disable the notification you no longer want/need:
AmbientLightSensorOSD DWORD 0
BrightnessOSD DWORD 0
CapsLockOSD DWORD 0
NumLockOSD DWORD 0
ScrollLockOSD DWORD 0
VolumeOSD DWORD 0


How to synchronize screen lock between Windows and Linux

From Windows 7, the first part can be done with scheduled tasks. You can create a task with a Trigger of "Workstation Lock", and an action of running cmd /c "echo knock-lock | nc -w 1 localhost 24809" and similarly for unlock.

How to clear outlook cache .ost file

Do it by recreating the offline data file

  1. Exit Outlook
  2. Open Mail configuration from the control panel
  3. Click email accounts. On the e-mail tab (opened) click "change"
  4. Clear the "use cached exchange mode", then click settings
  5. Go to the advanced tab, click "offline data file settings"
  6. Click "disable offline use". On the confirmation prompt click "yes" (obviously).
  7. Now go back, click "ok" and another prompt will appear asking you to create a file. Say "yes"
  8. Now check "use cached exchange mode" on the window you were returned to. Click "ok", "next", then "finish". You are done.

How to allow running privileged executables from a remote drive

This hack would allow your elevated programs to see network drives and be executed from these drives, without having to disable UAC completely.

  1. In the registry locate the key HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System
  2. Create a new DWORD entry EnableLinkedConnections, set it to 1
  3. Reboot

How to delete drivers and records of inactive devices

From the command prompt.

set devmgr_show_nonpresent_devices=1
devmgmt.msc”

When device manager is started, click View -> Show Hidden Devices. This will show you old devices as "greyed out" that you can then remove.

How to get a parent process id from the Windows command line

wmic process where (name like '%name of the process%') get parentprocessid

For further processing of the results in the batch file look here.

How to get process id of a batch file

I found the method that works quite reliably and does not require external commands:

for /f "usebackq tokens=* skip=1" %%P in (`wmic process where "commandline like '%%name of the file.bat'" get processid`) do set PID=%%P

Use %0 or the fully expanded %~f0 if you want to reference back to the name of the batch file that executes the wmic command.

How to determine which services are "hosted" by which svchost process

TASKLIST /FI "imagename eq svchost.exe" /SVC

How to run a batch file as a service

  • Install the resource kit 2003 from here
  • Run the following

instsrv.exe "''Service'' ''Name'' ''Here''" "C:\Program Files\Windows Resource Kits\Tools\srvany.exe"

  • Create the Parameters key in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Service Name Here
  • Add the Application string value under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Service Name Here\Parameters that reads "cmd /c C:\full path to your batch\name of the batch.bat"

For more info on srvany look here

Note for windows 2008+: srvany is deprecated. Look at the sc command to make it work.

How to run a command form a remote session that survives an RDP disconnect

Schedule it with an "at" command. Make sure all the paths used are absolute (try running it manually from a random folder) and that the command does not rely on your personal settings/environment.

How to print from Windows to a printer connected to Ubuntu

On the ubuntu print server edit /etc/samba/smb.conf and uncomment in [global]

load printers = yes
printing = cups
printcap name = cups

Add the following to [printers]

use client driver = Yes

Restart samba

sudo service smbd restart

On the Windows client go to Add a printer->Networked printer. Put in the URL of your printer

http://printserver:631/printers/yourprintername

If you do not know the URL you can get it the CUPS Web UI from the print server

http://localhost:631

In the PRINTERS tab, hover over the shared printer name or view its properties. Now point to your print driver on the Windows machine and print a test page.

How to turn off Internet Explorer Enhanced Security Configuration

if you see res://shdoclc.dll/hardAdmin.htm when opening IE, go to control panel -> add remove programms -> add remove windows components -> then uncheck IE Enhanced security config Click next and you are done

How to lock and unlock a windows box through an SSH connection

  • To lock:
    • open an ssh connection to the box and lock run

/cygdrive/c/WINDOWS/System32/rundll32.exe user32.dll,LockWorkStation

  • To unlock
    • Google for RemoteUnlock. Get RemoteUnlockDll.dll and RemoteUnlockService.exe from the web. Note that these execs may trigger antivirus alerts, so you might need to polymorph the code or feed it through an PE packer/encrypter. I am not giving you the links, because this a bit shady and the links to the code don't stay up for too long.
    • Run the exe on the box through ssh

How to do echo in a batch file without going to a next line

Here is an example where this is used for a rudimentary progress bar:

@echo off
for /l %%A in (1,1,20) do (
    <nul (set/p z=%%A)
    >nul ping 127.0.0.1 -n 2
)

And here is an example where info is written to a single line in a file from multiple uses of the set/p command:

<nul (set/p z=hello) >out.txt
<nul (set/p z= world!) >>out.txt
dir out.txt

The dir command should indicate the file size as 12 bytes: "hello world!".

The strings output need not be literal, and can originate from any source capable of creating a variable, simply by including a variable reference in the prompt string:

<nul (set/p z=sec min hours: %time:~6,2% %time:~3,2% %time:~0,2%)

1

How to find all dlls for a service

@echo off
set imagepath=
FOR /F "tokens=3" %%a in ('reg query HKLM\system\currentcontrolset\services\%1 /v imagepath 2^> nul ^| find "imagepath" ') DO set imagepath=%%a
if defined imagepath (
    echo Dependencies for %imagepath%:
    call depends /a0f1c /oc:~svcdep.tmp "%imagepath%"
    FOR /F "tokens=1 delims=, skip=1" %%b in ('type ~svcdep.tmp ^|findstr /B /c:"," ^|findstr /V /c:"?" ^| sort') do echo %%b
    del ~svcdep.tmp 2>nul
) else (
    echo '%1' is not installed or is not a valid service
)

How to login as an NT Authority system user

If you are using a remtoe connection, first, make sure you are connected to a console (main display) of the remote server To access the console run

mstsc /admin /v:servername

(older versions used /console switch)

The trick is to use task scheduler to kick off a cmd that will by default use the system user

start cmd
net start "Task Scheduler" (if it is not already started)
at 11:10 /interactive c:\windows\system32\cmd.exe

ATTN: If you are running this command over a TS connection the tasks will be brought up on the CONSOLE session, not your TS screen.

To check that the task was added successfully run

at 

Once the new cmd is up it will be running as the system user. To check that run

whoami 

Now you can use the elevated privileges.

For example to restore SQL sa or an administrative account just type

C:\WINDOWS\system32\mmc.exe /s "C:\Program Files\Microsoft SQL Server\80\Tools\BINN\SQL Server Enterprise Manager.MSC"

in the new cmd shell

How to remove login banner (legal notice) "by logging in this system you acknowledge..."

Annoying, isn`t it? Here is the pill -

regedit HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system

delete legalnoticetext and legalnoticecaption You'll be fine until the next time GPO is applied

How to run regedit interactively in the System account to view the contents of the SAM and SECURITY keys

psexec -i -d -s c:\windows\regedit.exe

How to set service dependancies

Run

regedit "LMachine/System/CurrentControlSet/Services/IBMWAS6Service - ITIMServerNode01"

Then add

DependOnService="DB2ADMIN\000\000", "REG_MULTI_SZ"

How to simulate bash backtick in win cmd batch

  • Generic backtick
rem Prep for backtick
<nul (set/p z=set result=) > setresult$
rem Run it
program > tmpresult$
copy setresult$ + tmpresult$ tmp$.bat > nul
call tmp$.bat
echo %result%
rem Teardown backtick
del setresult$
del tmpresult$
del tmp$.bat

  • If doing this in a loop add the following and use !result! instead of %result%

SetLocal EnableDelayedExpansion

  • Less generalized backtick with the use of sed
rem Does search and replace in both file name and file contents
<nul (set/p z=sed -rb s/\$1/%1/g "%%a" ^> ) > tmp$.bat
echo ../../%1/%1%2Profile/%%a | sed -r s/\$1/%1/g >> tmp$.bat
call tmp$.bat

@HowTo @Microsoft




Backlinks: iamhow.com:How To:How to synchronize screen lock between Windows and Linux