Monday, September 8, 2008

Useful general command-line operations

The commands below are a subset of the complete command list found in Useful command-lines, and are the remainder of command-line operations that didn't fit into one of the other categories I've used.

Each command-line can be copied and pasted at the command prompt, if you use a batch file you'll need to reference variables with double-percent (%%).


Open the administrative tools start menu list
control admintools

Open the scheduled tasks special folder
control SCHEDTASKS

Disable hibernation
powercfg -h off

Show network interface statistics (packets/errors/bytes)
netstat -e

Find remote processes and the command-line parameters with PowerShell
Get-WmiObject win32_process | Format-Table ExecutablePath,Caption,CommandLine,CreationDate,WorkingSetSize,ProcessId

Create an IIS virtual directory
cscript C:\WINDOWS\system32\iisvdir.vbs /create "Default Web Site" %Alias% %rootPath%

Use WMIC to get instances of a class and format the output as CSV
wmic path win32_process get name,commandline /format:csv

Find the current CPU utilisation for processes using WMI
wmic /node:"%computer%" path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime

Use JT to update a scheduled task's working directory
jt.exe /sac \\%computer%\c$\windows\Tasks\%Task%.job /sj WorkingDirectory = "%workingdir%"

Use WMIC aliases to format the output in CSV or XML
wmic process list /format:xml | wmic process list /format:csv

Use WMIC aliases to format the output in HTML TABLE, MOFCSV or XML
wmic process list /format:htable | wmic process list /format:HMOF

Use WMIC aliases to sort the output in HTML
wmic process list /format:htable:"sortby=Name" > test.html

Use WMIC aliases to filter and sort the output in CSV
wmic process get name /format:csv:"datatype=text":"sortby=Name"

Use WMIC remotely aliases to retrieve command-line process arugments
wmic /node:"%server%" process get name,CommandLine /format:csv:"sortby=Name"

Use WMIC wmic aliases to sort the result set by number
wmic Logon get /Format:htable:"datatype=number":"sortby=LogonType"

Check NULL sessions to see if user/group information can be enumerated
hunt.exe OR winfo.exe

Disable strict name checking for a machine
reg add \\%computer%\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters /v DisableStrictNameChecking /t reg_dword /d 0x1

List transports and if they are bound to NetBIOS (NetBT over TCP/IP)
browstat dumpnet

View the browse list using NetServerEnum to a domain or server
browstat view \Device\NetBT_Tcpip_{972F2574-31D4-4467-8BC0-70B3C57C1279} %domain%

Find remote cscript processes and the scripts they are running (arguments)
wmic /node:"%computer%" path win32_process Where "Caption Like '%cscript%' " get Caption,CommandLine,CreationDate,WorkingSetSize,ProcessId

Connect to a named SQL instance through Management Studio
%server%\%instance_name%

Query an Enterprise Vault Directory database for file group information(view)
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select * from dbo.view_FileGroupAndFileGroupFile"

Query an Enterprise Vault Directory database for file group information(table)
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select FileGroupName, FileGroupDescription, FileSpecification from filegroupfile inner join Filegroup on FileGroupFile.FileGroupEntryID = FileGroup.FileGroupEntryID Order By FileGroupName"

Query an Enterprise Vault Directory database for index errors
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "Select ArchiveName, ArchiveStatus, IndexRootPath, Offline, Failed, Rebuilding, IndexedItems, FailedItems from IndexVolumeView where (rebuilding != 0) OR (Failed != 0) OR (Offline != 0)"

Extract events from a non-standard event log
wmic /node:"%computer%" path Win32_NTLogEvent WHERE "SourceName='%EventSource%' AND LogFile='%LogName%' AND EventCode=%eventcode%"

Start a process in low priority
cmd /c start "LowPriority" /BELOWNORMAL notepad "a file.txt"

Software Information for each server
for /f %i in (Output from 'Domain Controllers') do psinfo \\%i > ServerInfo_%i.txt & filever \\%i\admin$\explorer.exe \\%i\admin$\system32\vbscript.dll \\%i\admin$\system32\kernel32.dll \\%i\admin$\system32\wbem\winmgmt.exe \\%i\admin$\system32\oleaut32.dll >> ServerInfo_%i.txt

