Activate via KMS

@echo off
Title Activation Tool
color 0a
set KMS=YOUR_KMS_IP_ADDRESS
color 0e

cls
echo Trying to contact the KMS…
ping -n 4 127.0.0.1>nul
ping %KMS% -n 2 | find “Reply” > nul
if %errorlevel% EQU 0 goto :NEXT
cls
color 0c
echo KMS cannot be contacted! Exiting now…
ping -n 6 127.0.0.1>nul
exit /b 0

:NEXT
color 0a
echo The KMS has been contacted.
ping -n 4 127.0.0.1>nul
echo.
Echo Activating Windows 7…
cscript C:\Windows\System32\slmgr.vbs -skms %KMS%
cscript C:\Windows\System32\slmgr.vbs -ato
ping -n 4 127.0.0.1>nul
cls
Echo Windows 7 has been activated!
ping -n 4 127.0.0.1>nul
if not exist “C:\Program Files (x86)\Microsoft Office\Office14\ospp.vbs” exit /b 0
cls
echo Activating Office 2010…
cscript “C:\Program Files (x86)\Microsoft Office\Office14\ospp.vbs” /sethst:%KMS%
cscript “C:\Program Files (x86)\Microsoft Office\Office14\ospp.vbs” /act
cls
Echo Office 2010 has been activated!
ping -n 4 127.0.0.1>nul

exit /b 0

email me

Using ENABLEDELAYEDEXPANSION

ENABLEDELAYEDEXPANSION is a useful property that allow you to do what you think should happen when you write a for loop or an if block. Consider this example.

set COUNT=0

for %%var in (1 2 3 4) do (

set /A COUNT=%COUNT% + 1

echo %COUNT%

)

Now in any other scripting or programming language, this would be just fine. Not so in windows batch. Since batch processor treats the whole for loop as one command, it expands the variables once and only once, before it executes the loop. So you end up with %COUNT% being expanded to its value, which is 0, before you start the loop, and you end up printing 0 four times in a row.

That’s where delayed expansion comes in. As the name suggests, delayed expansion makes batch processor delay expanding the variable to its value until it actually loops through it.

But to make that happen, you need to do two things.

1. Enable delayed expansion. You can do this by doing setlocal ENABLEDELAYEDEXPANSION at the beginning of your script.

2. Use ! instead of % to expand environment variable value.

Now here’s that example again using delayed expansion:

setlocal ENABLEDELAYEDEXPANSION

set COUNT=0

for %%var in (1 2 3 4) do (

set /A COUNT=!COUNT! + 1

echo !COUNT!

)

This time you will see 1 2 3 4 being printed, as you expect.

Another way of turning on delayed expansion is through the registry. You can go and add it manually through regedt32.exe, or you can load a registry file like the one shown here:

Windows Registry Editor Version 5.00[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]

“DelayedExpansion”=dword:00000001

Just save it to a file called enabledelayedexpansion.reg or something, and just invoke that file from the command line.

enabledelayedexpansion.reg

This will enable delayed expansion for current user. You can do the same for HKEY_LOCAL_MACHINE.
You need to start a new console window to see its effect. To check, simply do

echo !COMPUTERNAME!

in the new command console. If it prints your computername, then it recognizes the ! variable expansion, which means delayed expansion is enabled.
This way you don’t have to do setlocal ENABLEDELAYEDEXPANSION. But watch out, you need to make sure this thing is enabled if you are planning on skipping setlocal ENABLEDELAYEDEXPANSION in your script.

email me

Managing Text Files – VBScript

email me

Reading Text File

Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",1)
Dim strLine
do while not objFileToRead.AtEndOfStream
     strLine = objFileToRead.ReadLine()
     'Do something with the line
loop
objFileToRead.Close
Set objFileToRead = Nothing

Checking the Size of a File Before Reading It

Demonstration script that uses the FileSystemObject to ensure that a text file is not empty before attempting to read it. Script must be run on the local computer.

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\Windows\Netlogon.log")
If objFile.Size > 0 Then
    Set objReadFile = objFSO.OpenTextFile("C:\Windows\Netlogon.log", 1)
    strContents = objReadFile.ReadAll
    Wscript.Echo strContents
    objReadFile.Close
Else
    Wscript.Echo "The file is empty."
End If

Creating and Naming a Text File

Demonstration script that uses the FileSystemObject’s GetTempName method to generate a file name, and then creates a file by that name.

Set objFSO = CreateObject("Scripting.FileSystemObject")
strPath = "C:\FSO"
strFileName = objFSO.GetTempName
strFullName = objFSO.BuildPath(strPath, strFileName)
Set objFile = objFSO.CreateTextFile(strFullName)
objFile.Close
objFSO.DeleteFile(strFullName)

