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

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

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

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

View Group Policy application times

Remote GP Update

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

Find the shell extensions currently loaded

Find server information

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

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 "" 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

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 7

Get the lanmanserver description using SNMP
Snmputil.exe get %server% %community%

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.

No comments:

All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 13 years, and I know just about enough to realise that I don’t know very much.