Check Terminal Services Delete Temp on Exit flag
For /f %i in (Output from 'Domain Controllers') do Reg query “\\%i\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server” /v DeleteTempDirsOnExit

For each XP workstation, query the current site and what Group Policy info
@dsquery * domainroot -filter "(&(objectCategory=Computer)(operatingSystem=Windows XP Professional))" -limit 0 -attr cn > Workstations.txt & @For /f %i in (Workstations.txt) do @ping %i -n 1 >NUL & @if ErrorLevel 0 If NOT ErrorLevel 1 @Echo %i & for /f "tokens=3" %k in ('"reg query "\\%i\hklm\software\microsoft\windows\currentversion\group policy\history" /v DCName Find /i "DCName""') do @for /f %m in ('"nltest /server:%i /dsgetsite find /i /v "completed successfully""') do @echo %i,%k,%m

Time offsets from client diagnostics
@for %i in (*time*.txt) do @for /f "tokens=2 delims=:" %j in ('"find /i "NTP:" %i find /i "NTP:""') do @echo %i,%j

Find remote NIC bandwidth
wmic /node:%server% path Win32_PerfRawData_Tcpip_NetworkInterface GET Name,CurrentBandwidth

Find remote free physical memory
wmic /node:%Computer% path Win32_OperatingSystem GET FreePhysicalMemory

Find remote system information
SystemInfo /s %Computer%

Disk statistics, including the number of files on the filesystem
chkdsk /i /c

Query IIS web sites
iisweb /s %Server% /query "Default Web Site"

Check port state and connectivity
portqry -n %server% -e %endpoint% -v

Find the parent of a process
wmic path Win32_Process WHERE Name='%ProcessName%' GET Name,ParentProcessId

PSCP secure copy a file
pscp %file% %user%@%target%:/target/path

Accept a input and store in a variable
set /p <variable>=<prompt>

Remote Computer Management MMC
compmgmt.msc /computer=%1

Create a placeholder file
fsutil file createnew <filename><size>

Device Manager showing hidden devices
SET DEVMGR_SHOW_NONPRESENT_DEVICES=1 & Devmgmt.msc

Echo both stdout and stderr to the same file
> output.txt 2<&1

For the first token in each line in A, compare the second token in B
for /f "tokens=1-3 delims=," %i in ('"find /i /v "<exclude>" a.txt"') do @for /f "tokens=1-3 skip=2 delims=," %m in ('"find /i "%i" b.txt"') do @if /i "%i"=="%m" @if /i "%j" NEQ "%n" @echo %i,%j,%n

For the first token in each line in A, find not in B
for /f "skip=2 delims=," %i in ('" find /i /v "<exclue>" a.txt"') do @find /i "%i" b.txt 1>nul 2>nul & @if errorlevel 1 echo %i

Find the DFS roots from Active Directory
dsquery * "CN=DFS Volumes,CN=File Replication Service,CN=System,DC=domainRoot"

Find the DFS roots using dfsutil
dfsutil /domain:%domain% /view

View info on a DFS root
dfsutil /root:<dfsroot> /view

Port Query testing network connectivity to the specified endpoint
portqry -n %target% -e 135

Test RPC endpoints
rpcdump /s %computer% /v /i

Extract a cabinet from an MSI stream
msidb -d "%msi%" -x "%cabinet name%" (get the cabinet name from the Media table using orca, and the filenames from the File table)


Add a system environment variable
setenv -a test %path%;%AdminRoot%\Utils

Lock the workstation from the commandline
%windir%\System32\rundll32.exe user32.dll, LockWorkStation

Perform idle time optimisation (eg. file placement optimisation)
rundll32.exe advapi32.dll,ProcessIdleTasks

Hardware Installation from an INF file
%SystemRoot%\System32\rundll32.exe setupapi,InstallHinfSection DefaultInstall

Refresh network configuration after policy changes (eg SearchList)
RunDLL32.EXE netshell.dll,NetSetupFinishInstall