Creating a Text File

Demonstration script that creates a new, empty text file. Script must be run on the local computer.

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\FSO\ScriptLog.txt")

Generating a File Name

Demonstration script that uses the FileSystemObject’s GetTempName method to generate random file names. Script must be run on the local computer.

Set objFSO = CreateObject("Scripting.FileSystemObject")
For i = 1 to 10
    strTempFile = objFSO.GetTempName
    Wscript.Echo strTempFile
Next

Reading a Text File Character by Character

Demonstration script that uses the FileSystemObject to read a text file character-by-character, and individually echo those characters to the screen. Script must be run on the local computer.

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\New Text Document.txt", 1)
Do Until objFile.AtEndOfStream
    strCharacters = objFile.Read(1)
    Wscript.Echo strCharacters
Loop

Reading a Text File into an Array

Demonstration script that uses the VBScript Split command to read a line from a commas-separated values file, and then place the individual items in that line into an array.

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\servers and services.txt", ForReading)
Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
    arrServiceList = Split(strNextLine , ",")
    Wscript.Echo "Server name: " & arrServiceList(0)
    For i = 1 to Ubound(arrServiceList)
        Wscript.Echo "Service: " & arrServiceList(i)
    Next
Loop

Reading a Text File from the Bottom Up

Demonstration script that uses the FileSystemObject to read a text file, and then to echo the text file in inverse order (that is, beginning with the last line in the text file and ending with the first line).

Dim arrFileLines()
i = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", 1)
Do Until objFile.AtEndOfStream
     Redim Preserve arrFileLines(i)
     arrFileLines(i) = objFile.ReadLine
     i = i + 1
Loop
objFile.Close
For l = Ubound(arrFileLines) to LBound(arrFileLines) Step -1
    Wscript.Echo arrFileLines(l)
Next

Writing Data to a Text File

Demonstration script that retrieves the status for all the services installed on a computer, and then saves the service name and status to a text file.

Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\service_status.txt", ForAppending, True)
Set colServices =  GetObject("winmgmts:").ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colServices    
    objTextFile.WriteLine(objService.DisplayName & vbTab & _
        objService.State)
Next
objTextFile.Close

Windows – Dism Commands

email me

Some basic DISM commands:

Run following command to clean up any previous wims/mounts:
DISM /Cleanup-Wim


To check image info: 
Dism /Get-WimInfo /WimFile:C:\images\boot.wim

 

To check mounted images:
dism /get-mountedwiminfo

 

Mount .Wim File on your local C Drive:
dism /mount-wim /wimfile:c:\images\boot.wim /index:1 /Mountdir:c:\mount

 


Adding drivers command:
dism /image:c:\mount /add-driver /driver:c:\drivers\ /recurse


Unmounting image to wim file by running command:
dism /unmount-wim /mountdir:c:\mount\ /commit

 


Notes

Modify a Windows image using DISM

DISM – Deployment Image Servicing and Management

Use DISM in Windows PowerShell

Windows 10 DISM Command-Line Options

DISM Best Practices

PXE-E32: TFTP OPEN TIMEOUT

Verify that there are no other PXE servers running on the network. This is something that can be accomplished using a network sniffer. With the network sniffer verify that no other PXE server is responding to the client computer. The existence of another PXE server on the network could cause the PXE client to receive invalid TFTP server information.

If the the three above step check out, verify that PXE/TFTP server is listening on port 69. This can be done by running the utility TCPView from www.sysinternals.com and verifying the existence of ports 69, 1758, and 1759 in the Local Address section.

If the services are running in the service manager, but there are no services showing up in the tcpview other than on the pxe configuration service, look in the task manager on the pxe server (remote or ds local) to see if there are a large number of processes in the task manager.  If there are, use the following command line in a command prompt:  taskkill /Im process.exe /F  This will stop the processes and free up resources so that the pxemtftp and the pxe service can run.  This can be verified in the tcpview after running the command line.

If you are crossing subnets/VLANs/VPN, make sure that ports 69, 1758, and 1759 are allowed and that the network infrastructure is configured properly to allow the client computer to connect to the server via port 69, 1758, and 1759.

If your network is not properly configured to allow Multicasting, or you are not sure if it is, disable multicasting for the bootfile transfer by following the instructions in the document “Disabling Multicast for the PXE Boot File Transfer”. (For disabling Multicast ing Deployment Solution 6.5: If the routers/switches have been configured to pass multicast broadcast packets and the error is still occurring, go the PXE Configuration Utility in the DS console under Tools > PXE Configuration and the Multicast tab. You can disable the “Use Multicast for Boot File Transfer” (in Deployment Solution 6.5 the option is “Enable MTFTP”) and then send the job out again. This disables the use of multicast and then the settings on the routers/switches will no longer be a factor.)

