This is the second edition of useful command lines, adding another 132 commands that I've found useful. Note that many of the command-line calls may require Microsoft utilities (such as dsquery, wmic, dnscmd).
Most of the commands are for the windows-based command interpreter, with a few PowerShell and ESX service console commands creeping in. They range from diagnostics, troubleshooting and simply automating recurring tasks.
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 (%%).
See the original post with another 425 commands http://waynes-world-it.blogspot.com/2008/09/useful-command-lines.html
Given an IP and mask, return the subet the IP belongs to
for /f "tokens=1-8 delims=.- " %i in ('echo 192.168.5.200 255.255.255.0') do set /a Octet1="%i & %m" >nul & set /a Octet2="%j & %n" >nul & set /a Octet3="%k & %o" >nul & set /a Octet4="%l & %p" >nul & Echo %i.%j.%k.%l,!Octet1!.!Octet2!.!Octet3!.!Octet4!,%m.%n.%o.%p
Display the contents of the client DNS resolver cache
ipconfig /displaydns
Find the package source path of a program from SMS
wmic /namespace:\\root\sms\site_%sitecode% /node:"server" path SMS_Package Where "Name like '%programname%'" get Name,ShareName,PkgSourcePath
Find the session associated with a process
wmic path win32_process get name,sessionid
List the local winstation windows objects
objdir \Windows\Windowstations\Winsta0
Query the configuration container for Exchange mailbox stores
dsquery * ",CN=Configuration,DC=domainroot" -filter "(&(objectClass=msExchPrivateMDB)(objectCategory=msExchPrivateMDB))"
Query a Virtual Centre/VC 2.5 database for Virtual Machine details
sqlcmd -S server -d database -W -s "," -Q "select ENT.Name as 'Name', Lower(DNS_Name) as 'DNS Name', Guest_OS as 'OS', Mem_Size_MB as 'Mem', Num_VCPU as 'CPU', Num_NIC as 'NIC', IP_Address as 'IP', NET.MAC_Address as 'MAC Address', VM.FILE_Name as 'VMX location' from vpx_vm VM inner join VPX_NIC NET on VM.ID = NET.ENTITY_ID inner join VPX_ENTITY ENT on VM.ID = ENT.ID Order By ENT.Name"
Query a Virtual Centre/VC 2.5 database for Virtual Machine snapshots (GMT+10)
sqlcmd -S server -d database -W -s "," -Q "select ENT.Name as 'Name', Lower(DNS_Name) as 'DNS Name', Guest_OS as 'OS', Mem_Size_MB as 'Mem', IP_Address as 'IP', VM.FILE_Name as 'VMX location', VM.Suspend_Time as 'Suspend Time', VM.Suspend_Interval as 'Suspend Interval', VMS.Snapshot_Name as 'Snapshot Name', VMS.Snapshot_Desc 'Snapshot Description', DateAdd(Hour, 10, VMS.Create_Time) as 'Snapshot Time', VMS.Is_Current_Snapshot 'Current Snapshot' from vpx_vm VM inner join VPX_NIC NET on VM.ID = NET.ENTITY_ID inner join VPX_ENTITY ENT on VM.ID = ENT.ID inner join VPX_SNAPSHOT VMS on VM.ID = VMS.VM_ID"
Test the password for a domain account (assumes no existing IPC connection)
net use \\server\ipc$ /user:%domain%\%testuser% *
View the last-access, modified, created and MFT entry modified timestampes
timestomp "%fullpathtoFile%" -v
Create a scheduled task escaped with a command containing double-quotes (2003)
schtasks /create /SC Daily /TN "Task" /ST 12:00 /TR "cmd /c echo \"Test\"" /RU System
Create a scheduled task running two commands
schtasks /create /SC Daily /TN "Task" /ST 12:00 /TR "cmd /c echo Test1 & cmd /c echo Test2" /RU System
Check a number of computers to see if hibernation is enabled
for /f %i in (%controlfile%.txt) do @if exist \\%~i\c$\hiberfil.sys (echo %~i,Enabled) else (echo %~i,Disabled)
For each path in a control file, list the 8.3 short equivalent
for /f "tokens=*" %i in (test.txt) do echo %~si
Use if exist and disabled path parsing to bypass max_path
for /f "tokens=*" %i in (test.txt) do if exist "\\?\UNC\%~pnxi" echo File exists
Enumerate a cluster through WMI
wmic /node:"%node%" /namespace:\\root\mscluster path MSCluster_Cluster
Given a path exceeding MAX_PATH, return the 8.3 equivalent of the directories
for /f "tokens=*" %i in (longfiles.txt) do for /d %m in ("\\%~pi") do echo %~sm%~nxi
Given a path you know contains deeper than 260, batch to return the 8.3 subdirs
(3 lines) @for /f "tokens=*" %%i in (c:\temp\longdir1.txt) do @for /d %%m in ("\\%%~pi") do @Call :Process "%%~si" || :process || @if "%~1"=="" (goto :EOF) else (@for /d %%i in ("%~1\*.*") do @echo %%~si & Call :Process "%%~si")
Set a Domain Controller to be a Global Catalog server
dsmod server "%DC_DN%" -isgc yes
Check which network connections (drive mappings) a computer has
wmic /node:"%computer%" path win32_logicaldisk where "DriveType=4" get DeviceID,ProviderName
Query the current site of a remote computer using nltest
nltest /dsgetsite /server:%computer%
Query the current site of a remote computer using the registry
reg query \\%computer%\hklm\system\currentcontrolset\services\netlogon\parameters /v DynamicSiteName
Check the schema version on a Domain Controller (R2=31)
reg query \\%dc%\hklm\system\currentcontrolset\services\NTDS\parameters /v "Schema Version"
Query the revision of 2003 Update (R2=9)
dsquery * CN=Windows2003Update,CN=ForestUpdates,CN=Configuration,%forestRoot% -attr revision
Check the schema version on a Domain Controller (R2=31)
dsquery * "CN=Schema,CN=Configuration,%forestRoot%" -attr objectVersion -scope base
Find the disk signature of a disk through diskpart
echo select disk 0 > %temp%\diskpart.txt & echo detail disk >> %temp%\diskpart.txt & diskpart /s %temp%\diskpart.txt | find /i "Disk ID:"
Search a dnscmd export for duplicate IP address references
for /f "tokens=1,5" %i in (DNSExport.txt) do @if "%j" NEQ "" @for /f "tokens=1" %m in ('"findstr /i "%j$" DNSExport.txt find /i /c "%j""') do @if %m GTR 1 @echo %i,%j,%m
Search and report duplicate IPs from a dnscmd export
for /f "tokens=1,4" %i in (DNSExport.txt) do @if "%j" NEQ "" @for /f "tokens=1" %m in ('"findstr /i "%j$" DNSExport.txt find /i /c "%j""') do @if %m GTR 1 (@echo %j,%m: & findstr /i "%j$" DNSExport.txt & echo.)
Dump the dfsr config from the active directory
dfsrdiag dumpadcfg
Remove Outlook 2003 prevention of PST usage
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\11.0\Outlook /v DisablePST /t reg_dword /d 0x0
Set the command prompt to include the time of the last command
prompt $t $p$g
Create a zero byte file
echo file 2>zero.txt
Given a list of files, echo those that are zero bytes in size
for %i in (%source%\*) do @if %~zi == 0 @echo %i
From a dnscmd export, find duplicate IP addresses
echo. > DuplicateIPs.txt & (for /f "tokens=1,4" %i in (DNSRecords.txt) do @if "%j" NEQ "" @find /i "%j" DuplicateIPs.txt >nul & if errorlevel 1 for /f "tokens=1" %m in ('"findstr /i "%j$" DNSRecords.txt | find /i /c "%j""') do @if %m GTR 1 (@echo %j,%m: & findstr /i "%j$" DNSRecords.txt & echo.) >> DuplicateIPs.txt) & type DuplicateIPs.txt
Start xperf performance tracing using the 'Diag' group
xperf -start -on Diag -f %temp%\tracing.etl
Open an xperf trace, exporting context switching for threads and processes
xperf -i %temp%\tracing.etl -a cswitch -thread -process
Check whether VMware VMFS partitions are block aligned to 128
/sbin/fdisk -lu
Query a Virtual Centre/VC 2.5 database for Consolidation performance stats
sqlcmd -S server -d virtualcenter -W -s "," -Q "Select Top 6 ip_address as 'IP', cpu_mhz_avg/1000 as 'CPU', mem_mb_avg/1000 as 'RAM' , disk_percent_avg/1000 as 'Disk' from vpx_csl_system_perf vPERF inner join vpx_csl_system_ip_address vIP on vPERF.System_ID = vIP.system_ID order by sample_time desc"
Identify Virtual Machines that are currently powered on
/usr/sbin/vcbVmName -h %server% -u username -s powerstate:on
Find OCS 2007 classes/attributes in AD
dsquery * "CN=Schema,CN=Configuration,DC=forestRoot" -filter "(&((cn=*rtc*)(|(objectCategory=classSchema)(objectCategory=attributeSchema))))"
Find OCS 2007 server from DNS service records
nslookup -type=srv _SipInternalTLS._tcp.{FQDN}
Find OCS 2007 Pools published in the current directory
dsquery * -filter "(objectClass=msRTCSIP-Pools)"
Find OCS 2007 SCPs from the local domain
dsquery * "CN=Pools,CN=RTC Service,CN=Microsoft,CN=System,DC=domainRoot" -attr *
Export config from OCS 2007 from a remote server
lcscmd /config /action:export /level:machine /configfile:config.xml /fqdn:%server%
IIS Authentication and Access Control Diagnostics
authdiag.exe
Find the number of VMs per datastore from the VC database
sqlcmd -S server -d virtualcenter -W -s "," -Q "select DS.name, Count(VMDS.VM_ID) as 'VMs' from vpxv_vm_datastore VMDS inner join vpx_datastore DS on VMDS.DS_ID = DS.ID group by DS.name"
Find detail on the VMs per datastore from the VC database
sqlcmd -S server -d virtualcenter -W -s "," -Q "select DS.name, VMS.Name from vpxv_vm_datastore VMDS inner join vpx_datastore DS on VMDS.DS_ID = DS.ID inner join vpxv_vms VMS on VMDS.VM_ID = VMS.VMID order by DS.Name"
Unattended install of IIS (assuming INF created with relevant [components])
Sysocmgr.exe /i:%windir%\inf\sysoc.inf /u:%iisComponents%.inf
Find the Exchange 2003 organization from AD
dsquery * forestroot -filter "(&(objectCategory=msExchOrganizationContainer))"
Mount a virtual floppy
vfd install & vfd start & vfd open
Send an SMTP mail using blat
blat -f smtprelay@relay.local -to user@domain.com -subject Test -body "Test body" -server smtprelay
Create MAPI profiles with an Exchange connection on a server without Outlook
profman2.exe
Find mailboxes that are excluded from Recipient Update Policies
dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(msExchPoliciesExcluded=*))" -attr cn msExchPoliciesExcluded | find /i "{26491CFC-9E50-4857-861B-0CB8DF22B5D7}"
Export a connector space from MIIS/IIFP to XML
csexport %maName% maExport.xml
IIFP permissions, write proxyAddresses to user objects, inherited to subobjects
dsacls "OU=%targetOU%,%domainRoot%" /I:S /G %DOMAIN%\%GROUP%:WP;proxyAddresses;user
IIFP permissions, create and delete contact objects, inherited to subobjects
dsacls "OU=%targetOU%,%domainRoot%" /I:S /G %DOMAIN%\%GROUP%:CCDC;contact
IIFP permissions, read/write all properties, inherited to subobjects
dsacls "OU=%targetOU%,%domainRoot%" /I:S /G %DOMAIN%\%GROUP%:RPWP;;contact
Find extended rights in the directory that apply to schema classes
dsquery * "CN=Extended-Rights,CN=Configuration,dc=forestRoot" -attr displayName CN
Trigger the SD propagator adminsdholder process in a domain
admod -rootdse "FixUpInheritance::1"
Set interrupt processor affinity for PnP drivers
intfiltr.exe
Set interrupt processor affinity for processes persistent across reboots
imagecfg.exe -a 0xF calc.exe (the mask to use the first four logical processors)
Start an executable with the specified processor affinity
start /affinity f calc.exe (the mask to use the first four logical processors)
Modify a server to use only one processor
boot.ini, add /onecpu switch
Query DC/DNS servers and find unconditional non-ds forwarders
for /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do @for /f "tokens=1,3" %m in ('"dnscmd %i /info > DNS_%i.txt & tail -5 DNS_%i.txt | find /i "addr[" | find /i "addr""') do @echo %~ni,%m,%n
Create an Active Directory integrated DNS conditional forwarder (5.2.3790.0)
dnscmd /ZoneAdd %targetDomain% /DsForwarder %targetDomainNSIP%
Find DNS forwarder zones
dnscmd %server% /enumzones /forwarder
Find DNS forwarder targets
for /f %i in ('"dnscmd %server% /enumzones /forwarder | find /i "forwarder""') do dnscmd %server% /zoneinfo %i | find /i "master"
Find AdminSDHolder groups with GROUP_TYPE_SECURITY_ENABLED
dsquery * domainroot -filter "(&(objectCategory=Group)(objectClass=Group)(groupType:1.2.840.113556.1.4.803:=2147483648))"
Query an MIIS/IIFP database to find the management agent AD configuration
select ma_name, private_configuration_xml from mms_management_agent
Check the MIIS/IIFP GALSync.xml file to find the management agent AD config
Extensions\GALSync.xml
Query an MIIS/IIFP database to find the management agent AD containers to sync
select filter_xml from mms_partition MMSP inner join mms_management_agent MMSA on MMSP.ma_id = MMSA.ma_id where ma_name = 'MA-NAME' and partition_name = 'DC=domainRoot'
Set the IP address of a machine using netsh
netsh interface ip set address name="Local Area Connection" source=static addr=192.168.0.10 mask=255.255.255.0 gateway=192.168.0.1 1
Set local DNS client primary using netsh
netsh interface ip add dns name="Local Area Connection" addr=192.168.0.10 index=1
Set local DNS client secondary using netsh
netsh interface ip add dns name="Local Area Connection" addr=192.168.0.11 index=2
Set local WINS client primary using netsh
netsh interface ip add wins name="Local Area Connection" addr="192.168.0.10" index=1
Set local WINS client secondary using netsh
netsh interface ip add wins name="Local Area Connection" addr="192.168.0.11" index=2
Modify service DACLs to allow service start stop (assumes query already exists)
subinacl /service schedule /grant=builtin\users=TO
User cmdkey to add a stored credential when connecting to a remote server
cmdkey /add:remote.domain.com /user:domain\user /pass:*
Find the holders of the specified NT right / privilege
showpriv SeProfileSingleProcessPrivilege
Query the privileges the current user holds
whoami /priv
Delete the policy restriction to run adsiedit.msc
reg delete "HKCU\Software\Policies\Microsoft\MMC\{1C5DACFA-16BA-11D2-81D0-0000F87A7AA3}"
Stop and then restart the ESX software iSCSI initiator
/usr/sbin/esxcfg-swiscsi -d | /usr/sbin/esxcfg-swiscsi -e
Reset a computer account secure channel
nltest /sc_reset:%domain%[\%dc%]
Reset the password for a computer account
nltest /sc_change_pwd:%domain%
CSV directory export of one or more subcontainers of a container
for /f %i in ('"dsquery ou OU=People,DC=domainRoot -scope onelevel -o rdn"') do csvde -f UserExport-%~i.csv -l givenName,sn,displayname,mail,targetAddress,proxyAddresses,mailnickname -d "OU=%~i,OU=People,DC=domainRoot" -r "(&(objectClass=Contact)(objectCategory=Person))"
Query VMFS volume information from the service console
/usr/sbin/vmkfstools -P /vmfs/volumes/%GUID%
Change the volume label of a disk
label %drive%: %newlabel%
Find VMware CDP info from the service console
esxcfg-info | grep -C 18 '\==+CDP Summary'
Add a non expiring enabled user account to the Active Directory
dsadd user "CN=user,OU=Users,DC=test,DC=com" -pwd "password" -pwdneverExpires yes -disabled no -desc "Description"
Clear local DNS client settings using netsh
netsh interface ip delete dns name="Local Area Connection" addr=ALL
From an ESX service console, scan for updates from a depot for UpdateManager
/usr/sbin/esxupdate --HA --flushcache -d http://esx01/vci/hostupdates/hostupdate/esx/esx-3.5.0 scan
Check the VI35 Legato AAM HA agent
cat /var/log/vmware/aam/aam_config_util_addnode.log
VMware VI35 HA Legato AAM, list the cluster manager
/opt/vmware/aam/bin/ftcli -domain vmware -timeout 60 -cmd "listrules"
VMware VI35 HA Legato AAM, list the cluster nodes
/opt/vmware/aam/bin/ftcli -domain vmware -connect esx01 -port 8042 -timeout 60 -cmd "listnodes"
VMware ESX VI35 List the software iSCSI targets
/usr/sbin/vmkiscsi-tool -L -l vmhba32
Mount a local volume inside a local folder
mountvol c:\temp\mount1 \\?\Volume{f856ff87-70ae-11dc-8b8d-806d6172696f}\
Remove a mount point
mountvol C:\temp\mount1\ /d
List junctions or mount points
junction -s c:\temp
Find the boot device for an ESX installation
esxcfg-info -s | grep -A10 "Diagnostic Partition"
Find the boot device for an ESX installation
esxcfg-info -s | egrep -A4 "Parallel SCSI Interface|Block SCSI Interface"
Use vSphere RCLI to list an ESXi host filesystem
vifs.pl --server %server% --username %username% --password %password% -D /host
Use vSphere RCLI to backup an ESXi host (esxcfg-cfgbackup.pl)
vicfg-cfgbackup.pl --server %server% --username %username% --password %password% -s server.tgz
ESX VI35 list the virtual machines and their disks for performance analysis
/usr/lib/vmware/bin/vscsiStats -l
ESX VI35 gather disk statistics and display the latency histogram in CSV
/usr/lib/vmware/bin/vscsiStats -s; /usr/lib/vmware/bin/vscsiStats -x; /usr/lib/vmware/bin/vscsiStats -p latency -c;
Get Windows Remote Management config on the local machine
winrm get winrm/config
Windows Remote Management quick configuration to create a listener
winrm quickconfig
Test Windows Remote Management listener on the local host
winrm id
Create a Windows Remote Management https listener on the local host
winrm quickconfig -transport:https
Create a self-signed certificate
makecert" -r -pe -n -r 30/12/2039 -eku 1.3.6.1.5.5.7.3.1 -ss my-sr localMachine -sky Exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 c:\temp\test.cer
Query the SNTP servers a comptuer is using for time synchronisation
net time \\server /querysntp
Set the SNTP servers used for w32time synchronistaion
net time \\server /setsntp:"192.168.0.10 192.168.0.11"
Convert time from 100 nanosecond intervals since epoch 01/01/1601
w32tm /ntte 127076450620627215
Install the w32time Windows Time service
w32tm /register
Enable NTP Server for a w32time service
reg add \\server\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer /v Enabled /t reg_dword /d 0x1 /f
Find the error description given a win32 error number
net helpmsg 2
Delete the policy value controlling whether recently run programs are recorded
reg delete HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer /v NoRecentDocsHistory
Set registry permissions (subinacl 5.2.3790.1180 or later)
subinacl /keyreg "\\server\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /grant=domain\group=F
Set service DACLs (Q : Query SC, S: status, I: interrogate, T: Start, O: Stop)
subinacl /service \\server\schedule /grant=domain\group=TOQSI
Rename a LAN interface name (ncpa.cpl)
netsh interface set int name="Local Area Connection 2" newname="Local Area Connection"
Find all network devices
devcon findall =net
Find all network adapters for the Net class
devcon listclass net
Remove an old VMware VI3 PCNET Flexible/VLance/VMXNET adapter instance (@)
devcon remove "@PCI\VEN_1022&DEV_2000&SUBSYS_20001022&REV_10\3&61AAA01&0&88"
Find where a file is in the path
for %i in (calc.exe) do echo %~$PATH:i
Find the physical disk sector size
wmic path win32_diskdrive get BytesPerSector
Find the current amount of memory used by the file system virtual cache
wmic path Win32_PerfFormattedData_PerfOS_Memory get SystemCacheResidentBytes
Use robocopy in backup mode to take a copy of folder-level permissions
Robocopy \\server\source c:\temp\copy zxcvsadfqwer /E /B /COPYALL /R:1 /W:1
Find remote shares and paths using WMI
wmic /node:%server% path win32_share get Name,Path,Description
Find total memory, free memory and used paging file
wmic /node:%server% path Win32_OperatingSystem Get FreePhysicalMemory,FreeSpaceInPagingFiles,TotalVirtualMemorySize,TotalVisibleMemorySize
Search a remote computer's registry for a string
regfind -m \\%server% -y -b -n search_string
Set a computer to use a specified number of available processors
modify boot.ini, use the /NUMPROC=x switch or /ONECPU switch
Check the Exchange ESE buffer cache size
dsquery * "CN=InformationStore,CN=exchserver01,CN=Servers,CN=AdminGroup01,CN=Administrative Groups,CN=organisation,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domainRoot" -attr msExchESEParamCacheSizeMax -scope base
Query the start of authority record for a DNS zone
dnscmd %server% /enumrecords %fqdn% @ /type SOA
Wayne's World of IT (WWoIT), Copyright 2009 Wayne Martin.
Information regarding Windows Infrastructure, centred mostly around commandline automation and other useful bits of information.
1 comment:
Hi Wayne,
Thanks for sharing your insightful thoughts and suggestions - very helpful, and appreciated indeed.
On a related note, thought I'd let you know about a very cool new FREE tool called Gold Finger that we have become addicted to it, especially, finding out where all users have permissions in our Active Directory. (We came across it on ActiveDirSec.com.)
Gold Finger is an instantly deployable Microsoft endorsed Active Directory reporting tool that offers over 200 security reports (including powerful ACL analysis) for FREE.
It is developed by a Microsoft partner called Paramount Defenses Inc, and I believe was architected by the author of Microsoft's delegation whitepaper.
DOWNLOAD LINK: You can download it from http://www.paramountdefenses.com/goldfinger.php.
We've been using it for the past two weeks now and love it! If you need a free way to generate AD security reports, you'll certainly find it very helpful.
Best wishes,
Jonathan
Post a Comment