Query SMS inventory information from the commandline
wmic /namespace:\\root\sms\site_%SiteCode% /node:%Computer% path SMS_G_System_SYSTEM_ENCLOSURE WHERE ResourceID='%RID%'

Find remote connections to a server
wmic /node:%server% path win32_serverconnection

Find remote sessions to a server
wmic /node:%server% path win32_serversession

Find security patches applicable on a machine with MBSA
wmic /node:%computer% path Win32_PatchState

For services that aren't running, find their start type
for /f "skip=4 tokens=1-3" %i in ('sclist \\%computer%') do @if "%i" NEQ "running" @for /f "tokens=4" %m in ('"sc \\%computer% qc %j find /i "START_TYPE""') do @echo %i,%j,%k,%m

For computers listed, if a service exists, start it
for /f %i in (computers.txt) do sclist \\%i find /i "%service_name%" && sc \\%i start "%service_name%"

Query a registry value of multiple computers
for %i in (PC1 PC2 PC3) do @Echo %i & reg query \\%i\hklm\software\%key% /v %Value% find /i "%Value%"


Query the creation date of multiple computer objects
dsquery * -filter "(&(objectClass=Computer)(objectCategory=Computer)((cn=PC1)(cn=PC2)(cn=PC3)))" -attr CN whenCreated

Query SMS for the creation date of computer records
select Name0, Creation_Date0 from v_r_system where name0 in('PC1','PC2','PC3')

Find RIS servers hosting the specified image
for /f "tokens=2 skip=1 delims==, " %i in (RIS_Servers.txt) do @if exist \\%i\reminst\setup\english\%Source% @echo %i

Modify Outlook to allow access to blocked attachements
reg add HKU\S-1-5-21-2091930395-2002392527-14044502-274471\Software\Microsoft\Office\11.0\Outlook\Security /v Level1Remove /t reg_sz /d ".exe"

Open the Find Files Dialog Box
echo Set objShell = CreateObject("Shell.Application") > test.vbs && Echo objShell.FindFiles >> test.vbs && cscript test.vbs

View Software Installation controlled through AD, both current and history
gpsiviewer.exe

View Group Policy application times
gptime

Remote GP Update
rgprefresh

Find the tail of lines between two strings to display
for /f "delims=[]" %i in ('"find /i /N "Forwarders:" A.txt"') do for /f "delims=[]" %m in ('"find /i /N "Command completed successfully." A.txt"') do for /f %p in ('set /a %m-%i') do echo %p

Turn on RIS debugging
reg add \\%server%\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Binlsvc\Parameters /v Debug /t reg_dword /d 0x80FFFFFF & sc \\%server% stop binlsvc & sc \\%server% start binlsvc

Trigger a command to run on a specific event
eventtriggers /create /TR Test /L Security /EID 680 /T SUCCESSAUDIT /TK calc.exe

Create an XML file with the MD5 hashes of a set of files
FCIV

Find the shell extensions currently loaded
ShexView

Find server information
srvinfo.exe

LDAP Query from eDirectory
ldifde -d %rootDN% -s %NetwareServer% -f output.ldf -a "%UserDN%" *

csvde export form eDirectory
csvde -f OutputFile.csv -a "%UserDN%" * -r "(Objectclass=user)" -d "%rootDN%" -s NetwareServer%

Verify installed drivers
verifier.exe

Windows Updates Automatic Updates Detect now
wuauclt /detectnow

Test for ping and then query computers for network information
for /f %i in (pcs.txt) do @for /f "tokens=3 delims=: " %m in ('"ping -n 1 %i find /i "reply from""') @do for /f "tokens=*" %p in ('"@wmic /node:%i path Win32_PerfRawData_Tcpip_NetworkInterface GET find /i "1000" find /i /v "MS TCP Loopback interface""') do @echo %i,%m,%p

WireShark/ethereal filter to exclude 3389 RDP
!((tcp.srcport == 3389) (tcp.dstport == 3389))

Show NetBIOS SMB lanmanserver binding
net config server

Show NetBIOS SMB lanmanworkstation binding
net config redirector