Check to make sure that teamed NICs on the Deployment Solution are functioning correctly. Removing the team and re-creating it has resolved this issue for HP DL380 servers.

Another issue that has been discovered is if the machine that is PXE booting is assigned an IP address of the form xxx.xxx.xxx.255. The tftp server treats this as a broadcast and ignores it. To resolve this, an IP reservation needs to be made so that the .255 address is not assigned.

IPsecurity policies can also cause this error.  To test this disable the IPSEC service and try pxe booting the client.  If the client is able to PXE boot then you will need to make a boundary box exception in the IPSEC policy to allow communication over tcp/ip port 68 and 69 to the deployment server.

If all of the above check out and you are still seeing the error, collect all of the PXE Logs, as well as sniffer traces from the PXE server. Make sure that the sniffer traces are not filtered and capture all traffic. Also make sure to include any event viewer logs that might relate to PXE.

Make sure the box ‘Enable response to computers with active DS job assignments only’ in the DS tab of the PXE configuration utility is NOT checked. It will cause a PXE E32 TFTP Open timeout error as well.

email me

Always Unlock a Specified Account

email me

This is a simple but effective way to unlock a user account automatically. Note, you cannot use the same account name in the script…to run the script.

I have disabled the message boxes and added a loop.

On Error Resume Next

strUser = "TheUserName"

If strUser = vbNullString then
'MsgBox "Either Cancel was selected or you did not enter a user name.", 16, "User Unlock"
WScript.Quit
End If

strDomain = "YourDomainName"

Set objUser = GetObject("WinNT://"& strDomain &"/" & strUser & "")
If Err.Number <> 0 Then
'MsgBox (strUser) & " isn't a valid user name!", 48,"User Unlock"
Wscript.Quit
End If

Err.Clear

x = 0
do while x = 0

If objUser.IsAccountLocked = 0 Then
'MsgBox (strUser) & " isn't locked out.",64,"User Unlock"
Else
objUser.IsAccountLocked = 0
objUser.SetInfo
If Err.number = 0 Then
'MsgBox (strUser) & " has been unlocked.",64,"Unlock User"
Else
'MsgBox "There was an error unlocking" & (strUser) & " on " & UCase(strDomain) & ".",16,"User Unlock"
End If
End If

wscript.sleep 480000'8 minutes 'waits 8 minutes, and then cycles back. You can change this value.
loop

Set objUser = Nothing
Wscript.Quit

Check Laptop Power Adapter Status

email me

on error resume next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\wmi")
Set colItems = objWMIService.ExecQuery("Select * From BatteryStatus Where Voltage > 0")

For Each objItem in colItems
strCondition = objItem.PowerOnline
Next
if strCondition = "False" then msgbox "   Please connect the power adapter to the laptop."

WScript.Quit(0)

User Account Password Age

To Change the Minimum Password Age
net accounts /minpwage:(0-998)


To Change the Maximum Password Age –
(how long the user can use the password)
net accounts /maxpwage:(1-999)


To Disable Password Expiration for All Users

net accounts /maxpwage:unlimited


For my reference

net accounts [/forcelogoff:{minutes | no}] [/minpwlen:length] [/maxpwage:{days | unlimited}] [/minpwage:days] [/uniquepw:number] [/domain]


Parameters

/forcelogoff: { minutes | no } : Sets the number of minutes to wait before ending a user’s session with a server when the user account or valid logon time expires. The default value, no, prevents users from being forced to log off.

/minpwlen: length : Sets the minimum number of characters for a user account password. The range is from 0 through 127 characters and the default is six characters.

/maxpwage: { days | unlimited } : Sets the maximum number of days that a user account’s password is valid. The unlimited value sets no maximum time. The /maxpwage command-line option must be greater than /minpwage. The range is from 1 through 49,710 days (that is, unlimited equals 49,710 days), and the default value is 90 days.

/minpwage: days : Sets the minimum number of days before a user can change a new password. The default value is zero days, which sets no minimum time. The range is from 0 through 49,710 days.

/uniquepw: number : Requires a user to not repeat the same password for the specified number of password changes. The range is from 0 through 24 password changes, and the default is five password changes.


Examples

To display the current settings, the password requirements, and the server role for a server, type:

net accounts

 

To set a minimum of seven characters for user account passwords, type:

net accounts /minpwlen:7

 

To specify that users can reuse a password only after the fifth time they change passwords, type:

net accounts /uniquepw:5

 

