Scripting
Since I am from the DOS age I always used to script my way around problems. In windows 7 it is still possible to do everything with DOS scripts.
I hope you can find something useful here. For scripting I advise to use Notepad++ since it recognizes the script language you write in and uses colors to make commands and blocks stand out. There are plugins that can be very useful. I use TextFX frequently.
I highly recommend to visit the page of my respected fellow countryman Rob van der Woude who has a very well documented website on this subject or DosTips.
Good info on redirecting stdin and stdout can be found here at Microsoft.
WmiTool
I am working on a CMD script called wmitool. The aim is to build an administration tool that can be used for local and remote PC's. Wmitool is menu
driven. The wmitiool can be found here or in the file section below.
Discussion here on Windows SevenForums.
Note1: this tool is free and for educational purposes only. I give no permission to use it in a commercial environment.
Note2: if wmic cannot find /FORTMAT:CSV or XML then use the switch /locale:ms_409
Changes: added disable Service, added Create Restore Point, added Restore a Restore Point, service dependencies, group membership,send message, uninstall software by keyword, ...
Remote command execution
With wmic.exe you can execute any command on any PC. This is very useful.
wmic /node:[targetIPaddr] /user:[admin] process call create "[command]"
An example:
wmic /node:laptop /user:".\administrator" process call create "REG.EXE ADD HKLM\SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction /f /v Enable /t REG_SZ /d Y"
Make sure no user input is expected at the other end.
Powershell:
$PC="SOMEPCNAME"
Invoke-Command -ComputerName $PC -ScriptBlock {Set-ItemProperty -Path "HKLM:SOFTWARE\Policies\Microsoft\Edge" -Name "StartupBoostEnabled" -Type DWord -Value 0}
Using text output from DOS commands as variables in your script
Every DOS command produces text output. If you write a script you have a purpose for that script. You want something to be done. Most scripts need input to get a job done. The input can be obtained from the command output with the for /f command. Type for /? to see all options.
Also every DOS command returns an ErrorLevel. The value of 0 indicates mostly that the command was successful. You can test the ErrorLevel after the command with If ERRORLEVEL 0
Lets take a very simple example to illustrate the for /f command an I will explain what it does. We want to find all files on our harddrive with the extension ".log" and we want to compact them.
For /f "delims=" %f in ('dir /s /b C:\*.log') Do @Echo compacting %f & Compact.exe /C /F /I /Q "%f" || @Echo Error Compacting %f
This For executes the "dir /s /b C:\*.log" command just like you can do by typing the command at the prompt. It will output the files that have the .log extension.
The list of files that match are put into the variable %f one after another. So it steps through the list.
Note that file and foldernames can have spaces so we need to put "" around the filename in the Compact command.
For the same reason we need to define "delims=" because the For /f sees spaces by default as separator. So %f will otherwise be the first part up to the first space in the output. With "delims=" %f will always be the whole line of the output, regardless of spaces.
So for each list entry the command will do: Echo the filename and (&) compact it. The double pipe (||) command after the Compact command will kick in if the ErrorLevel of the Compact command is not 0 (so failed).
Double pipes command
Any command sets the errorlevel after completion. If the errorlevel is not 0 then there was an error with the last command. You can use "double pipes" to catch that.
To give an example with "double pipes" and the traditional way:
Net user %USERNAME% /Domain | Find /i "Domain Admins" || Echo %USERNAME% is not a member of Domain Admins
Net user %USERNAME% /Domain | Find /i "Domain Admins"
If Not ErrorLevel 0 Echo %USERNAME% is not a member of Domain Admins
You can use double ampersand "&&" if you want to continue if previous command was successful, errorlevel 0
Using Echo without linefeed
Echo|SET /p=text_to_echo
Set /p default option
In case the user presses an Enter answer will be N. In general: if the first command produce errorlevel>0 then do second command.
SET /p answer="Do you want to delete the file? (Y/N): " || SET answer=N
Multiple commands in Windows Shortcut Icon
Use this for multiple commands in a Windows Shortcut: cmd /c command1 & command2
For example:
cmd.exe /c Dir c:\windows /ah & Timeout 10
cmd.exe /c wmic.exe PAGEFILE get /format:LIST | msg *
cmd.exe /c PowerCfg.exe /BatteryReport /output C:\Temp\BatteryReport.html & C:\Temp\BatteryReport.html
cmd.exe /c cd /d %userprofile%\AppData\Local\Microsoft\Windows\Explorer & taskkill /im explorer.exe /f & del /f /q thumb* iconc* & rd thumb* /s /q & start explorer.exe
tasklist | find "some.exe" && taskkill /f /im some.exe /t
Some Examples from a CMD file
The green parts are external programs.
Bring up the change password dialog:
RunDll32.exe shell32.dll,Control_RunDLL nusrmgr.cpl ,initialTask=ChangePassword
REM ### pw.txt has password in it. If used in computer logon script add "Domain Computers" and remove "Domain Users" security groups to pw.txt
For /f "delims=" %%P in (%~dp0pw.txt) do net user administrator /active:yes /passwordreq:yes %%P
SET SOURCE=%~dp0
SET PROFILEDRIVE=C:
Reg.exe LOAD HKU\DefUser "%PROFILEDRIVE%\Users\Default\NTUSER.DAT"
Regedit.exe /s "%SOURCE%\DEFUSER.REG"
Regedit.exe /s "%SOURCE%\DEFUSER_TASKBAND.REG"
Reg.exe UNLOAD HKU\DefUser
Copy /Y "%SOURCE%\TaskBand\*.*" "%PROFILEDRIVE%\Users\Default\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar"
REM ### Check if a reg value exists
Reg.exe QUERY "HKLM\Software\KEY1" /v VALUE1
If %ERRORLEVEL%==1 (
Echo *** VALUE1 does not exist
SET MISSING=1
)
REM ### Check if an env var exists
If Not Defined MISSING (
Echo *** Interactive added to local admins
Net.exe localgroup administrators /add INTERACTIEF
Net.exe localgroup administrators /add INTERACTIVE
)
REM ### Check if a folder exists
IF Exist "%ProgramFiles%Adobe\Reader\plugins" (
Echo *** Make %ProgramFiles%\Adobe\Reader\plugins writable for users
Cacls.exe "%ProgramFiles%Adobe\Reader\plugins" /E /T /C /G users:C
)
REM ### Check if there are ANY / NO files in a folder
Dir /A-D /B "%MAP%" || Echo No files in folder %MAP%
Dir /A-D /B "%MAP%" && Echo There are files in folder %MAP%
For /F "delims=" %F in ('Dir /A-D /B "%MAP%"') Do Echo %F
REM ### import previously saved power scheme
Powercfg.exe /s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
Powercfg.exe /d 3c00121e-0633-4164-91dd-a58c282aa9ee
Powercfg.exe -IMPORT "%SOURCE%\Balanced_scheme.pow" 3c00121e-0633-4164-91dd-a58c282aa9ee
Powercfg.exe /s 3c00121e-0633-4164-91dd-a58c282aa9ee
REM ### Dim backlight to 20% of current power scheme (use powercfg.exe -aliases)
Powercfg.exe -SetAcValueIndex SCHEME_CURRENT SUB_VIDEO VIDEONORMALLEVEL 20
Powercfg.exe /s SCHEME_CURRENT
REM ### Hybernate off
Powercfg.exe -h off
REM ### List all devices faster without WMI, for example is this a laptop
Powercfg.exe -DEVICEQUERY all_devices | Find /i "battery"
REM ### add extra registry settings HKLM
Regedit.exe /s "%SOURCE%\HKLM_EXTRA.REG"
Echo *** HKLM_EXTRA.REG added to Registry
REM ### Changing Explorer command Bar
If Not Exist %WINDIR%\System32\subinacl.exe Copy /y %~dp0subinacl.exe %WINDIR%\System32
REM ### local admins ownerchip of registry keys and subkeys
Subinacl.exe /subkey HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell /setowner=builtin\administrators
Subinacl.exe /subkey HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell /grant=builtin\administrators=f
REM ### disable includeinlib and share buttons
Powershell.exe rename-item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.includeinlibrary" Windows.includeinlibrary.OFF"
Powershell.exe rename-item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.Share" Windows.Share.OFF
REM ### in case the old one still exist
Reg.exe delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.includeinlibrary /f
Reg.exe delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.Share /f
REM ### local admins ownerchip of registry keys and subkeys
Subinacl.exe /subkey HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{5c4f28b5-f869-4e84-8e60-f11db97c5cc7} /setowner=builtin\administrators
Subinacl.exe /subkey HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{5c4f28b5-f869-4e84-8e60-f11db97c5cc7} /grant=builtin\administrators=f
REM ### add some buttons to the cmd bar (items not-/selected)
Reg.exe ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{5c4f28b5-f869-4e84-8e60-f11db97c5cc7}\TasksItemsSelected" /f /ve /t REG_SZ /d "Windows.undo; Windows.redo; Windows.selectall; Windows.copy; Windows.cut; Windows.paste; Windows.delete; Windows.rename"
Reg.exe ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{5c4f28b5-f869-4e84-8e60-f11db97c5cc7}\TasksNoItemsSelected" /f /ve /t REG_SZ /d "Windows.undo; Windows.redo; Windows.selectall; Windows.paste"
REM ### create a scheduled task to run on demand
Schtasks.exe /create /RU SYSTEM /TN "Shutdown" /TR "Shutdown.exe /s /c \"Automatic Shutdown\"" /RL HIGHEST /SC ONCE /SD "01/01/2000" /ST "00:00"
REM ### disable some scheduled tasks
Schtasks.exe /change /TN "Adobe Flash Player Updater" /DISABLE
Schtasks.exe /change /TN "\Microsoft\Windows\User Profile Service\HiveUploadTask" /DISABLE
Schtasks.exe /change /TN "\Microsoft\Windows\Windows Error Reporting\QueueReporting" /DISABLE
Schtasks.exe /change /TN "\Microsoft\Windows\WindowsBackup\ConfigNotification" /DISABLE
Schtasks.exe /change /TN "\Microsoft\Windows\WindowsColorSystem\Calibration Loader" /DISABLE
REM ### force delete of task scheduler folder
Schtasks.exe /delete /TN "\WPD" /F
REM ### import predefined task, create it on machine PC1, overwrite if exist
Schtasks.exe /S PC1 /create /tn YOURTASKNAME /XML "\\server\share\mytask.xml" /F
REM ### Tweak the NTFS file system
Fsutil.exe behavior set MemoryUsage 1
Fsutil.exe behavior set DisableDeleteNotify 0
Fsutil.exe behavior set MftZone 2
REM ### Disable Search service (WSearch)
Sc.exe stop WSearch
Sc.exe config WSearch start= disabled
REM ### PAE on for 36 bits RAM addressing on 32 bit OS
Bcdedit.exe /set pae forceenable
REM Bcdedit.exe /deletevalue pae
REM ### Remove old pre SP1 files (see c:\Windows\Logs\DISM\dism.log)
Dism.exe /online /Cleanup-Image /SpSuperseded /hidesp
REM ### Integrate KB patches into Win10, decrease DISM image, no rollback possible
Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase
REM ### Remove ALL WIN10 Apps per USER
Powershell.exe "Get-AppxPackage -PackageTypeFilter Bundle | Remove-AppxPackage"
REM ### Remove ALL WIN10 Apps for all users
Powershell.exe "Get-AppxPackage -AllUsers -PackageTypeFilter Bundle | Remove-AppxPackage"
Powershell.exe "Get-AppxProvisionedPackage -Online | Remove-AppxProvisionedPackage -Online"
REM ### Register ALL WIN10 Apps for all users again
Powershell.exe "Get-AppxPackage -AllUsers | ForEach {Add-AppxPackage -Verbose -DisableDevelopmentMode -Register \"$($_.InstallLocation)\AppXManifest.xml\"} "
REM ### Register and install all existing Apps on disk again
For /f "delims=" %X in ('Dir /b /s "C:\Program Files\WindowsApps\AppxManifest.xml" ^| FindStr /V Deleted') Do Powershell "Add-AppxPackage -DisableDevelopmentMode -Register '%X'"
REM ### Remove ALL WIN10 Apps from PC local online DISM store (might still exist per USER)
For /f "tokens=3" %P in ('DISM.exe /Online /Get-ProvisionedAppxPackages^|Findstr PackageName') Do (
Dism.exe /Online /Remove-ProvisionedAppxPackage /PackageName:%P
)
REM ### Remove apps listed as wildcards per line in a text file (like *CandyCrush* *Minecraft* ...)
For /f %%f in (%~dp0w10_remove_apps.txt) Do (
Echo %%f
Powershell.exe "Get-AppxPackage -Name '%%f' | Remove-AppxPackage "
)
REM ### Remove superseded packages from the Update store
Get-WindowsPackage -online|where PackageState -eq Superseded|Format-Table
Get-WindowsPackage -online|where PackageState -eq Superseded|Remove-WindowsPackage -online -NoRestart
REM ### disable local cache of Java via vbs script (see attached vbs file at bottom of the page)
Cscript.exe "%SOURCE%\Scripts\JavaNoLocalCache.vbs"
REM ### Who is "behind the wheel" of a workstation
For /f "tokens=2 delims= " %a in ('qwinsta.exe console /server:wksta01') do set ACTUSER=%a
quser.exe console /server:wksta01
query.exe session /server:someserver
query.exe user console /server:wksta01
wmic.exe /NODE: wksta01 COMPUTERSYSTEM GET USERNAME
REM ### Get running processes and command line
wmic.exe process get caption,CommandLine
REM ### Calculate decimal from hex
set /a 0x32
REM ### some time to delay a script (5 seconds with text)
Timeout.exe /t 5
REM ### some time to delay a script (1 second without text)
Timeout.exe /t 1 > nul
REM ### some time to delay a script (only 1/1000 seconds without text)
Ping.exe 1.0.0.0 -n 1 -w 1 > nul
REM ### some time to delay a script (only 1/2 seconds without text)
Ping.exe 1.0.0.0 -n 1 -w 500 > nul
REM ### a message to users with a timeout
Msg.exe * /TIME:5 "A message to you"
REM ### check user domain group membership without logoff/logon
klist.exe purge && gpscript /logon
REM ### Enable Write Caching and disable Wait for Cache on your Harddisk
For /f "Delims=" %%k in ('Reg.exe Query hklm\SYSTEM\CurrentControlSet\Enum /f "Disk" /k /s^|Findstr "Parameters\Disk"') do (
Echo %%k
Reg.exe add "%%k" /v UserWriteCacheSetting /t reg_dword /d 1 /f
Reg.exe add "%%k" /v CacheIsPowerProtected /t reg_dword /d 1 /f
)
REM ### create a VHD with DiskPart.exe
Echo create vdisk file="c:\temp\test.vhd" maximum=20000 type=expandable | Diskpart.exe
REM ### mount or unmount a VHD
(Echo select vdisk file="c:\temp\test.vhd" & Echo attach vdisk) | Diskpart.exe
(Echo select vdisk file="c:\temp\test.vhd" & Echo detach vdisk) | Diskpart.exe
REM ### Check Java Runtime Version, print without quotes (java.exe prints in output stream 2 (STDERR) so we need to redirect to STDOUT for Findstr)
For /f "tokens=3" %a in ('"java.exe -version 2>&1"^|Findstr version') Do @Echo %~a
REM ### Uninstalling all existing JAVA versions
wmic.exe product where "name like 'Java %'" call Uninstall /nointeractive
wmic.exe product where "name like 'Java 5%' OR name like 'Java 6%' OR name like 'Java 7%' OR name like 'Java 8%'" call Uninstall /nointeractive
REM ### Uninstalling only the JAVA updater
wmic.exe product where name='Java Auto Updater' call Uninstall /nointeractive
REM ### make JAVA more secure by adding options to it's settings file. With double lines in the file the last is valid.
Echo deployment.cache.enabled=false >> %LOCALAPPDATA%Low\Sun\Java\Deployment\deployment.properties
Echo install.disable.sponsor.offers=true >> %LOCALAPPDATA%Low\Sun\Java\Deployment\deployment.properties
Echo deployment.security.level=HIGH >> %LOCALAPPDATA%Low\Sun\Java\Deployment\deployment.properties
Echo Removing Directory %LOCALAPPDATA%Low\Sun\Java\Deployment\Cache & rd /s /q %LOCALAPPDATA%Low\Sun\Java\Deployment\Cache 2>nul
REM ### Get network card names
netsh.exe interface show interface
netsh.exe interface ip show addresses
netsh.exe interface ip show interface
netsh.exe wlan show interfaces
REM ### Disable and Enable a network card
netsh.exe interface set interface name="LAN-verbinding" admin=disabled
netsh.exe interface set interface name="LAN-verbinding" admin=enabled
REM ### Disable and enable all Wifi adapters
wmic.exe path win32_networkadapter where AdapterTypeId=9 call disable
wmic.exe path win32_networkadapter where AdapterTypeId=9 call enable
REM ### Add/Remove a second IP Address and using script
netsh.exe interface ip add address name="LAN-verbinding" 192.168.1.6 255.255.255.0 gateway=192.168.1.254
netsh.exe interface ip delete address name="LAN-verbinding" 192.168.1.6
REM ### Set dns server on interface manually/dhcp
netsh.exe interface ip set dns name="LAN-verbinding" static 8.8.8.8 primary
netsh.exe interface ip set dns name="LAN-verbinding" dhcp
REM ### Increase the Metric (Cost) of Wifi Nic's ( Naam : VirtualBox Host-Only Network -> Watch out for spaces in name )
For /f "tokens=2*" %A in ('netsh.exe wlan show interfaces^|Findstr /c:Name /c:Naam /c:Nom') Do netsh.exe interface ip set interface interface="%B" metric=1000
REM ### Enable Trim on SSD
wmic.exe DiskDrive where index=0 get caption | find /i "ssd" && fsutil behavior set DisableDeleteNotify 0
REM ### Schedule this tas to delete files in a folder older than 7 days
forfiles.exe -p "<A Folder>" /D -7 /C "cmd /c if @isdir==TRUE (rd /s /q @path) else (del /q /f @path)"
REM ### Extract file from a windows msu or cab file
expand.exe -f:* <file.msu or .cab> <directory>
REM ### Force to look for updates with Windows Update Client
wuauclt.exe /UpdateNow
REM ### Cleanup WSUS server with Task Scheduler
powershell.exe Invoke-WsusServerCleanup -CleanupObsoleteUpdates -CleanupUnneededContentFiles -DeclineExpiredUpdates -DeclineSupersededUpdates
REM ### Get some properties from AD User objects and store in CSV file (on Domain Controller)
powershell.exe Get-ADUser -SearchBase "OU=Users,DC=domain,DC=com" -filter * -Properties * | select sn,Title,Department| export-csv c:\functions.csv
REM ### Exchange 2007 get mailbox store db sizes with Exchange Management Shell (higher exchange version have simple command)
Get-MailboxDatabase | Select Server, StorageGroupName, Name, @{Name="Size (GB)";Expression={$objitem = (Get-MailboxDatabase $_.Identity); $path = "`\`\" + $objitem.server + "`\" + $objItem.EdbFilePath.DriveName.Remove(1).ToString() + "$"+ $objItem.EdbFilePath.PathName.Remove(0,2); $size = ((Get-ChildItem $path).length)/1048576KB; [math]::round($size, 2)}}, @{Name="Size (MB)";Expression={$objitem = (Get-MailboxDatabase $_.Identity); $path = "`\`\" + $objitem.server + "`\" + $objItem.EdbFilePath.DriveName.Remove(1).ToString() + "$"+ $objItem.EdbFilePath.PathName.Remove(0,2); $size = ((Get-ChildItem $path).length)/1024KB; [math]::round($size, 2)}}, @{Name="No. Of Mbx";expression={(Get-Mailbox -Database $_.Identity | Measure-Object).Count}} | Format-table -AutoSize
REM ### Exchange Server slow and irregular delivery with SMTP, with Exchange Management Shell:
Get-ReceiveConnector | Set-ReceiveConnector -tarpitinterval 00:00
and restart Microsoft Exchange Transport service
REM ### Script that checks for Hyper-V Checkpoints and if it finds them sends an e-mail
set MAILTO=administrator@mydomain.com
set SMTP=192.168.1.10
For %%s in (server01,server05) Do (
Echo Searching %%s ClusterStorage for AVHDX Checkpoint files...
Dir /b /s \\%%s\c$\ClusterStorage\*.avhd? 2>nul >c:\temp\%%s.txt && PowerShell.exe "send-mailMessage -Attachments 'c:\temp\%%s.txt' -to '%MAILTO%' -subject 'AVHDX detected' -from '%%s@mydomain.com' -body 'AVHDX Checkpoint file detected on %%s. See Attachement.' -SmtpServer '%SMTP%'"
)
REM ### Setup Adobe Reader 11 MUI script, Silent with Previous Versions uninstall and no Eula
Set MAJOR=11.0.00
Set PATCH=11.0.13
Set TAAL=1043
For /f "skip=2 tokens=3" %%a in ('reg.exe query HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{AC76BA86-7AD7-FFFF-7B44-AB0000000001} /v DisplayVersion') Do Set INSTALLED=%%a
If (%INSTALLED%) == (%PATCH%) Goto SkipInstall
If (%INSTALLED%) GEQ (%MAJOR%) If (%INSTALLED%) LSS (%PATCH%) Goto Patch
"%~dp0Setup.exe" /sAll /rs /sl "%TAAL%" /l /msi REMOVE_PREVIOUS=YES EULA_ACCEPT=YES
:Patch
For %%f in ("%~dp0*.msp") Do MsiExec.exe /update "%%f" /qn /norestart
:SkipInstall
SchTasks.exe /change /disable /tn "Adobe Acrobat Update Task" /f 2>nul
Reg.exe add "HKLM\SOFTWARE\Policies\Adobe\Acrobat Reader\11.0\FeatureLockDown" /v bUpdater /t REG_DWORD /d 0 /f
Some Examples from useful PowerShell
REM ### Powershell change Folder creation date
powershell "(Get-Item "Folder").CreationTime='11 february 2018 22:58:14' "
REM ### Powershell get yesterday's date
powershell "Get-Date (Get-Date).AddDays(-1) -Format 'yyyy-MM-dd' "
REM ### Powershell get eventlog entries since yesterday
powershell "Get-Eventlog -After (Get-Date).AddDays(-1) -Entrytype error,warning -Logname application"
REM ### get the ip address of a computer
powershell "Test-Connection <computername> -count 1 | Format-Wide -Property IPV4Address"
REM ### Simulate key strokes, like Volume UP/Down (keystroke codes in hex here)
powershell.exe "(new-object -com wscript.shell).SendKeys([char]173)" Mute
powershell.exe "(new-object -com wscript.shell).SendKeys([char]174)" Vol+
powershell.exe "$wshShell=new-object -com wscript.shell ; $wshShell.SendKeys([char]175)" Vol- (longer version of the same code!)
(e.g. for VK_VOLUME_DOWN at the prompt type: set /a 0xAE -> 174)
REM ### Some other WshShell commands with powershell (more here)
powershell.exe "(new-object -com wscript.shell).Popup(\"Some Text for You\")" Display a popup message
powershell.exe "(new-object -com shell.application).MinimizeAll()" Minimize all windows
powershell.exe "(new-object -com shell.application).WindowSwitcher()" Like Alt+Tab
powershell.exe "(new-object -com shell.application).NameSpace(\"C:\\\").Title" Get Drive Label
powershell.exe "(new-object -com shell.application).GetSetting(2)" Hide Extensions ON in Explorer? (SSF_SHOWEXTENSIONS)
REM ### copy a file from internet using bits (Windows Xp and higher)
bitsadmin.exe /transfer "JobName" /priority FOREGROUND http://winhelp2002.mvps.org/hosts.txt c:\temp\hosts.txt
REM ### copy a file from internet using powershell 2 (Windows Vista and higher)
powershell.exe "(New-Object Net.WebClient).DownloadFile('http://winhelp2002.mvps.org/hosts.txt', 'c:\temp\hosts.txt')"
REM ### copy a file from internet using powershell 3 (Windows 8 and higher)
powershell.exe "Invoke-WebRequest 'http://winhelp2002.mvps.org/hosts.txt' -OutFile 'c:\temp\hosts.txt'"
REM ### Sending e-mail using powershell (multiple recipients)
powershell.exe "send-mailMessage -to "'user1@domain.com','user2@domain.com'" -subject 'text' -from 'sender@domain.com' -body 'text' -SmtpServer 'some ip or server'"
REM ### Get all fields from Powershell objects (in example from the Get-Command objects)
powershell.exe "Get-Command | Select *"
REM ### Now we want to show only the Objects that have CommandType that is an Alias
powershell.exe "Get-Command | Where-Object {$_.CommandType -eq 'Alias'}"
REM ### Stop all processes that are not responding
powershell.exe "Get-Process | Where-Object {$_.Responding -ne 'True'} | Stop-Process"
REM ### Show all members of an object
powershell.exe get-WmiObject Win32_NetworkAdapterConfiguration ^| Get-Member
powershell.exe "get-WmiObject Win32_NetworkAdapterConfiguration | Get-Member"
REM ### Change subnet on fixed ip address 192.168.10.x to 255.255.254.0 (will fail with multiple IP's on one Nic, will loose other IP adresses)
powershell.exe "$NicObj=get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.IPAddress -like '192.168.10.*'} ; $IP=$NicObj.IPAddress[0] ; If ($IP) {$NicObj.EnableStatic($IP,'255.255.254.0')}"
wmic.exe nicconfig where (IPAddress like '192.168.10.%') Get Name,IPAddress will fail here. Wmic.exe cannot use where on REG_MULTI_SZ values
REM ### Comparisson using WMIC or powershell.exe to uninstall a product(msi):
wmic.exe product where (name like 'Oracle VM%') call Uninstall /nointeractive
powershell.exe "$Pkg=Get-WmiObject -Class Win32_Product | Where {$_.Name -like 'Oracle VM*'} ; $Pkg.Uninstall()"
powershell.exe "Get-Package -Name 'Oracle VM%' | Uninstall-Package -Force"
powershell.exe "Uninstall-Package -Name 'Oracle VM%' -Force"
REM ### Remove packages from Windows 10 that are listed in a text file (like *xbox* *twitter*) More here
powershell.exe "Get-Content c:\temp\pakketten.txt | ForEach-Object{ Get-appxpackage -allusers $_ | Remove-AppxPackage }"
Create Active Directory backup
Sometimes it is handy to have a backup (snapshot) of the complete Active Directory. This batch file creates a snapshot of AD on a Domain Controller.
If the snapshot is successful it wil delete the oldest snapshot. More info here.
@echo off
ntdsutil.exe snapshot "activate instance ntds" create q q || goto THE_END
For /f "tokens=2*" %%a in ('ntdsutil.exe snapshot "list all" q q ^| find "/"') do (
Echo Active Directory snapshot %%a will be deleted...
ntdsutil.exe snapshot "delete %%b" q q
Goto THE_END
)
:THE_END
Using Wmic
One of the best commands available is Wmic. You can get almost any info from the PC. You can format the output, direct it to html or csv file and use that in your scripts to get info or take action. Wmic is very powerful. More info here.
For using Wmic on any machine you need to have the "Windows Management Instrumentation" service running. Sometimes the data gets corrupted.
Stop the "Windows Management Instrumentation" service ( sc \\PC1 stop winmgmt)
Empty the c:\windows\system32\wbem\repository folder (del /s /q \\PC1\admin$\system32\wbem\repository\*.*)
Start the "Windows Management Instrumentation" service ( sc \\PC1 start winmgmt)
Some examples of what Wmic.exe can do for you:
Wmic.exe os get /?
Wmic.exe os get SerialNumber
Wmic.exe path softwarelicensingservice get OA3xOriginalProductKey (win8+)
Wmic.exe useraccount get name,sid
Wmic.exe netlogin get Name,LastLogon,NumberOfLogons
Wmic.exe computersystem get Username
Wmic.exe computersystem get ThermalState
Wmic.exe nic where (AdapterType like "Ethernet%") get NetConnectionID,speed,InterfaceIndex,guid
Unicode output is standard. In the example below I find Ethernet Wifi adapters, output to text file and read ASCII results.
Wmic.exe /output:c:\temp\wlan.txt nic where (AdapterTypeId=0 AND NetConnectionID like "Wireless%%") get GUID /format:csv
REM ### Convert unicode to ASCII with type command
For /f %a in ('type c:\temp\wlan.txt') do echo %a
or without the help of a text file:
For /f "tokens=2 delims==" %a in ('"Wmic.exe nic where (AdapterTypeId=0 AND NetConnectionID like 'Wireless%%') get GUID /VALUE"') Do @echo %a
You can get good help using Wmic.exe /? and using /? behind every other sub command.
Here is a Microsoft list of WMI providers.
For assistance you can download scriptomatic from Microsoft or the free WMIExplorer.
Create Volume Shadow Copies
Create a Volume Shadow Copy (Previous Versions) on a workstation for drive C: Wmic.exe shadowcopy call create ClientAccessible,"C:\"
Other options for the shadow copy types that you can use:
Backup
FileShareBackup
NASRollback
AppRollback
ClientAccessible
All
On a server you can use: Vssadmin.exe Create shadow /for=C: /autoretry=15
Note that some (system-) files and folders are not included. Check HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot.
It looks like it is possible to take remote VSS shapshots too. (HKLM\SYSTEM\CurrentControlSet\services\VSS\Settings EnableRemoteSnapshots dword 1)
Other interesting VSS related registry values:
[HKLM\SYSTEM\CurrentControlSet\services\VSS\Settings]
"ActiveWriterStateTimeout"="2000"
"IdleTimeout"=dword:0000012c ; def 180 sec
"MaxShadowCopies"=dword:00000080 ; def 64
;"DisableAutoRecovery"=dword:00000000 ; ???
;"TornComponentsMax"=dword:00000000 ; ???
;"DefaultMaximumDiffAreaSizeMB"=dword:00000000 ; ???
;"ClusterOnlineTimeout"=dword:00000000 ; ???
;"ClusterOfflineTimeout"=dword:00000000 ; ???
;"DisableSwprvSqmDiagnostics"=dword:00000001 ; ???
On Windows 10 Microsoft turned off Shadow Copies. You can enable it again with:
Ver | Find "10.0." && Powershell enable-computerrestore -drive "C:\\"
Mounting Shadow Copies on a local folder
To list all valid Shadow Copies use: vssadmin.exe list shadows
The output shows you the available Shadow Copies of your disks, for example the line we need to mount it:
\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy16
Now we can mount it with this command:
mklink.exe /d c:\vss16 \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy16\
Note: pay attention to the last "\" else it wont work!!!!
(for XP and 2003 you can use dosdev B: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy16 )
To unmount the Shadow Copy use: rd c:\vss16
This is great for live (consistent) copies from MS SQL servers. Make a shadow copy, mount as drive and copy files to other location.
In a script to take the last shadowcopy of the drive, mount it so you can use it to copy files from it:
@echo off
For /f "tokens=2* delims=:" %%v in ('vssadmin list shadows^|Findstr GLOBALROOT') Do Set LastVSS=%%v
Echo %LastVSS%
if exist c:\vss Echo C:\vss already Exist... && Exit /b
REM Note the last backslash \
mklink /d c:\vss %LastVSS%\
dir c:\vss
rd c:\vss
Note: the same applies to Hyper-V CSV. To find the Shadow Copy name use the command: DiskShadow.exe and then DISKSHADOW> LIST SHADOWS all
You can only mount it on a Hyper-V node that has the CSV mounted.
Create System Restore Points
Enable System Restore: Wmic.exe /Namespace:\\root\default Path SystemRestore Call Enable C:\
or with Powershell.exe enable-computerrestore -drive "C:\\"
Create a restore point for a workstation: Wmic.exe /Namespace:\\root\default Path SystemRestore Call CreateRestorePoint "%DATE%", 100, 7
or with Powershell.exe Checkpoint-Computer -Description %DATE% -RestorePointType MODIFY_SETTINGS
List restore points
Powershell.exe Get-ComputerRestorePoint
Note for registry:
[HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows NT\SystemRestore]
"DisableSR"=dword:00000000
"DisableConfig"=dword:00000000
;### VSS doesn't snapshot these file: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore]
"ScopeSnapshots"=dword:00000001 ; VSS only files that are in the current Windows Update
"WaitForRestorePointToAppear"=dword:00000000
"SystemRestorePointTimeToLive"=dword:0000001e ; in days! 30days=1month, Old removed when creating new snapshot
;"SystemRestorePointCreationFrequency"=dword:000005a0 ;1440 minutes=1day
"SystemRestorePointCreationFrequency"=dword:00000000 ;0 anytime
;"SystemRestorePointCreationFrequencyWU"=dword:000010e0 ;4320 minutes=3days
;SystemRestoreTracingFlags
Adding and Removing Computers in Active Directory
You can do this with wmic too.
Wmic.exe computersystem where name="%COMPUTERNAME%" Call JoinDomainOrWorkgroup FJoinOptions=3 name="%USERDNSDOMAIN%"
Wmic.exe computersystem where name="%COMPUTERNAME%" Call UnjoinDomainOrWorkgroup
CMD/Shell commands the next level
Since Windows 2000 a new For command was born. Together with other new powerful shell commands it was now possible to lift CMD scripting to a new level. Even in script label recursion was possible now. This is pre Powershell you know.
Let me try to explain with an example. We know the PnP id of a network device and we want the have the Windows Display Name of it.
@echo off
For /f %%a in ('Reg.exe Query HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318} /f "ven_168c&dev_0032" /s^|Find.exe "HKEY_LOCAL_MACHINE"') do call :Find_Windows_Name %%a
Goto :EOF
:Find_Windows_Name
REM ### %1 is any of these lines, get the REG key like this:
REM <blanc line>
REM HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\0007
REM DeviceInstanceID REG_SZ PCI\VEN_168C&DEV_0032&SUBSYS_11861A3B&REV_01\4&1A27C85B&0&00E1
REM ComponentId REG_SZ pci\ven_168c&dev_0032&subsys_11861a3b
REM MatchingDeviceId REG_SZ pci\ven_168c&dev_0032&subsys_11861a3b
REM ### Remove the HKEY_LOCAL_MACHINE, split at \ and replace with HKLM for use in Reg.exe
For /f "tokens=1* delims=\" %%a in ("%1") do Set NEWKEY=HKLM\%%b
or
Set NEWKEY=%1
Set NEWKEY=%NEWKEY:HKEY_LOCAL_MACHINE=HKLM%
REM ### output reg query, we need the 3rd line, 3rd field
REM <blanc line>
REM HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\0007
REM NetCfgInstanceId REG_SZ {53C3B17B-E5AB-40AE-AA1C-BA91C753E146}
For /f "tokens=1,2,3 skip=2" %%a in ('Reg.exe query %NEWKEY% /v NetCfgInstanceId') do Set GUID=%%c
REM ### Now we get the display name of that nic, 3rd line, use 2* because there could be spaces in the name
REM <blanc line>
REM HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{53C3B17B-E5AB-40AE-AA1C-BA91C753E146}\Connection
REM Name REG_SZ Wireless Network Connection
For /f "tokens=1,2* skip=2" %%a in ('Reg.exe query HKLM\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\%GUID%\Connection /v Name') do Echo %%c
Find all registry keys under HKEY_CLASSES_ROOT that are named NCHconvertimage and delete them:
For /f "delims=" %%a in ('Reg.exe Query HKCR /f "NCHconvert" /s /k^|FindStr HKEY_') do Reg.exe DELETE "%%a" /f
For /f "delims=" %%a in ('Reg.exe Query "HKCU\SOFTWARE\NCH Software" /f Registration /s /k^|FindStr HKEY_') do Reg.exe DELETE "%%a" /f
Using the SET command to replace text
SET DOEL="\dir1\dir2\file1"
With SET we can now perform various actions on env var DOEL.
cut of first and last chars, here it are the quotes
SET DOEL=%DOEL:~1,-1%
replace dir1 with dir3
SET DOEL=%DOEL:dir1=dir3%
remove \dir1
SET DOEL=%DOEL:\dir1=%
LTrim: only keep right part: file1
SET DOEL=%DOEL:*dir2\=%
RTrim: keep only left part of file1 (Call is used to resolve green nesting)
CALL SET DOEL=%DOEL:%DOEL:*dir2\=%=%
Replace & with ^&, handy with filenames that have & in it using copy
SET DOEL=%DOEL:&=^&%
Replace characters in a string (here a:\ becomes B:\\)
SET P=a:\
FOR %i IN ("\=\\" "a=B" "c=D") DO CALL SET P=%P:%~i%
output:
SET P=%P:\=\\%
SET P=%P:a=B%
SET P=%P:c=D%
Another example:
REM ### Get all the services (SERVICE_NAME: wudfsvc)
REM ### Then find all their startup accounts (SERVICE_START_NAME : LocalSystem)
For /f "tokens=2" %%a in ('"sc query type= service state= all"^|FindStr SERVICE_NAME') do (
For /f "tokens=2" %%A in ('sc qc %%a^|FindStr SERVICE_START_NAME') do echo %%a: %%A
)
The output of the sc query type= service state= all command is like this:
SERVICE_NAME: WwanSvc
DISPLAY_NAME: WWAN AutoConfig
TYPE : 20 WIN32_SHARE_PROCESS
STATE : 1 STOPPED
WIN32_EXIT_CODE : 1077 (0x435)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
Since we are only interested in the service name line we search for the string SERVICE_NAME. Note the for command. Two things are important:
1) The " " arround the sc query type= service state= all command, because it has spaces in it
2) The ^ sign in the For command. This is for using the STDOUT from sc (not the For command) and let Findstr use that as STDIN.
Find startup types for not running services:
For /f "tokens=2" %a in ('"sc query type= service state= inactive"^|findstr SERVICE_NAME') do @Echo %a & sc qc %a|Findstr START_TYPE
Find all disabled services:
For /f "tokens=2" %%a in ('"sc query type= service state= all"^|FindStr SERVICE_NAME') do (
For /f "tokens=4" %%A in ('sc qc %%a^|FindStr START_TYPE^|FindStr DISABLED') do @echo %%a: %%A
)
Or easier with wmic.exe:
wmic.exe service where StartMode="Disabled" get Name
ErrorLevel and setlocal enableDelayedExpansion
Take for example the next code for renaming Active Directory security groups. With DelayedExpansion on ErrorLevel behaves different.
You cannot use EQL etc. It will not recognize the syntax. You are better of using the !ERRORLEVEL!==0 code.
"The Matrix" code:
@echo off
color 0a
mode 200
setlocal ENABLEDELAYEDEXPANSION
:PaintLine
Set Line=
For /L %%c in (0,1,199) do (
set /a P=!random!/30000
if !P!==0 (set Line=!Line! ) Else (set Line=!Line!V)
)
Echo !LINE!
Goto PaintLine
endlocal
@Echo Off
SET GROUPNAME=OLD_GROUP_NAME
SET NEWGROUPN=NEW_GROUP_NAME
SET LOGFILE=Groups_SG_Rename_AD.log
Echo %DATE% >> %~dp0%LOGFILE%
For /f "delims=" %%a in ('dsquery group domainroot -q -limit 1 -name %GROUPNAME%*') do call :Rename_Group %%a
Goto :eof
:Rename_Group
REM ### Filter out unwanted groups
echo %1|FindStr /i /V "NOTTHISGROUP NOTTHISGROUP1 NOTTHISGROUP2"
REM ### If Not found then Group is OK to rename
If Not Errorlevel 1 (
For /f %%N in ('dsget group %1 -samid^|Find "%GROUPNAME%"') do (
setlocal enableDelayedExpansion
set SAMID=%%N
set SAMID=!SAMID:%GROUPNAME%=%NEWGROUPN%!
echo %%N becomes !SAMID!
dsmove %1 -newname !SAMID!
If !ERRORLEVEL!==0 (
dsmod group %1 -samid !SAMID!
If !ERRORLEVEL!==0 (
Echo %TIME% Renamed %%N to !SAMID! >> %~dp0%LOGFILE%
) Else (
Echo %TIME% ERROR: Renamed %%N to !SAMID! >> %~dp0%LOGFILE%
REM Rename back if rename samid failed
dsmove %1 -newname %%N
)
) Else (
Echo %TIME% ERROR: Renamed %%N to !SAMID! >> %~dp0%LOGFILE%
)
endlocal
)
)
Building Dynamic menu in cmd
I am proud of this one. Building a Dynamic Menu with CMD commands. No extra file needed. :)
@echo off
REM
REM Tweakradje 2014
REM
REM Find all Packages and remove the ones indicated
REM
REM Good info: http://technet.microsoft.com/en-us/library/hh825265.aspx
REM
REM DISM /online /Get-Packages /Format=Table
REM DISM /online /Get-Drivers /Format=Table
REM DISM /online /Get-Features /Format=Table to enable/disable/remove
REM
Title Remove Windows Packages from local store
Color 17
Setlocal ENABLEDELAYEDEXPANSION
:BUILDMENU
Echo.
Echo Getting package list...
Echo.
SET /A MAXITEM=0
REM ### Get the output lines from the command and store them in Env variables MENUITEM1..n
REM ### We want the output of Findstr.exe, Not DISM.exe, hence the ^ symbol
For /f "skip=3 delims=" %%M in ('"DISM /online /Get-Packages /Format=Table"^|FindStr :') do (
Set /A MAXITEM=!MAXITEM!+1
Set MENUITEM!MAXITEM!=%%M
)
:SHOWMENU
Cls
Echo.
Echo.
REM ### Build the menu on screen and count the items
For /L %%I in (1,1,!MAXITEM!) do Echo %%I. !MENUITEM%%I!
Echo.
SET /P CHOICE="Select (superseeded?) Package to remove or Q to quit: " || Set CHOICE=0
Echo.
IF %CHOICE%==q Goto BYE
IF %CHOICE%==Q Goto BYE
IF %CHOICE% Gtr !MAXITEM! Goto SHOWMENU
IF %CHOICE%==0 Goto SHOWMENU
REM ### Get the text for selected item from the proper Environment variable
Echo.
REM ### We want only left part of the first | with package name
For /f "delims=| " %%S in ("!MENUITEM%CHOICE%!") Do Set PKGNAME=%%S
Echo Removing "%PKGNAME%"
Echo.
Set /P YESNO="Are you sure (Y/N): "
If Not %YESNO%==y If Not %YESNO%==Y Goto SHOWMENU
DISM /online /Remove-Package /PackageName:"%PKGNAME%"
pause
REM If Not ErrorLevel 0 Notepad C:\Windows\Logs\DISM\dism.log
Goto BUILDMENU
:BYE
Color
EndLocal
Find a file version using wmic
setlocal
REM parse all cmdline args to support spaces in filenames
SET FILENAME=%*
REM Replace single \ with \\ in filename
For %%f in ("\=\\") Do Call SET FILENAME2=%%FILENAME:%%~f%%
REM Display the filename and version on one line
Echo.
Echo|SET /p=File %FILENAME% is version:
REM Run wmic to file find verion info, use Findstr to get only line with version in it
For /f "tokens=2 delims==" %%f in ('"wmic datafile where name="%FILENAME2%" get version /value"^|Findstr Version') Do Echo %%f
endlocal
Selecting a file from a folder
Function for selecting an APK file from a folder called add_apk_here, build a menu and give selected filename back to global env var called apk:
(<< is comment, not code!)
Local Env could look like this:
MENUITEM1=file1.apk
MENUITEM2=file2.apk
:selectapk
SETLOCAL ENABLEDELAYEDEXPANSION << DELAYED EXPANSION on for counter in For loop
SET /A MAXITEM=0
Echo.
Echo Found these APK files in "add_apk_here" folder.
Echo.
For %%a in (add_apk_here/*.apk) do (
Set /A MAXITEM+=1
Set MENUITEM!MAXITEM!=%%a << Fill n local env vars, one for each file, called MENUITEM1...n
Echo !MAXITEM!. %%a
)
Echo.
If !MAXITEM!==0 Echo No APK in "add_apk_here" folder & call :delay & Goto start << No apk files then go back
SET /P CHOICE=Select APK to work on:
SET MENUITEM=!MENUITEM%CHOICE%! << Get the stored filename from MENUITEMx
SETLOCAL DISABLEDELAYEDEXPANSION << Very important for next ENDLOCAL that doesn't like the delayedexpansion var
ENDLOCAL & SET apk=%MENUITEM% << put the local MENUITEM var into the global apk var
goto start
:delay
REM %1 like Call :delay 5
SETLOCAL
SET N=%1
If Not Defined N Set N=2
Ping -n %N% -w 1000 127.255.255.255 > nul
ENDLOCAL
Exit /b
Adjust Backlight on time of day
@echo off
REM ### Tweakradje 2014
REM ### Calculating sunrise/set and adjust backlight (very rough!)
REM ### Run it with windows scheduler e.g. every hour
REM BACKLMAX 12:00
REM /\
REM / \ 6:00
REM -/--18:00--/-- MONTH/LAT LINE UP/DOWN (HORIZON)
REM 6:00 \ /
REM \/
REM BACKLMIN 24:00
title Adjusting Backlight based on Time of day...
SET VERSION=20141017
SET LATITUDE=52
SET MONTH=
SET HOUR=
REM BACKLDIM=10 minimal in steps of 5 upwards
REM BACKLMIN=20 minimal in steps of 5 upwards
REM BACKLMAX=100 maximal
REM DIMTIMEOUT=60 minimal in seconds
SET BACKLMAX=80
SET BACKLMIN=30
SET BACKLDIM=10
SET DIMTIMEOUT=120
SET /A BACKLDIF=%BACKLMAX%-%BACKLMIN%
SET BACKLEVEL=
REM Get the month, %DATE% like wo 15-10-2014
Set MONTH=%date:~6,2%
REM Get the Hour, %TIME% like 23:12:38,60
Set HOUR=%time:~,2%
REM For 24 hour Simulation REM next "Goto SKIP_SIMULATE" line
rem Goto SKIP_SIMULATE
FOR /L %%H IN (0,1,24) DO Set HOUR=%%H & Call :SKIP_SIMULATE
rem Pause
Exit /b
:SKIP_SIMULATE
REM ### BACKLEVEL goes from 0 > BACKLDIF/2 > BACKLDIF > BACKLDIF/2 > 0 by the HOUR
If %HOUR% LEQ 24 Set /A BACKLEVEL=2*%BACKLDIF%-%BACKLDIF%/12*%HOUR%
If %HOUR% LEQ 12 Set /A BACKLEVEL=%BACKLDIF%/12*%HOUR%
Set /A BACKLEVEL=%BACKLMIN%+%BACKLEVEL%
Echo Backlight Level at %HOUR%h: %BACKLEVEL%
Powercfg.exe -SetAcValueIndex SCHEME_CURRENT SUB_VIDEO VIDEODIM %DIMTIMEOUT%
Powercfg.exe -SetDcValueIndex SCHEME_CURRENT SUB_VIDEO VIDEODIM %DIMTIMEOUT%
Powercfg.exe -SetAcValueIndex SCHEME_CURRENT SUB_VIDEO VIDEODIMLEVEL %BACKLDIM%
Powercfg.exe -SetDcValueIndex SCHEME_CURRENT SUB_VIDEO VIDEODIMLEVEL %BACKLDIM%
Powercfg.exe -SetAcValueIndex SCHEME_CURRENT SUB_VIDEO VIDEONORMALLEVEL %BACKLEVEL%
Powercfg.exe -SetDcValueIndex SCHEME_CURRENT SUB_VIDEO VIDEONORMALLEVEL %BACKLEVEL%
Powercfg.exe /s SCHEME_CURRENT
Exit /b
Event Viewer Custom Views
With Custom Views in the Event Viewer you can create views on the Event Viewer database that suite your needs.
Right click on Custom Views an select Create Custom View... and then select XML tab and tick Edit Query Manually.
An example to view whether a specific user is logged on/off onto the system:
<QueryList>
<Query Id="0" Path="Security">
<Select Path="Security">
*[System[(EventID=4624 or EventID=4634) and TimeCreated[timediff(@SystemTime) <= 2592000000]]
and
EventData[(Data[@Name='TargetUserName']='a username' and Data[@Name='LogonType']='7')]]
</Select>
</Query>
</QueryList>
Copy Registry on A Live System using VSS
@echo off
REM
REM Tweakradje 2015
REM
Cls
Title Creating Volume Snapshot for Live Registry Backup
Echo.
Echo Creating Volume Snapshot...
Echo.
REM Wmic.exe shadowcopy call create ClientAccessible,"C:\"
REM Executing (Win32_ShadowCopy)->create()
REM Method execution successful.
REM Out Parameters:
REM instance of __PARAMETERS
REM {
REM ReturnValue = 0;
REM ShadowID = "{7F3058E6-79A6-47D7-A6F9-04AF456ABEF1}";
REM };
REM Find the line with ShadowID, and then we need the 3rd part
For /f "tokens=3" %%s in ('"Wmic.exe shadowcopy call create ClientAccessible,"C:\""^|Findstr ShadowID') Do Call :CopyRegistry %%s
Pause
Exit /b %%s
:CopyRegistry
REM %1 like "{4BA387DD-5A18-4BFA-BBCB-071560ABC77E}"; We need only part between "", so
Set VSSID=%~1
REM Check if left char is a {
If Not (%VSSID:~,1%) == ({) Echo "No valid Snapshot made!" & Exit /b
Echo.
Echo Snapshot success. (ID %VSSID%)
Echo.
REM vssadmin list shadows /Shadow={a759180d-6bbe-4aaf-b3aa-57d219aa3e88}
REM vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool
REM (C) Copyright 2001-2005 Microsoft Corp.
REM
REM Contents of shadow copy set ID: {caf5cc6b-0c9d-4f88-abe8-83f89faf96bf}
REM Contained 1 shadow copies at creation time: 16-5-2015 15:44:13
REM Shadow Copy ID: {a759180d-6bbe-4aaf-b3aa-57d219aa3e88}
REM Original Volume: (C:)\\?\Volume{2bfd2d95-a745-11e4-9803-806e6f6e6963}\
REM Shadow Copy Volume: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy23
REM Originating Machine: ASUS
REM Service Machine: ASUS
REM Provider: 'Microsoft Software Shadow Copy provider 1.0'
REM Type: ClientAccessible
REM Attributes: Persistent, Client-accessible, No auto release, No writers, Differential
REM Get the Shadow Copy Volume, Find the line in output with GLOBALROOT, divide line by : and take 2nd part
For /f "tokens=2 delims=:" %%s in ('"vssadmin.exe list shadows /Shadow=%VSSID%"^|FindStr GLOBALROOT') Do Set VSSVOL=%%s
Echo.
Echo Copying Registry files from %VSSVOL% to C:\Temp
Echo.
Echo|SET /p=software & Copy /Y %VSSVOL%\Windows\System32\Config\software c:\temp\hklm_software
Echo|SET /p=system & Copy /Y %VSSVOL%\Windows\System32\Config\system c:\temp\hklm_system
Echo|SET /p=components & Copy /Y %VSSVOL%\Windows\System32\Config\components c:\temp\hklm_components
Echo|SET /p=security & Copy /Y %VSSVOL%\Windows\System32\Config\security c:\temp\hklm_security
Echo|SET /p=sam & Copy /Y %VSSVOL%\Windows\System32\Config\sam c:\temp\hklm_sam
Echo|SET /p=default & Copy /Y %VSSVOL%\Windows\System32\Config\default c:\temp\hkcu_default
Echo|SET /p=LocalService & Copy /Y %VSSVOL%\Windows\ServiceProfiles\LocalService\ntuser.dat c:\temp\hku_localservice
Echo|SET /p=NetworkService & Copy /Y %VSSVOL%\Windows\ServiceProfiles\NetworkService\ntuser.dat c:\temp\hku_networkservice
Echo|SET /p=SystemProfile & Copy /Y %VSSVOL%\Windows\System32\config\systemprofile\ntuser.dat c:\temp\hku_system
Echo|SET /p=CurrentUser (%USERNAME%) & Copy /Y %VSSVOL%\%USERPROFILE:~3%\ntuser.dat c:\temp\hku_%USERNAME%
Echo|SET /p=CurrentUser Classes & Copy /Y %VSSVOL%\%LOCALAPPDATA:~3%\Microsoft\Windows\UsrClass.dat c:\temp\hku_%USERNAME%_classes
Echo.
Echo Done. Removing VSS Snapshot (ID %VSSID%)...
Echo.
vssadmin.exe delete Shadows /Shadow=%VSSID% /Quiet >nul
If %errorlevel% == 1 (
Echo Snapshot ID %VSSID% not deleted!
) Else (
Echo Snapshot succesfully removed.
)
Exit /b
Get the current user SID and profile path using WMI from a cmd script:
REM If script is running as system user
For /f "skip=1 delims=> " %%a in ('query.exe user console') Do set LUSER=%%a
For /f "tokens=2 delims==" %%a in ('"wmic.exe path win32_useraccount where Name='%LUSER%' get SID /VALUE"') Do set SID=%%a
REM If script is running as current user
For /f "tokens=2 skip=4" %%a in ('whoami.exe /user') Do set SID=%%a
For /f "tokens=2 delims==" %%a in ('"wmic.exe path Win32_UserProfile where SID='%SID%' get LocalPath /VALUE"') Do set PROFDIR=%%a
Msg.exe * User %LUSER% has SID %SID% and ProfileDir %PROFDIR%
If the script is running as current user you can also use %HOMEDRIVE%%HOMEPATH% to get the Profile Directory
Change a User AD attribute (like Dialin)
set objOU = GetObject("LDAP://OU=Users,OU=Site1,DC=domain,DC=com")
For Each objUser In objOU
If (objUser.Class = "user") Then
objUser.msNPAllowDialin = TRUE
objUser.SetInfo
End If
Next
Check users membership of Domain Groups at logon
Whoami.exe /groups | Find /i "Domain Admins"
If Not Errorlevel 1 Echo Dude, you're a Domain Admin
or
Net.exe Group "Domain Admins" /domain | Find /i "%USERNAME%"
If Not Errorlevel 1 Echo Dude, you're a Domain Admin
Note: Net.exe Group /Domain ONLY lists global security groups
Scripts and Group Policies
It is possible with Gpo's to start scripts at Startup and/or Shutdown. If you want runs these scripts at Computer Level then Gpo runs as the local System account.
Accessing the script on the network share is done by the local System account with the Computer account the Gpo is running on.
If you don't change the Share permissions on the share the scripts are located they will not run.
To fix this add the Domain Computers group from AD with Read permissions to the NTFS permissions of that share!
You can run this script as system with a Scheduled Task and you will see which user in logging on:
REM ### Find name of user that is behind keyboard
For /f "skip=1 delims=> " %%a in ('query.exe user console') Do Set LUSER=%%a
Msg.exe * "Username: %USERNAME% Console: %LUSER%"
The gpscript command
Windows runs logon and startup scripts after a boot. You can also force to rerun them at a later time using the gpscript.exe command. Useful if you want to debug the scripts.
gpscript /Startup
gpscript /Shutdown
gpscript /Logon
gpscript /Logoff
gpscript /RefreshSystemParam
Problems with applying GPO's
Long "Applying computer settings" after boot indicates the Domain Controller cannot be found (this may take up to two minutes).
That can have several causes.
Firewall
This is can be a NLA/Firewall problem. The NLA service determines the Network Location (Home/Work(Private) or Public) for each active network card.
First NLA will use the network card domain name. See here for more info.
The firewall applies a profile on that result, that could be Domain, Private or Public. Sometimes this process goes wrong. Then the wrong Firewall profile is active, hence problems communicating with the DC's. Try switching the Firewall off completely and reboot to see if that is the case.
You can also use a group policy to force Unknown Networks to Private on your Domain Computers or add your domain name to the DNS suffix of a NIC.
More info here.
Windows 7
Computer Configuration > Policies > Administrative Templates > System > Group Policy > Startup policy processing wait time (GpNetworkStartTimeoutPolicyValue)
Set the Amount of time to wait (in seconds) to 30 (Although 30 seconds is default it makes a difference)
A value of between 15 and 30 seconds is normal. If gpo scripts are not executed then you can tell the group policy service to wait. The time can be set like this:
Reg.exe add "HKLM\Software\Policies\Microsoft\Windows\System" /v GpNetworkStartTimeoutPolicyValue /t REG_DWORD /d 0x14 /f
You can examine the time it takes on average how log it takes to start processing the GPO's. Examine this value in the registry:
Reg.exe query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\History" /v AvgWaitTimeoutAtStartup
At least Windows 7 looks at AvgWaitTimeoutAtStartup if GpNetworkStartTimeoutPolicyValue is not set. Sometimes that causes that a DC cannot be found.
Microsoft article about intermittently fail to apply group policy at startup here.
There is a little bug in Windows 7 with the "apply once GPO". Check this registry key and remove any CLSID at least once
Reg.exe delete "HKLM\SOFTWARE\Microsoft\Group Policy\Client\RunOnce" /va /f
If you have a W2k3 DC and Windows 7 workstations you need to set this on every workstation to avoid long logon wait times ("applying settings"):
Netsh.exe interface tcp set global autotuninglevel=disabled
Netsh.exe interface tcp set global chimney=disabled
Windows 10
Hiberboot prevents gpo mapped network drives to be mapped in time (multiple tries might succeed). So you need to disable hiberboot for now on Windows 10 machines. Turn off hibernation all together with: Powercfg.exe /H Off
You can also disable the hiberboot feature by the registry:
Reg.exe add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /v HiberbootEnabled /t REG_DWORD /d 0 /f
Note: on win2k3 server: reg.exe add HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v EnableTCPChimney /t REG_DWORD /d 0
Tip: Avoid WMI-query scripts with "Item-level targetting". WMI queries ask a lot of disk access during boot and login.
Use "Stop processing items in this extension if an error occurs" or "Apply once and do not reapply" to improve gpo processing.
Tip: If you have multiple fixed IP's on one NIC remove all but the one of the domain controller subnet. Then type the command ipconfig /registerdns and after that add other fixed IP addresses.
Windows Defender complete uninstall for Windows 7
When installing Security Essentials or SCEP the Windows Defender stays on your system. So if you want to get rid of Defender use my script. The script uses Microsoft's subinacl.exe tool (included) to get ownership of registry keys and subdirectories/files to remove them. Run the script elevated. It will not interfere with Microsoft Security Essentials if that is already on your system.
See Win7DefenderUninstall.zip in Download list at bottom of this page.
If you want to update Defender or Security Essentials on Daily basis? Create a Task in the Scheduler that run "MpCmdRun.exe -SignatureUpdate" daily.