Find the session connection for a username and find the client workstation
for /f "tokens=2 delims=\" %i in ('"dsquery user -name %user% dsget user -hmdir find /i "%user%""') do @for /f "skip=1 tokens=1-3" %m in ('"wmic /node:"%i" path win32_serversession WHERE "UserName Like '%user%'" Get ComputerName,ActiveTime,IdleTime"') do @for /f "tokens=2" %q in ('"ping -a %n -n 1 find /i "pinging""') do @echo %q %user% %n %i %m %o

Doskey macro to find session connection information for a user/workstation
FU=for %g in ($1 $2 $3 $4 $5 $6 $7 $8 $9) do @for /f "tokens=2 delims=\" %i in ('"dsquery user -name %g dsget user -hmdir find /i "%g""') do @for /f "skip=1 tokens=1-3" %m in ('"wmic /node:"%i" path win32_serversession WHERE "UserName Like '%g'" Get ComputerName,ActiveTime,IdleTime"') do @for /f "tokens=2" %q in ('"ping -a %n -n 1 find /i "pinging""') do @echo %q %g %n %i %m %o

Refresh per user settings such as desktop wallpaper
RunDll32.exe USER32.DLL,UpdatePerUserSystemParameters ,1 ,True

Query RDP sessions on a 2003 server
query session

Shadow an existing TS or console session (Ctrl -* to end the shadow)
shadow %session%

Run a command in the winlogon secure desktop of winsta0\winlogon
psexec /x /d /s cmd

Remotely Run a command in the winlogon secure desktop of winsta0\winlogon
psexec /s \\%computer% cmd /c c:\windows\temp\psexec /x /d /s cmd

Update the wallpaper on the winlogon secure desktop winsta0\winlogon
psexec /accepteula /x /s RunDll32.exe USER32.DLL,UpdatePerUserSystemParameters

Run commands automatically when a command prompt is started
reg add "hklm\software\microsoft\Command Processor" /v AutoRun /t reg_sz /d "doskey /macrofile=macros.txt"

Export the groups a user in eDirectory is a member of
ldifde -f output.txt -s %NetwareServer% -a "%AccountDN%" * -d %rootDN% -r "(&(Objectclass=user)(((cn=User1)(cn=User2))))" -l cn,groupMembership

Produce a list of files that should be purged based in minage
robocopy /l %Source% %Temp%\Purge%Random% *.* /minage:6 /FP /NJS /NJH /E /TS /NS

Find the install date from a list of servers
for %i in (%Server1% %Server2%) do psinfo \\%i 2>nul findstr /i /c:"Install date" /c:"%ComputerName%"

Use findstr with regular expressions to find start of line + space + 'New Dir'
findstr /i "^.*New.Dir" Dirs.txt

Use delayed environment varialble substitution in a for loop
for /f "delims=:" %i in ('"findstr /i /n "^.*New.Dir" PurgeFiles.txt"') do Set Directory=0000%i & Echo !Directory:~-5!

Query Windows Update logs from contactable machines in an OU
for /f %i in ('"dsquery computer %DN% -o rdn"') do @for /f "tokens=3 delims=: " %m in ('"ping -n 1 %i find /i "reply from""') do dumpel -s %i -l system -e 19 20 -m "Windows Update Agent"

Produce a flat list of files, with the last-write date
dir %Directory% /tw/s find /i "/" find /i /v "DIR" > Output.txt

Given a control file and a text file, output control entries that aren't found
for /f "tokens=1-3" %i in (%ControlFile%) do @find /i "%i" %TextFile% >NUL & @if errorlevel 1 echo %i

Given a control file and a text file, show whether or not control is in text
for /f "tokens=1-3" %i in (%ControlFile%) do @find /i "%i" %TextFile% >NUL & @if errorlevel 0 if not errorlevel 1 (echo %i Member) else (echo %i NotMember)

Query a specific eDirectory group for its members
ldifde -f output.txt -s %NetwareServer% -a "%AccountDN%" * -d %rootDN% -l cn,member

Export a Operations Manager 2007 sealed management pack to an unsealed XML
. c:\windows\temp\MpToXml.ps1 "%SealedMP%.mp" c:\windows\temp