To prevent users from changing passwords more often than every seven days, force users to change passwords every 30 days, and force users to log off after the logon time expires with a five-minute warning, type:

net accounts /minpwage:7 /maxpwage:30 /forcelogoff:5

 

To ensure that the preceding settings take effect for the domain that the computer is logged on to, type:

net accounts /minpwage:7 /maxpwage:30 /domain

email me

Useful WMIC Statements

see Windows Category

 

Using wmic can prove quite powerful in automation and scripting tasks.
 
 

Spot Odd Executables
wmic process where “NOT ExecutablePath like ‘%Windows%'” get ExecutablePath

Look at services that are set to start automatically
wmic service where StartMode=”Auto” get Name, State

Find user-created shares (usually not hidden)
wmic share where “NOT Name like ‘%$'” get Name, Path

Find processes that starts on boot
wmic startup get caption, command, user

Identify any local system accounts that are enabled (guest, etc.)
wmic useraccount where “Disabled=0 AND LocalAccount=1″ get Name”

Change Start Mode of Service
wmic service where (name like “Fax” OR name like “Alerter”) CALL ChangeStartMode Disabled

Number of Logons Per USERID
wmic netlogin where (name like “%jackson”) get numberoflogons

Return a Certain Kind of Event from Eventlog
wmic ntevent where (message like “%logon%”) list brief

Clear the Eventlog (Security example)
wmic nteventlog where (description like “%secevent%”) call cleareventlog

Get Mac Address
wmic nic get macaddress

Reboot or Shutdown
wmic os where buildnumber=”7601″ call reboot

Update Static IP Address
wmic nicconfig where index=9 call enablestatic(“192.168.1.100”), (“255.255.255.0”)

Change network Gateway
wmic nicconfig where index=9 call setgateways(“192.168.1.254”, “192.168.1.200”),(1,2)

Enable DHCP
wmic nicconfig where index=9 call enabledhcp

Service Management
wmic service where caption=”DHCP Client” call changestartmode “Disabled”

Start an Application
wmic process call create “notepad.exe”

Terminate an Application
wmic process where name=”notepad.exe” call terminate

Change process Priority
wmic process where name=”notepad.exe” call setpriority 64

Get List of Process Identifiers
wmic process where (Name=’svchost.exe’) get name,processid

Information about Hard Drives
wmic logicaldisk where drivetype=3 get name, freespace, systemname, filesystem, size, volumeserialnumber

Information about OS
wmic os get bootdevice, buildnumber, caption, freespaceinpagingfiles, installdate, name, systemdrive, windowsdirectory /format:htable > c:\osinfo.htm

Information about Files
wmic path cim_datafile where “Path=’\\windows\\system32\\wbem\\’ and FileSize>1784088” > c:\wbemfiles.txt

Process List
wmic process get /format:htable > c:\process.htm

Retrieve list of warning and error events not from system or security logs
wmic ntevent where “EventType c:\appevent.htm

Total Hard Drive Space Check
wmic logicaldisk list brief

Get Running Services Information
wmic service where (state=”running”) get caption, name, startmode, state

Get Startmode of Services
wmic service get caption, name, startmode, state

Get Domain Names And When Account PWD set to Expire
wmic UserAccount get name,PasswordExpires /Value

Get Hotfix and Security Patch Information
wmic QFE get /format:CSV >QFE.CSV

Get Startup List
wmic startup list full

Find a Specific Process
wmic process list brief find “cmd.exe”

Get List of IP Interfaces
wmic nicconfig where IPEnabled=’true’

Change IP Address
wmic nicconfig where Index=1 call EnableStatic (“192.168.1.1”), (“255.255.255.0”)

OS and System Report HTML Formatted
wmic /output:c:\os.html os get /format:hform

Products and Programs Installed Report HTML Formatted
wmic /output:c:\product.html product get /format:hform

Services Report on a Remote Machine HTML Formatted
wmic /output:c:\services.htm /node:server1 service list full / format:htable

Turn on Remote Desktop Remotely
wmic /node:”servername” /user:”user@domain” /password: “password” RDToggle where ServerName=”server name” call SetAllowTSConnections 1

Get Server Drive Space Usage Remotely
wmic /node:%%A LogicalDisk where DriveType=”3″ get DeviceID,FileSystem,FreeSpace,Size /Format:csv
MORE /E +2 >> SRVSPACE.CSV

Get PC Serial Number
wmic /node:”HOST” bios get serialnumber

Get PC Product Number
wmic /node:”HOST” baseboard get product

Get Services for Remote Machine in HTML Format
wmic /output:c:\services.htm /node:ServerName service list full / format:htable

 

< Windows 10 Category