Join output split across two lines using delayed variable expansion (cmd /v:on)
for /f "tokens=3,4" %i in ('"findstr /i /c:"printDuplexSupported" /c:"Share Name" PrintersRegQuery.txt"') do @if "%i"=="REG_SZ" (@Set Printer=%j) else (@Echo !Printer!,%i)

Open an Excel document in read-only mode from the commandline
start excel /h /e %xls%

Extract B if A is found in B, otherwise report blank
for /f "tokens=1-3 delims=," %i in (a.txt) do @find /i "%i" b.csv >nul & If errorlevel 0 if not errorlevel 1 (for /f "tokens=4 delims=," %m in ('"find /i "%i" b.csv find /i "%i""') do @echo %i,%m,%j,%k) else (Echo %i,none,%j,%k)

Query SMS for computers on a particular subnet
wmic /namespace:\\root\sms\site_%sitecode% /node:"%site_Server%" path SMS_R_System WHERE "IPSubnets='%subnet%' AND Active=1'" get name

Query SMS for computers in a specific AD site
wmic /namespace:\\root\sms\site_%sitecode% /node:"%site_Server%" path SMS_R_System WHERE "ADSiteName='BNE' AND Active=1'" get name

Find the owner of a process using WMI - see who's logged on remotely
wmic /node:"%computer%" PROCESS where "caption='explorer.exe'" getowner

Convert a file to/from base64 to transmit a binary file through filters
http://www.motobit.com/util/base64-decoder-encoder.asp

Disable path parsing when listing a directory
dir "\\?\c:\folder"

Find network information for a computer from SMS
wmic /namespace:\\root\sms\site_%sitecode% /node:"%siteserver%" path SMS_R_System WHERE Name='%computer%' get name,adsitename,IPAddresses,IPSubnets,MACAddresses

Send a Wake-on-lan magic packet on a local subnet
wolcmd 00157283E57F 192.168.0.10 255.255.255.0 7

Get the lanmanserver description using SNMP
Snmputil.exe get %server% %community% .iso.org.dod.internet.private.enterprises.lanmanager.lanmgr-2.server.svDescription.0z

Query the performance counters stored in a log file
relog.exe file.blg -q

Report multiple named instances of SQL on a remote server
reg query "\\%server%\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL

Query the group membership cache used by Group Policy
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Group Policy\GroupMembership

Check the first x characters from A against B, report differences (cmd /v:on)
for /f "tokens=1-4 delims=," %i in (%Source%) do @set VarA=%i & Set VarB=%j& if /i "!VarA:~0,4!" NEQ "!VarB:~0,4!" echo %i,%j,%k,%l mismatch


Check local profiles, reporting whether they are local administrators or not
for /f %i in ('"dir /b/ad "c:\Documents and Settings""') do @for /f %m in ('"psgetsid %i 2>Nul | find /i "s-1""') do @reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\%m\GroupMembership" 2>nul | find /i "S-1-5-32-544" 1>nul & @if errorlevel 1 (@echo %i Not an Administrator or group policy entry not found) else (@echo %i Is an Administrator)

View the User Accounts control panel applet
Control Userpasswords2

Roll daily logs into monthly logs (command runs each day)
for /f "tokens=3,4 delims=/ " %i in ('echo %date%') do copy c:\logs\daily\logfile_%j%i??.csv c:\logs\monthly\logfile_%j%i.csv /y

List the file screen groups for File Server Resource Manager (FSRM)
filescrn filegroup list

Directory listing of all files in bare format, excluding the the dir objects
dir \\%server%\%share%\*.* /a-d/s/b

Master an ISO Image from a source directory
oscdimg -m -h -n . %Target%.iso

Enable Netlogon debugging
nltest /dbflag:0x2080FFFF

Start a remote process using Powershell/WMI
$computer = "."; ([WMICLASS]"\\$computer\root\CIMv2:win32_process").Create("notepad.exe")

Find remote drivers installed on a computer
devcon -m:\\%computer% status *

Create a floppy image from the given path
bfi.exe -v -f=test.img %path%

Extract files from a floppy image (Gilles Vollant extract.exe)
extract -e %imgfile%



Wayne's World of IT (WWoIT), Copyright 2008 Wayne Martin.

2 comments:

Post a Comment