Friday, January 23, 2009

Under Windows 7.7000

[] Windows PowerShell w/ windows 7 ...

Powershell.exe is being installed in %windir%\ system32\ windowspowershell\ v1.0. The prompt shows: 'Windows PowerShell V2' on the first line; 'Copyright (C) 2008 Microsoft Corporation. All rights reserved.' on the second line. The Screen Background and Screen Text uses white on black, same as that of cmd.exe, when the V2CTP3 uses gray on blue black.

PS C:\stub> $PSVersionTable

Name Value
---- -----
CLRVersion 2.0.50727.3521
BuildVersion 6.1.7000.0
PSVersion 2.0
PSCompatibleVersions {1.0, 2.0}

PS C:\stub> [environment]::OSversion | fl

Platform : Win32NT
ServicePack :
Version : 6.1.7000.0
VersionString : Microsoft Windows NT 6.1.7000.0

There is an extra module called TroubleshootingPack in Windows 7 but not in V2CTP3.

Its WindowsPowerShellHelp.chm, file size was 1,560,143 bytes (in Windows 7) released one month later than V2CTP3 (1,604,819 bytes). About_Associative_Array help section is similar to cmdlet head section but different help layout; this is not available in V2CTP3. Another was About_Globbing help section.

Just as V2CTP3 released before Christmas Day in 2008, the powershell_ise.exe was 196,608 bytes (filesize), which was released two days later than Windows 7's (192,512 bytes). Such feature is found in Home Basic Edition too.

[] Microsoft.NET Framework 3.5.1 w/ windows 7...

The web browser version shows: 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)'.

The following shows what CSC.exe has:

C:\Windows\Microsoft.NET\Framework\v2.0.50727>csc
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.3521
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

C:\Windows\Microsoft.NET\Framework\v3.5>csc
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.715
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

[] NT Services w/ windows 7 ...

The following services that are automatically started when Windows is up running:

Background Intelligent Transfer Service, Base Filtering System, COM+ Event System, Cryptographic Services, DCOM Server Process Launcher, Desktop Window Manager Session Manager, DHCP Client, Diagnostic Policy Service, Distributed Link Tracking Client, DNS Client, Group Policy Client, IKE and AuthIP IPsec Keying Modules, IP Helper, Network Location Awareness, Network Store Interface Service, Offline Files, Plug and Play, Power, Print Spooler, Remote Procedure Call, Security Accounts Manager, Security Center, Server, Shell Hardware Detection, Software Protection, Superfetch, System Event Notification Service, Task Scheduler, TCP/IP NetBIOS Helper, Themes, User Profile Service, Windows Audio, Windows Audio Endpoint Builder, Windows Defender, Windows Driver Foundation, Windows Event Log, Windows Firewall, Windows Management Instrumentation, Windows Search, Windows Update, Workstation.

The following shown here whose services are manually started:

Application Experience, Diagnostic Service Host, Diagnostic System Host, Function Discovery Provider Host, Function Discovery Resource Publicatioin, HomeGroup Provider, Network Connections, Network List Service, Portable Device Enumerator Service, Program Compatibility Assistant Service, SSDP Discovery.

The following services are disabled:

Internet Connection Sharing, Net.Tcp Port Sharing Service, Routing and Remote Access, Windows Media Center Extender Service, Windows Media Center Service Launcher.

The rest of them whose Startup Type is set to Manual:

Adaptive Brightness, AppID Service, Application Information, Application Layer Gateway Service, Application Management, BitLocker Drive Encryption Service, Block Level Backup Engine Service, Bluetooth Support Service, BranchCache, Certificate Propagation, CNG Key Isolation, COM+ System Application, Credential Manager Service, Disk Defragmenter, Distributed Transaction Coordinator, Encrypting File System, Extensible Authentication Protocol, Fax, Health Key and Certificate Management, HomeGroup Listener, Human Interface Device Access, Interactive Services Detection, KtmRm for DTC, Link-Layer Topology Discovery Mapper, Microsoft .NET Framework NGEN, Microsoft iSCSI Initiator Service, Microsoft Software Shadow Copy Provider, Netlogon, Network Access Protection Agent, Parental Controls, Peer Name Resolution Protocol, Peer Networking Grouping, Peer Networking Identity Manager, Performance Logs & Alerts, PnP-X IP Bus Enumerator, PNRP Machine Name Publication Service, Pong Service for Wireless USB, Problem Reports and Solutions Control Panel Support, Protected Storage, Quality Windows Audio Video Experience, Remote Access Auto Connection Manager, Remote Access Connection Manager, Remote Desktop Services, Remote Desktop Services Configuration, Remote Desktop Services UserMode Port Redirector, Remote Procedure Call Locator, Remote Registry, Secondary Logon, Secure Socket Tunneling Protocol Service, Sensors MTP Monitor Service, Smart Card, Smart Card Removal Policy, SNMP Trap, SPP Notification Service, Tablet PC Input Service, Telephony, Thread Ordering Server, UPnP Device Host, Virtual Disk, Volume Shadow Copy, WebClient, Windows Backup, Windows Biometric Service, Windows CardSpace, Windows Color System, Windows Connect Now, Windows Error Reporting Service, Windows Event Collector, Windows Font Cache Service, Windows Image Acquisition, Windows Installer, Windows Media Center Receiver Service, Windows Media Center Scheduler Service, Windows Media Player Network Sharing Service, Windows Modules Installer, Windows Presentation Foundation Font Cache 3.0.0.0, Windows Remote Management, Windows Time, WinHTTP Web Proxy Auto-Discovery Service, Wired AutoConfig, WLAN AutoConfig, WMI Performance Adapter, WWAN AutoConfig.

These are services that are new to me:-

Adaptive Brightness properties are:
Service name: SensrSvc
Description: Monitors ambient light sensors to detect changes in ambient light and adjust the display brightness.

AppID Service properties are:
Service name: AppIDSvc
Description: Disabling this service will prevent Application Control Policies from being enforced.

Block Level Backup Engine Service properties are:
Service name: wbengine
Description: The WBENGINE service is used by Windows Backup to perform backup and recovery operations. If this service is stopped by user, it may cause the currently running backup or recovery operation to fail. Disabling this service may disable backup and recovery operations using Windows backup on this machine.

BranchCache properties are:
Service name: PeerDistSvc
Description: This service caches network content from peers on the local subnet.

HomeGroup Listener properties are:
Service name: HomeGroupListener
Description: Makes local computer changes associated with configuration and maintenance of the homegroup-joined computer.

HomeGroup Provider properties are:
Service name: HomeGroupProvider
Description: Performs networking tasks associated with configuration and maintenance of homegroups.

Pong Service for Wireless USB properties are:
Service name: PngSvc
Description: The PngSvc service hosts the cable based association module for Wireless USB devices. Cable association involves establishing trust between a Wireless USB device and host by exchanging a secret key over a USB cable.

Windows Biometric Service properties are:
Service name: WbioSrvc
Description: The Windows biometric service gives client applications the ability to capture, compare, manipulate, and store biometric data without gaining direct access to any biometric hardware or samples. The service is hosted in a privileged SVCHOST process.

WWAN AutoConfig properties are:
Service name: WwanSvc
Description: This service manages mobile broadband (GSM & CDMA) data card/embedded module adapters and connections by auto-configuring the networks. It is strongly recommended that this service be kept running for best user experience of mobile broadband devices.

[] Windows Features w/ windows 7 ...

Available features are as follows:

ActiveX Installer Service
Games
Indexing Service
Internet Information Services
Internet Information Services Hostable Web Core
Microsoft .NET Framework 3.5.1 <--- new
Microsoft Message Queue Server
Printing and Document Services
Ras CMAK feature
Remote Differential Compression
RIP Listener
Services for NFS
Simple Network Management Protocol
Simple TCPIP services
Subsystem for UNIX-based Applications
Tablet PC Components
Telnet Client
Telnet Server
TFTP Client
Windows Gadget Platform <--- new
Windows OCR
Windows Process Activation Service
XPS

[] Test Lab w/ Windows 7 ...

Using VMware 6.0.2 to run Windows 7 beta was best way to test the latest operating system.

The OSVersionInfo that I has got here:-
Major Version: 6
Minor Version: 1
Build number: 7000
BuildLabs: 7000 winmain_win7beta 081212-1400
EULAID: Win7_B.1_PRO_NRL_en-US
DVD ISO: 2.47GB
Shift-F10 during installation: Microsoft Windows [6.1.7000]
Windows Media Player: 12.0.7000.7000

Disk Management Layout:-

Disk 0 #1 200MB NTFS
marked as 'Active, System, Primary Partition'
has no drive letter

Disk 0 #2 19.80GB NTFS
marked as 'Boot, Page File, Crash Dump, Primary Partition'
has drive letter (C:)

To remove the 'Send Feedback' at top right of dialog, HKCU\ Control Panel\ Desktop\ FeedbackToolEnabled (DWORD), changed from its default value of '3' to '0'.

Phew!

Thursday, January 22, 2009

building a Zoo Tycoon

Way back in the year 2003, I bought a complete set of Zoo Tycoon and am still enjoying playing it. It expands one's creativity by matching and mixing different zoo animals, marine animals and the most interesting, is the dinosaurs! Each scenario earns zoo rating and donations from the guests. My target goes as high as 90% zoo rating when there are more exhibits especially for good mixtures of animals. For example, hippotamus with flamingo, and ostrich family consists of common wildbeest, and thomson gazelle. Sell away their babies each few months to earn extras. Twice the 8x8 exhibits for Africa buffalo for ten members surrounded with tall grasses and small rocks. They are savannah animals which are easily tended by zookeepers.

There are few scenarios that reaches 86% (zoo rating) such as lochness monster, giant tortoise, stegosaurus, camptosaurus, western manatee, and common sawfish; the former four animals are dinosaurs while the last two are marine animals. As more and more exhibits are being added so does the zoo rating increases. For example, after putting bottlenose dolphin, dolphin show, and ostrich family, the zoo rating is 86%, then adding another three zoo animals, such as, hippotamus family, black buck, and spotted hyena, the zoo rating is increased by 2%, then add four dinosaurs, the final score is 90%. Another scenario for this kind of zoo rating will be: bottlenose dolphin with its show, ostrich family, Africa buffalo, hippotamus family, and beluga, and the four dinosaurs. There is once when the zoo rating reaches 92% for 13 exhibits -- bottlenose dolphin, lochness monster, giant tortoise, stegosarus, camptosaurus, ostrich family, hippotamus family, plain zebra, beluga, black buck, spotted hyena, black rhino, and wild dog.

The best is to modify the Kids themes by removing all the existing objects except the bottlenose dolphin and its show. With just six exhibits, the zoo rating goes from 93% onwards -- ostrich family, plain zebra, western manatee, beluga, and black rhino.

You can also mix sea turtle and barracuda with whale shark family. What a challenging game!

Tuesday, January 20, 2009

store data in an array

PS> 1, 2.5, "oranges", (Get-Process svchost)

1 <--- an integer
2.5 <--- a double precision floating point number
oranges <--- a string
... <--- a Process object

how powershell expression evaluates 9 (numeric)

PS> 4 + 5

PS> $(4 + 5)

PS> "$(4 + 5)"

9

count all running processes

PS> $processCount = (get-process).count
PS> "$processCount processes running in the system."

21 processes running in the system.

backtick for dollar sign

to escape the dollar sign using a backtick

PS> $a = "hello"
PS> $b = "`$a there"
PS> $b

$a there

focus on how the powershell process object has been configured

PS> get-process powershell
| FL PSConfiguration


Name : powershell
Id : 896
PriorityClass : Normal
FileVersion : 6.1.6585.1 (fbl_srv_powershell_ctp.080411-1634)

report on the system resources

to report on the system resources that are being used by powershell process object

PS> get-process powershell
| FL PSResources


Name : powershell
Id : 896
HandleCount : 505
WorkingSet : 4820992
PagedMemorySize : 47415296
PrivateMemorySize : 47415296
VirtualMemorySize : 203001856
TotalProcessorTime : 00:00:14.1718750

display processes's alias property

PS> get-process
| get-member -type AliasProperty


TypeName: System.Diagnostics.Process

Name MemberType Definition
---- ---------- ----------
Handles AliasProperty Handles = Handlecount
Name AliasProperty Name = ProcessName
NPM AliasProperty NPM = NonpagedSystemMemorySize
PM AliasProperty PM = PagedMemorySize
VM AliasProperty VM = VirtualMemorySize
WS AliasProperty WS = WorkingSet or physical memory

access the certification store

PS> get-childitem cert:


Location : CurrentUser
StoreNames : {UserDS, AuthRoot, CA, Trust...}

Location : LocalMachine
StoreNames : {AuthRoot, CA, Trust, Disallowed...}


PS> get-childitem cert:\CurrentUser\CA


It shows 'Thumbprint', 'Subject' headers.

The Subject header has 'CN=Root Agency', MS WHC, VeriSign Class 2 etc.

export and import processes by using a variable

step 1) PS> $p = get-process

step 2) Now write the variable to a CSV file and a CliXML file:
PS> $p | export-CSV .\test.csv
PS> $p | export-CliXML .\test.xml

step 3) Now import these values into two new variables:
PS> $p1 = import-csv .\test.csv
PS> $p2 = import-CliXML .\test.xml

step 4) To view their output from these variables:
PS> $p1 <----------- in a list format
PS> $p2 <----------- in a tabular format

list of processes using $_

to list of processes but display the name and CPU time

PS> get-process
| forEach-object { write-host $_.ProcessName $_.CPU }

store them into a variable

to list all processes and sort these in descending order according to their CPU time, and store them into a variable

PS> $a = get-process
| sort-object CPU -descending

PS> $a

the "format.ps1xml" files

to display Explorer process object by using the views (tree) defined in the "format.ps1xml" files in PS directory

PS> get-process explorer
| format-custom Modules

class Process
{
Modules =
[
class ProcessModule
{
...
class FileVersionInfo
{
...

CPU clock cycles

to list all processes running on a local machine that are using more CPU clock cycles than other processes

PS> Get-Process |
ForEach-Object `
{if ($_.cpu -lt 100)
{Write-Host $_.name, $_.cpu -foregroundcolor Yellow}
elseif ($_.cpu -gt 100)
{Write-Host $_.name, $_.cpu -foregroundcolor Cyan}}


We use an if statement to decide on the color of the text to display. If the amount of CPU time is less than 100, then the color of text is yellow. If it is more than 100, then we change the color of the text to cyan.

list detailed information with FL and FT

to list the modules property of Explorer process object

PS> get-process explorer
| fl Modules

or,

PS> get-process explorer
| fl -property name,modules

or,

PS> get-process explorer
| ft modules -wrap

or,

PS> get-process explorer
| fl Modules
| out-file 'test2.htm'


Modules : {System.Diagnostics.ProcessModule (Explorer.EXE), System.Diagnostics.ProcessModule (ntdll.dll), System.Diagnostics.ProcessModule (kernel32.dll), System.Diagnostics.ProcessModule (ADVAPI32.dll)...}

write-warning = write-verbose = yellow

to display the message

PS> $WarningPreference = "Continue"

Write-Warning "Stopping SQL Service..."

or,

PS> $VerbosePreference = "Continue"

Write-Verbose -message "SQL Service has been started. You may proceed..."

(Yellow on Black if powershell.exe in V1.0 or above)
(Black on White if gpowershell.exe in V2CTP2)
(Black on White if powershell_ise.exe in V2CTP3)

Monday, January 19, 2009

two nested for-loops

to display the progress of two nested for-loops

PS> for ($i = 1; $i -lt 101; $i++ )
{for ($j=0;$j -lt 10000;$j++) {} write-progress -activity "Search in Progress" -status "% Complete:" -percentcomplete $i;}

Explanation: The Write-Progress command includes a status bar heading (-activity), a status line, and the variable, $i (the counter in the for-loop), that indicates the relative completeness of the task. The second for-loop is the time counter.

The characters 'Search in Progress', '% Complete:' and repeating 'o' are shown in yellow on a teal progress bar. Graphical Windows PowerShell (V2CTP2) won't see this animation.

start and stop the Calc process

to start and stop the Calc process and then detects processes that have stopped

PS> calc <---- start the Calc process

PS> $p = get-process calc <---- get an object and store it

PS> stop-process -inputobject $p <----- stop the Calc process

PS> get-process | where-object {$_.HasExited}

` HasExited ` is a property of process object. Because the Calc process has been stopped, the value of HasExited property is TRUE, so there is no output.

stop a particular instance of the Notepad process by its ID

PS> stop-process -id 3952 -confirm -passthru

Explanation: ` -confirm ` parameter prompts the user before stopping the process. Because the prompt includes the process name, as well as its ID, this is best practice. ` -passthru ` parameter passes the process object to the formatter for display. (This is not applicable to graphical powershell)

stop all instances of the Notepad process

PS> stop-process -name Notepad

Explanation: (Each instance of Notepad runs in its own process.) It uses the Name parameter to specify the processes, all of which have the same name. If you were to use the ID parameter to stop the same processes, you would have to list the process IDs of each instance of Notepad.

list the running processes grouped by priority

PS> $a = get-process

PS> get-process -inputobject $a
| format-table -view priority

Explanation: The first command gets all of the processes on the computer and stores them in the $a variable. The second command uses the InputObject parameter to pass the process objects that are stored in the $a variable to Get-Process. The pipeline operator passes the objects to the Format-Table cmdlet, which formats the processes by using the "Priority" view defined in the PS1XML format files in the Windows PowerShell home directory ($pshome).

PriorityClass: Normal/ High. It shows properties such as ProcessName, Id, HandleCount, WorkingSet

working set

to get all running processes that have a working set greater than 20 MB

PS> get-process
| where-object {$_.WorkingSet -gt 20000000}

` -gt ` stands for 'greater than'.

` 20000000 ` is in bytes.

The pipeline operator ( | ) passes the process objects to the 'Where-Object' cmdlet, which selects only the object with a value greater than 20,000,000 bytes for the WorkingSet property.

data handling with an XML format

[] to get objects representing the commands in the history and export them to the History.xml file

PS> get-history
| export-clixml 'history.xml'

[] to show content of History.xml file using default web browser (if above done)

PS> .\history.xml

[] to import commands in the History.xml file and show them on the screen

PS> import-clixml 'history.xml'

[] to import commands in the History.xml file and add them to the current session history

PS> import-clixml 'history.xml'
| add-history -passthru

` -passthru ` parameter shows the current session history on the screen, and won't store them into the History.xml file. The 'Id' is changing.

[] to import data from a Log file and store them into Xmlfile1.xml

PS> get-content .\Dec16-1205hr.PS2CTP2.log
| export-clixml xmlfile1.xml

or,

PS> get-content .\Dec16-1205hr.PS2CTP2.log
| ConvertTo-html
| Out-File htmfile1.htm

This is useful to know what is going on in "Action start..." and "Action ended..." in its .Log (20KB) file, by looking at Section tag in its .XML (510KB) file; .Htm (83KB) file shows garbage indeed.

get information about .NET Framework DLL

PS> [system.diagnostics.eventlog] | fl

Module : System.dll
Assembly : System, Version=2.0.0.0
BaseType : System.ComponentModel.Component
Namespace : System.Diagnostics
Name : EventLog
MemberType : TypeInfo

get information about operating system

PS> [Environment]::OSVersion | fl

On a Windows XP machine:
Platform : Win32NT
ServicePack : Service Pack 2
Version : 5.1.2600.131072
VersionString : Microsoft Windows NT 5.1.2600 Service Pack 2

On a Windows Vista machine:
Platform : Win32NT
ServicePack : Service Pack 1
Version : 6.0.6001.65536
VersionString : Microsoft Windows NT 6.0.6001 Service Pack 1

understand how Get-Date works

PS> get-date

Tuesday, December 16, 2008 9:49:29

PS> (get-date).ToLongTimeString()

9:49:45 <----- 24HR format

PS> (get-date).ToShortTimeString()

10:28 AM

PS> (get-date).ToLongDateString()

Tuesday, December 16, 2008

PS> (get-date).ToShortDateString()

2008-Dec-17

when XML denies CSV and HTM

to get the ServiceController objects for all of the services that are running in their own processes, then export this information to a CSV file

PS R:\> get-service
| where { $_.serviceType -eq "Win32OwnProcess" }
| export-csv -notype ./edit3.csv

or,

PS R:> get-service | where { $_.serviceType -eq "Win32OwnProcess" } | export-csv -notype ./edit3.csv


or,

PS R:\> get-service
| where { $_.serviceType -eq "Win32OwnProcess" }
| export-csv -notype ./edit3.htm <--- not applicable for .xml


` edit3.csv ` contains delimited (comma-separted) text.

match and go

to store configuration information

PS R:\> get-service
| where { $_.Name -match "w32time" }


Status Name DisplayName
------ ---- -----------
Stopped W32Time Windows Time

` $_ ` contains the current pipeline object.
if ` -match "" `, then it list out all.

run a cmdlet command from a cmd command

[] to run PowerShell commands from a cmd command prompt

step 1) press WinLogo-key 'R' and type cmd.exe

R:\> powershell.exe -command "get-service"

[] to run PowerShell commands from a Start | Run prompt

step 1) press WinLogo-key 'R' and type

PS> powershell -command "C:\Lindows\co\Administrator\wpsEventsClear.ps1"

[] to call PowerShell from a cmd command prompt that will sort the services

step 1) press WinLogo-key 'R' and type

R:\> powershell.exe -command "get-service | sort Name"

the entire command string is enclosed in quotation marks to prevent cmd from attempting to handle the pipeline.

list services to a text file

[] to output a table containing the names of running services to a file named 'RunningServices.txt'

PS R:\> get-service -ServiceName * |
>> where-object { $_.status -eq "running" } |
>> format-table ServiceName, Status |
>> out-file -filePath "r:\RunningServices.txt"
>>

[] to open with Notepad

PS R:\> .\RunningServices.txt

frontslash = backslash

to run PowerShell script (.ps1), either:

./cleantemp.ps1

or,

.\cleantemp.ps1

works!

begin with 'a' through 'f' and 'n' through 'z'

to find all services but exclude those whose service names begin with 'a' through 'f' and 'n' through 'z'

PS R:\> get-service -Name * -Exclude [a-fn-z]* |
>> sort-object Name | format-table Name, DisplayName -auto
>>


` >> ` appears when you press Enter-key before typing.

contain the character sequence

to find running services that contain the character sequence 'sql' in the service's name

PS R:\> get-service "*sql*"
| where-object { $_.status -eq "running" }

or,

PS R:\> get-service
| where-object { $_.status -eq "running" }
| where-object { $_.name -match ".*sql.*" }


Status Name DisplayName
------ ---- -----------
Running MSSQLServer MSSQLServer

something like "net"

to list out all services that are currently running, whose displayName is something like "net"

PS R:\> get-service
| where { $_.status -eq "running" -and $_.displayName -like "*net*" }

Status Name DisplayName
------ ---- -----------
Running clr_optimizatio... .NET Runtime Optimization Service v...
Running LmHosts TCP/IP NetBIOS Helper
Running Netman Network Connections
Running Nla Network Location Awareness (NLA)

list out all services and store them an MS Excel spreadsheet

PS>
$a = new-object -comobject excel.application
$a.Visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "Service Name"
$c.Cells.Item(1,2) = "Service Status"
$i = 2
get-service | foreach-object{ $c.cells.item($i,1) = $_.name; $c.cells.item($i,2) = $_.status; $i=$i+1}
$b.SaveAs("Test.xls")
$a.Quit()

Make sure you have installed MS Excel because it will register it as a COM-type, otherwise it can't load during processing.

list out all services and store them into a web page

step 1) to list and store
PS R:\> get-service | convertto-html > .\a10.html

step 2) to run a web page
PS R:\> .\a10.html

`a10.html` will show a detailed information such as ( Name, CanPauseAndContinue, CanShutdown, CanStop, DisplayName, DependentServices, MachineName, ServiceName, ServicesDependentOn, ServiceHandle, Status, ServiceType, Site Container )

display data in colors

to list out of all services by limiting to name and their status

PS R:\> get-service
| foreach-object { write-host -f yellow -b red $_.name $_.status }

` -f ` also can be coded as ` -foregroundcolor `.
` -b ` also can be coded as ` -backgroundcolor `

display data with DataGrid

to tabulate a list of all services by sorting the services by their state before filling the datagrid, then output the processes

PS>
[void][System.reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
$form = new-object System.Windows.Forms.Form
$DataGridView = new-object System.windows.forms.DataGridView
$Form.Text = "My First Datagrid"
$array= new-object System.Collections.ArrayList

$array.AddRange( @( get-service | write-output ) )
// $array.AddRange( @( get-process | sort-object company | write-output ) )

$DataGridView.DataSource = $array
$DataGridView.Dock = "fill"
$DataGridView.AllowUsertoResizeColumns=$True
$form.Controls.Add($DataGridView)
$form.showdialog()


For Get-Service cmdlet, the column headers in datagrid shows (Name, CanPauseAndContinue, CanShutdown, CanStop, DisplayName, ServiceName, Status)

For Get-Process cmdlet, the column headers in datagrid shows ( _NounName, Name, Handles, VM, WS, PM, NPM, Path, Company, CPU, FileVersion, ProductVersion, Description, Product, BasePriority, HandleCount, Id, etc. ) or, get-process | fl *

depend on WMI service vs WMI service depend on

[] to list out all services that depend on WMI service

PS> (Get-Service winmgmt).DependentServices

Status Name DisplayName
------ ---- -----------
Stopped wscsvc Security Center
Stopped SharedAccess Windows Firewall/ICS

[] to list out all services that WMI service depend on

PS> (Get-Service winmgmt).ServicesDependedOn

Status Name DisplayName
------ ---- -----------
Running RPCSS Remote Procedure Call (RPC)

'start', 'stop' mssqlserver

[] to start a service by calling the ServiceController.Start method

PS R:\> (Get-Service mssqlserver).Start()

MSDE7 icon at system tray turned from 'Red' to 'Green'

[] to stop a service by calling the ServiceController.Stop method

PS R:\> (Get-Service mssqlserver).Stop()

MSDE7 icon at system tray turned from 'Green' to 'Red'

grouping services

[] to get a report of all services and count total number of 'running' and 'stopped' status

PS> get-service | group-object status

Count Name Group
----- ---- -----
58 Stopped {System.ServiceProcess.ServiceController...}
29 Running {System.ServiceProcess.ServiceController..}

[] to show all services in the "Stopped" group

PS R:\> (get-service | group-object status)[0].group

[] to show all services in the "Running" group

PS R:\> (get-service | group-object status)[1].group

services depend on services

[] to list the services on the computer that have dependent services

PS R:\> get-service | where-object {$_.DependentServices}

Status Name DisplayName
------ ---- -----------
Running dmserver Logical Disk Manager
Running EventSystem COM+ Event System
Stopped lanmanserver Server

[] to display the complete list of dependent services of MSSQLSERVER service

PS R:\> (get-service mssqlserver).dependentservices

Status Name DisplayName
------ ---- -----------
Stopped SQLServerAgent SQLServerAgent

[] to display the number of dependent services that each service has

PS> get-service | where-object {$_.DependentServices} | format-list -property Name, DependentServices, @{Label="NoOfDependentServices"; Expression={$_.dependentservices.count}}

Name : lanmanworkstation
DependentServices : {RpcLocator, Netlogon, Messenger, Browser...}
NoOfDependentServices : 5

use of a pipe for plumber work?

to display only the services that are currently running

PS R:\> get-service | where-object {$_.Status -eq "Running"}

or,

PS R:\> get-service | where { $_.Status -eq "Running" }


` | ` is a pipeline operator, which passes the results to the Where-Object cmdlet, which selects the services with a Status property that equals "Running".

` -eq ` represents ' equal to '.

` Status ` is only one property of service objects.

` $_ ` is the current object operator, which indicates that the cmdlet will example the Status property of each service as it goes through the pipeline.

beginning with an 'n'

[] to list out the service name (not the displayName) beginning with 'n'

PS> get-service -include n*

[] to list out the service (displayName) beginning with 'n'

PS> get-service -displayName n*

[] to display only the service names that begin with 'n'

1) gets the services (name, not DisplayName) on the system and then stores them in the $input1 variable

PS R:\> $input1 = get-service

2) gets the services in the $input1 variable, but includes only those that begin with 'n'

PS R:\> get-service -inputobject $input1 -include n*

'-InputOutput` parameter passes the objects stored in the variable to Get-Service.

when 'Stopped' comes before 'Running'...

to sort in ascending order by status value

PS R:\> gsv | sort-object -property status

Stopped ... <---- sort mechanism takes this as integer value of '1'
Running ... <---- sort mechanism takes this as integer value of '4'

'gsv' is the built-in alias of 'get-service'

create the $out1 variable

to create the $out1 variable (will be removed once PS window is exit)

1) stores the service object in it

PS> get-service browser -OutVariable out1

2) append the service object to the content of $out1

PS> get-service wmi -OutVariable +out1

3) display the contents of $out1

PS> $out1

get OSVersion information in html format

PS> [environment]::OSversion
| convertto-html
| out-file 'r:\test1.html'

To view with web browser,

./test1.html

whether AllSigned or Restricted, let PS1 go

to execute PowerShell script (.ps1) w/o initilizing each code signing

step 1) REGEDIT4

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
"ExecutionPolicy"="Unrestricted"

By default, the above parameter is not initialised during first time installation. This parameter will remain in the system registry until you remove it manually.

step 2) open powershell object-based function
PS> .\stopit.ps1

use of [math]:: calculation

[] to evaluate (PI + 2)

PS R:\> invoke-expression ([math]::PI + 2)

5.14159265358979

[] to evaluate Sine 90 degree to nearest whole number

PS R:\> $d1 = [math]::Sin(90)
PS R:\> [math]::Round($d1)

1

[] to evaluate 2^32 and 2^64

PS R:\> [math]::Pow(2,32)

4294967296

PS R:\> [math]::Pow(2,64)

1.84467440737096E+19

Pow(2,49) is the maximum power to show a non expontient

[] to get the value in terms of TeraByte of 2^49

PS R:\> [math]::Pow(2,49)

562949953421312

PS R:\> [math]::Pow(2,49) /1TB

512

where and what

[] to locate where powershell.exe installed

PS R:\> [environment]::CommandLine


"C:\LINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe"


[] to determine what logon user currently using powershell

PS R:\> [environment]::CurrentDirectory


c:\Lindows\co\Administrator

use of NewLine

to identify the type of OS with service pack

PS R:\> $line1 = [environment]::NewLine
PS R:\> $line2 = [environment]::OSVersion
PS R:\> $line3 = $line1 + $line2
PS R:\> $line3



Microsoft Windows NT 5.1.2600 Service Pack 2

'NewLine' will leave a block of 4 rows of spaces

delete unwanted registry key

to delete both the 'PSHome' and 'PowerShellPath' registry entries

PS> Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PSHome

PS> Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath

rename existing registry key

to rename the PowerShellPath entry to "PSHome" and display the renamed value

PS> Rename-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -NewName PSHome -passthru

change MaxSize of EventLog via registry

to overwrite a pre-existing registry entry value

PS> New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\Eventlog\Application -Name MaxSize -PropertyType DWord -Value 512 -force

'512' is in decimal format; it means 512KB

add new registry key

to add a new entry named 'PowerShellPath' to the CurrentVersion key, and return information about the new entry

PS> New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -PropertyType String -Value $PSHome

PowerShellPath
--------------
C:\LINDOWS\system32\WindowsPowerShell\v1.0\

change system's prompt

to change to the CurrentVersion registry container

PS> Set-Location -Path hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion

Change from original prompt
`PS C:\Lindows\co\Administrator>`

to

new prompt
`PS HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion>`

access CurrentVersion of HKLM

to view the registry entries in a more readable form

PS> Get-ItemProperty -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion

DevicePath : C:\LINDOWS\inf
MediaPathUnexpanded : C:\LINDOWS\Media
SM_GamesName : Games
SM_ConfigureProgramsName : Set Program Access and Defaults
ProgramFilesDir : c:\Lindows\cn <--- release Vista's journaling
CommonFilesDir : c:\Lindows\cn <--- release Vista's journaling
ProductId : 55274-642-3428963-23367
WallPaperDir : C:\LINDOWS\Web\Wallpaper
MediaPath : C:\LINDOWS\Media
ProgramFilesPath : C:\LINDOWS\cn <--- release Vista's journaling
SM_AccessoriesName : Accessories
PF_AccessoriesName : Accessories

'C:\LINDOWS' is alternative method of consolidating %ProgramFiles% and %Documents and Settings%, where Vista won't overwrite its system files.

copy items recursively

[] to copy the folder C:\temp\test1 to the new folder c:\temp\DeleteMe recursively

PS> Copy-Item C:\temp\test1 -Recurse c:\temp\DeleteMe

[] to copy all .txt files contained anywhere in c:\data to c:\temp\text

PS> Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination c:\temp\text

be the force with you...

to overwrite a pre-existing destination, even when it is read-only

PS> Copy-Item -Path c:\boot.ini -Destination c:\boot.bak -Force

back-up an item

to back up C:\boot.ini to C:\boot.bak

PS> Copy-Item -Path c:\boot.ini -Destination c:\boot.bak

get all items

[] to get all items within a folder

PS> Get-ChildItem -Force C:\

[] to to list everything on the C drive

PS> Get-ChildItem -Force C:\ -Recurse

[] to find all executables within the Program Files folder that were last modified after October 1, 2005 and which are neither smaller than 1 megabyte nor larger than 10 megabytes

PS> Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe
| Where-Object -FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}

network share and networked drive

[] to create a network share

PS> (Get-WmiObject -List -ComputerName . | Where-Object -FilterScript {$_.Name -eq "Win32_Share"}).Create("C:\temp","TempShare",0,25,"test share of the temp folder")

[] to remove a network share

PS> (Get-WmiObject -Class Win32_Share -ComputerName . -Filter "Name='TempShare'").Delete()

[] to create a new networked drive that maps the share \\FPS01\users to local drive B:

PS> (New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users")

Win32_NetworkAdapterConfiguration betw. Win32_NetworkAdapter

[] to retrieve network adapter information such as MAC addresses and adapter types

PS> Get-WmiObject -Class Win32_NetworkAdapter -ComputerName .

[] to find the DHCP-enabled adapters on a computer

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "DHCPEnabled=true" -ComputerName .

[] to find the IP-enabled adapters on a computer

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true and DHCPEnabled=true" -ComputerName .

[] to enable DHCP on all adapters

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName .
| ForEach-Object -Process {$_.EnableDHCP()}

[] to releases all DHCP leases on adapters on the local computer that are obtaining DHCP leases from 192.168.1.254

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true and DHCPEnabled=true" -ComputerName .
| Where-Object -FilterScript {$_.DHCPServer -contains "192.168.1.254"}
| ForEach-Object -Process {$_.ReleaseDHCPLease()}

[] to renew a DHCP lease

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true and DHCPEnabled=true" -ComputerName .
| Where-Object -FilterScript {$_.DHCPServer -contains "192.168.1.254"}
| ForEach-Object -Process {$_.ReleaseDHCPLease()}

ping with Win32_PingStatus class

[] to ping against a computer (Address, ResponseTime)

PS> Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .
| Format-Table -Property Address,ResponseTime,StatusCode -Autosize

[] to ping all of the computers on a subnet

PS> 1..254
| ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='192.168.1." + $_ + "'") -ComputerName .}
| Select-Object -Property Address,ResponseTime,StatusCode

Private network number (192.168.1.0) and Class C subnet mask (255.255.255.0)

gets IP addresses, DHCP, DNS, routing

[] to get all IP addresses in use on the local computer

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Format-Table -Property IPAddress

[] to display detailed IP configuration data for each network adapter

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .

[] to display detailed information about DHCP, DNS, routing

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*

add/remove printer

[] to add a new network printer

PS> (New-Object -ComObject WScript.Network).AddWindowsPrinterConnection("\\Printserver01\Xerox5")

[] to set the default printer

PS> (Get-WmiObject -ComputerName . -Class Win32_Printer -Filter "Name='HP LaserJet 5Si'").SetDefaultPrinter()

or,
PS> (New-Object -ComObject WScript.Network).SetDefaultPrinter('HP LaserJet 5Si')

[] to remove a printer connection

PS> (New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5")

log-off, shut-down, re-boot system

[] to logoff current session

PS> (Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(0)


[] to shut down the computer

PS> (Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(1)


[] to reboot the operating system

PS> (Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(2)

list the applications installed with the Windows Installer (MSI)

[] to list the applications installed with the Windows Installer, esp. those hidden from appwiz.cpl, in a summary

PS> Get-WmiObject -Class Win32_Product -ComputerName .

IdentifyingNumber : {95120000-00B9-0409-0000-0000000FF1CE}
Name : Microsoft Application Error Reporting
Vendor : Microsoft Corporation
Version : 12.0.6012.5000 <--- SQL Server 2008 component
Caption : Microsoft Application Error Reporting


[] to list the applications installed with the Windows Installer, esp. those hidden from appwiz.cpl, in detail

PS> Get-WmiObject -Class Win32_Product -ComputerName . | fl -Property *

Extra information are InstallDate, PackageCache etc.


[] to list the applications installed with the Windows Installer, esp. those hidden from appwiz.cpl, in specified properties

PS> Get-WmiObject -Class Win32_Product -ComputerName . | fl -Property Name,InstallDate,InstallLocation,PackageCache,Vendor

Name : Microsoft Application Error Reporting
InstallDate : 20081130
InstallLocation :
PackageCache : C:\LINDOWS\Installer\583d7.msi
Vendor : Microsoft Corporation


[] to find only the names of installed applications using Windows Installer

PS> Get-WmiObject -Class Win32_Product -ComputerName . | fw -Column 1

MSXML4 Parser
Microsoft Application Error Reporting
Microsoft .NET Framework 3.0 Service Pack 2
Microsoft .NET Framework 3.5 SP1
Windows PowerShell(TM) V2 (CTP2)
Microsoft Office Access 2003 Runtime
Microsoft .NET Framework 2.0 Service Pack 2

is .NET CLR 2.0 running now?

to identify NT services' StartMode, ProcessId, and State

PS> Get-WmiObject -Class Win32_Service -ComputerName .

ExitCode : 0
Name : clr_optimization_v2.0.50727_32
ProcessId : 1492
StartMode : Auto
State : Running
Status : OK

When PowerShell v1.0, V2CTP2, or V2CTP3 is used for this project.

retrieve the current local time

PS> Get-WmiObject -Class Win32_LocalTime -ComputerName .
| Select-Object -Property [a-z]*

Information like DayOfWeek, WeekInMonth, Quarter etc.

get information summary of CPU, OS, Licenses

[] to get version information summary of current CPU and OS

PS> Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property BuildNumber,BuildType,OSType,ServicePackMajorVersion,ServicePackMinorVersion


BuildNumber : 2600 <---- SP2
BuildType : Uniprocessor Free
OSType : 18 <---- XP
ServicePackMajorVersion : 2
ServicePackMinorVersion : 0


[] to retrieve information e.g. number of licensed users, current number of users, and owner name

PS> Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property *user* | fl


NumberOfLicensedUsers :
NumberOfUsers : 2
RegisteredUser : Jose Clinton <--- UserName

My laptop software configuration.

list all installed hotfixes

to list all installed hotfixes Id only

PS> Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName . -Property HotFixId | Select-Object -Property HotFixId

HotFixId
--------
File 1
File 1
File 1
Q147222
KB942288-v3
KB954550-v5
XpsEPSC

provide OEM data of computer model

PS> Get-WmiObject -Class Win32_ComputerSystem


Domain : WORKGROUP
Manufacturer : Acer
Model : Aspire 5610
Name : NPARKS <--- ComputerName
PrimaryOwnerName : Jose Clinton <--- UserName
TotalPhysicalMemory : 1063309312 <--- in bytes; 1GB

My laptop configuration.

retrieve CPU information

PS> Get-WmiObject -Class Win32_Processor -ComputerName .

Information like CurrentClockSpeed, CurrentVoltage, L2CacheSize, ExtClock, MaxClockSpeed, ProcessorId, SocketDesignation etc.

collect information about the desktops

to collect information about the desktops on the local computer

PS> Get-WmiObject -Class Win32_Desktop -ComputerName .

Information like IconSpacing, IconTitleFaceName, ScreenSaverTimeout, Wallpaper etc.

restart multiple services

to restart multiple services by getting a list of services, filter them, and then perform the restart

PS> Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service

start the print spooler NT service

PS> start-service -name spooler

Do this step when the Spooler service has stopped.

stop the MSDE7 SQL server NT service

PS> stop-service -name mssqlserver -force

WARNING: Waiting for service 'MSSQLServer (MSSQLServer)' to finish stopping...

'-force' must be applied here because it has dependencies.

Others are Logical Disk Manager, COM+ Event System, Workstation, Network Connections, SSDP Discovery Service, Windows Management Instrumentation.

determine which NT services have stopped or still running

PS> get-service | sort-object -Property Status

terminate sessions of SQL

to terminate sessions of SQL Server with confirming

PS> get-process -name sql* | stop-process -passthru

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
52 2 900 3020 47 0.05 1564 sqlmangr

Warning!
Are you sure you want to perform this action?
Performing operation 'Stop-Process' on Target 'sqlservr(1072)'
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):l <--- stands for 'No to All'

prompt before proceed

to stop process with confirmation

PS> stop-process -Name * -confirm

Confirm
Are you sure you want to perform this action?
Performing operation "Stop-Process" on Target "csrss (472)".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):n <---- stands for 'No'

show the CPU identification

to see the CPU identification

PS> $env:Processor_Identifier

x86 Family 6 Model 14 Stepping 8, GenuineIntel

My laptop is Intel Centrino processor type.

Sunday, January 18, 2009

check the version of Windows PowerShell

PS> $PSVersionTable

Name Value
---- -----
CLRVersion 2.0.50727.3053 <--- SP2
BuildVersion 6.1.6585.1 <--- Vista SP1
PSVersion 2.0 <--- V2CTP2/3
PSCompatibleVersions {1.0, 2.0} <--- v1.0 RTM or above

arrange the list in reverse order

to sort the objects in reverse order by ProcessName

PS> get-process | sort-object -Property Name -descending

The way Sort-Object cmdlet works:

0a <-- Zero first then letter 'a'
0A
A0
a0

F
f
Ff
fF

quick view of free disk space and drive type

[] to return free space information for each local disk in terms of bytes

PS> get-wmiobject -class win32_logicaldisk | ft -auto -Property DeviceId,DriveType,FreeSpace,Size,VolumeName

DeviceId DriveType FreeSpace Size VolumeName
-------- --------- --------- ---- ----------
C: 3 9533083648 20958011392 ACER
D: 3 2435698688 4992708608 MISC
E: 3 28816961536 50668896256 DATA
F: 5 <---- CDROM drive
R: 3 16655360 16694784 RamDisk
S: 5


[] to return free space information for each local disk in terms of GB

PS> Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace | ForEach-Object -Process {$_.FreeSpace = ($_.FreeSpace)/1024.0/1024.0/1024.0; $_} | ft -auto

Name FreeSpace
---- ---------
C: 8.87826919555664
D: 2.2684211730957
E: 26.8378868103027
F: 0
R: 0.0155115127563477
S: 0

system drivers running endlessly

to list out the 'Running' State of system drivers

PS> Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"}

DisplayName : XAudio <--- a sample
Name : XAudio
State : Running
Status : OK
Started : True

1,2,3,4 but give me 1 and 2

to return the ones from a list of numbers that are less than 3

PS> 1,2,3,4 | where-object -filterscript {$_ -lt 3}

1
2

'lt' stands for 'less than'.

round off 2 decimal numbers

to round off the value of '24.49' to nearest whole number

PS> [System.Math]::Round(24.49)

24 <--- notice it is not '24.5' then '25'

give me PI

to identify the PI property of System.Math class

PS> [System.Math]::PI

3.14159265358979 (14 decimals)

identify CPU, Computer/Domain/User Name

[] to identify the number of CPU it has

PS> [System.Environment]::ProcessorCount

1 <--- Solo or one processor

[] to identify the computer name

PS> [System.Environment]::MachineName

NPARKS

or,

PS> [System.Environment]::UserDomainName

NPARKS

[] to identify the current logon account name

PS> [System.Environment]::UserName

Administrator

check the Major, Minor, Build, Revision

to identify the revision of .NET Framework 2

PS> [System.Environment]::Version

Major Minor Build Revision
----- ----- ----- --------
2 0 50727 3053 <---- SP2?

check the operating system version

PS> [System.Environment]::OSVersion | fl


Platform : Win32NT <--- 32-bit type; Next Technology
ServicePack : Service Pack 2
Version : 5.1.2600.131072 <--- Major, Minor, Build, Release?
VersionString : Microsoft Windows NT 5.1.2600 Service Pack 2

'::' indicate a static method or property. '[xxx]' indicate a class name.

wipe out entries not wanted in Event Log

to clear an event log's entries of the Application log

PS> $AppLog = new-object -typename system.diagnostics.eventlog -argumentlist application
PS> $AppLog

Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
51,200 -1 DoNotOverwrite 2,523 Application <--- before


PS> $AppLog.Clear()
PS> $AppLog

Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
51,200 -1 DoNotOverwrite 0 Application <--- after

gather total number of Event Log entries

to get information about an event log, e.g. Application

PS> new-object -typename system.diagnostics.eventlog -argumentlist application

Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
51,200 -1 DoNotOverwrite 2,523 Application

Event viewer won't show these valuable information.

display available memory data

[] to display available memory data

PS> Get-WmiObject -Class Win32_OperatingSystem -Property TotalVirtualMemorySize,TotalVisible
MemorySize,FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles

FreePhysicalMemory : 757084
FreeSpaceInPagingFiles : 2280892
FreeVirtualMemory : 2037184
TotalVirtualMemorySize : 2097024
TotalVisibleMemorySize : 1038388

[] to display available memory data more readable

PS> Get-WmiObject -Class Win32_OperatingSystem
| fl -Property TotalV*,Free*


TotalVirtualMemorySize : 2097024
TotalVisibleMemorySize : 1038388
FreePhysicalMemory : 758992
FreeSpaceInPagingFiles : 2280504
FreeVirtualMemory : 2037184

retrieve information about a computer

PS> get-wmiobject -class win32_operatingsystem


SystemDirectory : C:\LINDOWS\system32 <---- where drivers are stored
Organization : Regional Farmstay Inc. <---- same as Company
BuildNumber : 2600 <---- Service Pack 2
RegisteredUser : Jose Clinton <---- same as User Name
SerialNumber : 55274-642-3428963-23367 <---- actual is alphanumeric
Version : 5.1.2600 <---- Windows XP SP2

WMI classes from Local/Remote computer

[] to get a list of the WMI classes available on the local computer

PS> get-wmiobject -list

[] to get a list of the WMI classes available on the remote computer by specifying a computer name or IP address

PS> get-wmiobject -list -computername 127.0.0.1

make changes to a text file

to open a file in Notepad if .txt is associated

PS> invoke-item r:\new.directory\good.txt

delete information with permission rights

to delete the folder and its files without confirming

PS> remove-item r:\temp\new.directory -recurse

copy content of a directory from and to

[] to copy the 'New.Directory' directory from the R: drive to the 'r:\temp' directory

PS> copy-item -path r:\new.directory -destination r:\temp

[] to copy all of the contents of a folder and overwrite the empty folder (if above is done)

PS> copy-item -path r:\new.directory -destination r:\temp -recurse -force -passthru

move a directory from location to location

to move the 'New.Directory' from 'r:\temp' directory to the root of the R: drive and verify that the item was moved

PS> move-item -path r:\temp\new.directory -destination r:\ -passthru

change filename

to change the name of a file named 'file1.log' to 'file2.log'

PS> rename-item -path r:\temp\file1.log file2.log

create a registry key under HKLM

to create a registry key named '_Test' in the CurrentVersion subkey

PS> New-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\_Test


Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion

SKC VC Name Property
--- -- ---- --------
0 0 _Test {}

create a directory and file

[] to create a new directory named 'new.directory' in the 'r:\temp' directory

PS> new-item -path r:\temp\new.directory -itemtype directory

[] to create a file named 'file1.log' in the 'r:\temp' directory

PS> new-item -path r:\temp\file1.log -itemtype file


Directory: Microsoft.PowerShell.Core\FileSystem::R:\temp


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2008-Dec-10 7:39 PM 0 file1.log <--- empty content

find all files with specified criteria

[] to find all files in the Windows directory with the suffix .log and exactly five characters in the base name

PS> get-childitem -path c:\lindows\?????.log


Directory: Microsoft.PowerShell.Core\FileSystem::C:\lindows


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2008-Nov-30 12:41 PM 5868 ocgen.log
-a--- 2008-Dec-10 8:56 AM 194 setup.log

[] to find all files that begin with the letter 'c' in the Windows directory

PS> get-childitem -path c:\windows\system32\c*

[] to find all files whose names begin with 'u' or 'z'

PS> get-childitem -path c:\windows\system32\[uz]*

[] to find 32-bit Windows compatibility DLLs excluding Windows 95 and 16-bit type in the System32 folder

PS> get-childitem -path c:\windows\system32\w*32*.dll -exclude *[9516]*

[] to restrict the items to those that are in the Windows folder with names end with '*.dll', excluding those names from 'a to y'

PS> get-childitem -path c:\lindows -Include *.dll -recurse -exclude [a-y]*.dll

reveal R-O, S, H -attribute files

In Vista, to display hidden items

PS> get-childitem -path c:\users\administrator -force

access HKLM registry

to set your location (prompt) to the HKLM\Software key in the registry key

PS> set-location -path HKLM:\software -passthru

Path
----
HKLM:\software


PS HKLM:\software>

print out a list of processes

[] to send a list of processes to the unicode file

PS> get-process
| out-file -filepath d:\temp\sample.txt

[] to send a list of processes to default printer, e.g. doPDF

PS> get-process
| out-printer

[] to send a list of processes to the ASCII file

PS> get-process
| out-file -filepath d:\temp\sample.txt -Encoding ASCII

[] to save output as it would have displayed on the console

PS> get-process
| out-file -filepath d:\temp\sample.txt -Width 80

Maximum is 2147483647. For example, MS Notepad can accomodate a line that ends at position 1000th (when thewordwrap feature is disabled).

save as XPS image file

to send the data to an image file

PS> Get-command get-command
| out-printer -name "Microsoft Office Document Image Writer"

view content page by page

to read a specified file and page their contents to the host

PS> more startit.cmd

echo off
cls

color a
echo Starting Wireless Zero Configuration
pause
net start WZCSVC

echo.
echo Starting Windows Firewall
pause
net start SharedAccess

echo.
echo Starting Security Center
pause
net start wscsvc

-- More --

group processes

to group processes by name for easier inspection

PS> get-process -name svchost
| ft -Wrap -autosize path,company,id -groupby name


Name: svchost

Path Company Id
---- ------- --
C:\LINDOWS\system32\svchost.exe Microsoft Corporation 704
C:\LINDOWS\system32\svchost.exe Microsoft Corporation 768
C:\LINDOWS\System32\svchost.exe Microsoft Corporation 808
C:\LINDOWS\system32\svchost.exe Microsoft Corporation 856
C:\LINDOWS\system32\svchost.exe Microsoft Corporation 892

Saturday, January 17, 2009

system path environment

to see the paths in the Path environment variable

PS> $env:path

C:\LINDOWS\system32;C:\LINDOWS;C:\LINDOWS\System32\Wbem;"C:\LINDOWS\Microsoft.NET\Framew...

create & use Function

to create a function

PS> function bootini {notepad c:\boot.ini}

to run existing function

PS> bootini <---- if above is done

alias for Notepad

to create the alias "np" for Notepad

PS> set-alias np c:\lindows\notepad.exe

to remove the "np" alias

PS> remove-item alias:np

get-wmiObject

to get info about the BIOS on the local computer

PS> get-wmiobject win32_bios -computername nparks


SMBIOSBIOSVersion : V3.50
Manufacturer : Acer
Name : Ver 1.00PARTTBLP
SerialNumber : LXAU60J0077020D4581601
Version : ACRSYS - 6040000

get-command

to search for log file (.log) in a directory

PS> get-command -name *.log

$ variable operator

to perform an addition of two values

PS> $str1 = 4 + 5
PS> write-host "the result is" $str1

get-service

to list out all NT services status into a file
get-service | fl | out-file "r:\o1.txt"

get-service

[] to identify the status of NT service, e.g. xmlprov
PS> get-service xmlprov | fl


Name : xmlprov
DisplayName : Network Provisioning Service
Status : Stopped
DependentServices : {}
ServicesDependedOn : {RpcSs}
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
ServiceType : Win32ShareProcess

get-item

to find out the Mode, LastWriteTime, Length of current prompt
PS> get-item .


Directory: Microsoft.PowerShell.Core\FileSystem::C:\Lindows\co


Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2008-Dec-04 6:51 PM Administrator

stuff about PowerShell

Here is my research states:

- Windows PowerShell
Copyright (C) 2006 Microsoft Corporation. All rights reserved.

- Microsoft Windows® PowerShell is a new command-line shell and scripting language designed for system administration and automation. Built on the .NET Framework, Windows PowerShell enables IT professionals and developers control and automate the administration of Windows and applications.

- needs CLR 2.0

- processes objects (not text) based on the .NET platform.

- perform object-based (command-line) functions.

- relies heavily on the .NET framework

- all the built-in types are really .NET types

- works on xpsp2, svr2003sp1, vista sp1

- looks similar to that of MS-DOS command-line shell

- some knowledge of C# FCL, vbscript, sql, automation, DS, AD, batch

- a background in scripting and WMI are helpful

- is a Microsoft .NET-connected environment designed for administrative automation.

- provides a new approach to building commands, composing solutions, and creating management GUI tools.

- enables a system administrator to automate the administration of system resources by the execution of commands either directly or through scripts.

- run a command name can refer to
-- a Cmdlet (aka. Command-let)
-- single-function commands
-- have a verb-noun naming convention, such as Get-Help or Set-MachineName
-- an .ps1 script file
-- an executable file with the extension .bat, .cmd, .com, or .exe
-- WSH files with a .vbs, .js, .wsh, or .wsf extension rely on the WSH engine
-- UNIX Bash Shell internal command, e.g. man, clear, cat, mount, popd, sleep, h, ps, history, pushd, tee, kill, pwd, lp, r, write, diff, ls

- properties ( bits of data )

- methods ( actions )

automates the Upgrade to Win95

This script automates the upgrade to Windows 95, using settings from the existing Windows installation except for User Information. Setup will prompt for a User Name and Organization. You can modify this script to predefine the user name. This script also automatically installs the Accessibility features, and contains entries that can be modified to create a hands-free installation using predefined settings.

[SETUP]
; 0 = stop for user input, 1 = do not stop for user input
Express=1

; 0 = do not create startup disk, 1 = create startup disk
EBD=0

; 0 = do not allow user to choose Uninstall and do not back up existing Windows
; 1 = show Uninstall options for user to choose
; 5 = automatically create backup files for uninstalling Windows 95
uninstall=0

; 0 = prompt for confirmation before overwriting more recent files
; 1 = overwrite without confirmation
vrc=1

; Remove ";" and set this value to your 10-digit Windows 95 product ID,
; which is printed on the Windows 95 CD or your Certification of Authenticity.
ProductID=26099-oem-0070957-53008

; 0 = compact, 1 = typical, 2 = portable, 3 = custom setup type
InstallType=1

; Remove ";" from the value for your timezone
;TimeZone="Afghanistan"
;TimeZone="Alaskan"
;TimeZone="Arabian"
;TimeZone="Atlantic"
;TimeZone="AUS Central"
;TimeZone="Azores"
;TimeZone="Bangkok"
;TimeZone="Canada Central"
;TimeZone="Cen. Australia"
;TimeZone="Central"
;TimeZone="Central Asia"
;TimeZone="Central Pacific"
;TimeZone="China"
;TimeZone="Czech"
;TimeZone="Dateline"
;TimeZone="E. Europe"
;TimeZone="E. South America"
;TimeZone="Eastern"
;TimeZone="Egypt"
;TimeZone="Fiji"
;TimeZone="GFT"
;TimeZone="GMT"
;TimeZone="Greenwich"
;TimeZone="Hawaiian"
;TimeZone="India"
;TimeZone="Iran"
;TimeZone="Israel"
;TimeZone="Lisbon Warsaw"
;TimeZone="Mexico"
;TimeZone="Mid-Atlantic"
;TimeZone="Mountain"
;TimeZone="New Zealand"
;TimeZone="Newfoundland"
;TimeZone="Pacific"
;TimeZone="Romance"
;TimeZone="Russian"
;TimeZone="SA Eastern"
;TimeZone="SA Pacific"
;TimeZone="SA Western"
;TimeZone="Samoa"
;TimeZone="Saudi Arabia"
;TimeZone="South Africa"
;TimeZone="Sydney"
TimeZone="Taipei"
;TimeZone="Tasmania"
;TimeZone="Tokyo"
;TimeZone="US Eastern"
;TimeZone="US Mountain"
;TimeZone="W. Europe"
;TimeZone="West Asia"
;TimeZone="West Pacific"

; If you modify this script to define the user information,
; set Display=0 in the following section to skip the prompt.
; Type correct values for Name= and Org=, or accept defaults.
[NAMEANDORG]
; 0 = do not prompt for user name information (use defaults)
; 1 = prompt for user and company identification
Display=0

; Set a blank default user name.
; to avoid using the user name from previous Windows installation.
; Or type a name between the quotes to predefine this information.
Name="Kent Clark"

; Set a blank default company.
; Or type text between the quotes to predefine the company name.
Org="Fishery Inc."

[NETWORK]
; 0 = do not prompt for network components during Custom setup type,
; so Setup will only use detection to install networking.
; 1 = prompt for network components
Display=0

; The following section defines which components to install.
; 0 = do not install component, 1 = install component
; This script installs Accessibility features automatically.
; The other options specified here are the defaults for Custom setup type.
[OptionalComponents]
"Accessibility Options"=0
"Accessories"=1
"Communications"=1
"Disk Tools"=1
"Multimedia"=1
"Screen Savers"=0
"Disk compression tools"=0
"Paint"=1
"HyperTerminal"=0
"Defrag"=1
"Calculator"=1
"Backup"=0
"Phone Dialer"=0
"Flying Windows"=0
"Microsoft Fax"=0
"Microsoft Fax Services"=0
"Microsoft Fax Viewer"=0
"The Microsoft Network"=0
"Audio Compression"=1
"Video Compression"=1
"Sound Recorder"=0
"Volume Control"=1
"Media Player"=1
"Microsoft Exchange"=0
"Microsoft Mail Services"=0
"Briefcase"=0
"Document Templates"=1
"WordPad"=1
"Dial-Up Networking"=0
"Direct Cable Connection"=0
"Mouse Pointers"=0
"Windows 95 Tour"=0
"Online User's Guide"=0
"Desktop Wallpaper"=0
"System Monitor"=0
"Net Watcher"=0
"Character Map"=0
"Additional Screen Savers"=0
"Games"=0
"Quick View"=1
"System Resource Meter"=0
"CompuServe Mail Services"=0
"Sample Sounds"=1
"Musica Sound Scheme"=0
"Jungle Sound Scheme"=0
"Robotz Sound Scheme"=0
"Utopia Sound Scheme"=0
"CD Player"=1

I write an unattended script called msbatch.inf and place it together with the Win95 cabinet files onto a CD.

install Device drivers automatically

Managing those device drivers can be collected into a CD, however, administering them tends to harder to handle. So, I write a DOS batch file called autoinst.bat:


echo off
echo chipset driver...
start "installing..." /wait "E:\_apbk\Drivers-xp\chipset\setup.exe" -s

echo graphics driver..
start "installing..." /wait "E:\_apbk\Drivers-xp\video\setup.exe" -s

echo audio driver...will reboot pc
start "installing..." /wait "E:\_apbk\Drivers-xp\Audio\setup.exe" -b -s

that install motherboard chipset driver, followed by video and then audio. Lastly, it will restart Windows.

make Gaming smoother

Nowsdays games eat lots of system resources, most NT services can be disabled. So, I write a DOS batch called services_xp.bat:

echo off

echo.
echo Ready to turn off NT services before playing games....
pause

echo .NET Runtime Optimization Service v2.0.50727_X86
pause
net stop clr_optimization_v2.0.50727_32

echo .
echo DHCP Client
pause
net stop dhcp

echo.
echo Distributed Link Tracking Client
pause
net stop TrkWks

echo.
echo DNS Client
pause
net stop Dnscache

echo.
echo Fast User Switching Compatibility
pause
net stop FastUserSwitchingCompatibility

echo.
echo Help and Support
pause
net stop helpsvc

echo.
echo IPSEC Services
pause
net stop PolicyAgent

echo.
echo LightScribeService Direct Disc Labeling Service
pause
net stop LightScribeService

echo.
echo Print Spooler
pause
net stop Spooler

echo.
echo Remote Registry takes very long time to disable itself. mission abort.
pause
rem net stop RemoteRegistry

echo.
echo Server
pause
net stop lanmanserver

echo.
echo SSDP Discovery Service takes very long time to disable itself. mission abort.
pause
rem net stop SSDPSRV

echo.
echo TCP/IP NetBIOS Helper takes very long time to disable itself. mission abort.
pause
rem net stop LmHosts

echo.
echo Themes
pause
net stop Themes

echo.
echo Workstation
pause
net stop lanmanworkstation

echo.
echo All done well.
echo ready to exit
pause
exit

that will automatically perform the disabling task. This really put me smile all day long!

clear Game caches

Running one of SysInternal Suite utility, called Contig, which make defragmentation a lot faster. However, if those caching that created by most games, like Rise of Nations, I would rather have it removed before defragmenting my hard disk drive. So, I sat down to graft a DOS batch which:-

1) go into '%userProfile%\Application Data\Microsoft Games\Thrones and Patriots Trial\'

2) remove all subfolders, except 'StateBackup'

Of course, I can easily use Windows Explorer to remove them. But the batch file does the clean job!

keep IE safe and sound

One wonders those free programs that allows one to clear traces especially after using MSIE, either shareware, trial or donationware etc. Well, I write a DOS batch file called rundll32_vista.cmd:

echo off

echo delete IE addons tracking records
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351

echo delete IE miscellaneous files
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

echo delete IE password stored
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

echo delete IE autofill form data
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

echo delete IE temporary files
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

echo delete IE cookies
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

echo delete IE history list
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

pause
exit

which do the most daunting job ever for me free of downloading them. See the magic works!

remove Unused devices

After sometime ago I wonder what devices have been installed via its Automatic Updates in XP or Vista. Normally these hidden device names are not visible in Device Manager and I have to sieve through Windows registry database to locate and verify one by one. Then an idea of DOS scripting came to my mind, so I started to write a batch file:


echo off

set devmgr_show_nonpresent_devices=1
devmgmt.msc
exit

that allows me to view all devices that are commonly displayed by Windows and check its device properties to make wise judgment. Wow, superb!

surf Wireless without heavy loads

Everytime I need to use wireless on my system, I have to manually disable or turn off the common NT services via Services.msc, so, I write a DOS batch file called offline.bat:


echo off
cls

net stop LanmanServer

net stop LanmanWorkstation

net stop W32Time

net stop WSearch

net stop stisvc

net stop Eventlog

net stop WebClient

This saves me lot of hassles and less error prone to many clicks doing this set of task. And, these services seem not in use for most of my development work. It has no harm of disabling them that would save up system resources. Safe and sound!

measure Vista grading

WinSAT grading result just passed and reported onto a web page in Vista. The benchmark has no shortcut link in its Start Menu, so, I write a DOS batch called measure.bat:

echo off

winsat graphicsformal -aurora -moobe -wddm

winsat dwm -normalw 10 -glassw 4 -time 10 -v -fullscreen

winsat d3d -totalobj 20 -objs C(20) -totaltex 10 -texpobj C(1) -alushader -noalpha -fullscreen -v -time 10

that displays 3D objects while running the benchmark tests by its own WinSAT graphicas engine. The Aurora shows windowblinds of lights (an array of different thin lighting colors). Give it a try!

repair Vista Boot

The other day after installing Windows XP into my system over Vista, the Vista boot manager menu is no longer appearing. So, I write a DOS batch file called nt60repair.bat:-

@echo off

color a

echo Run DAEMON first...
pause

echo.
echo Load vu5384.iso ....
pause

d:
cd boot
bootsect /nt60 c:

echo.
echo Vista Boot Manager repaired...
pause

Because vu5384.iso, a Vista beta, is to be used for repairing, a virtual CDROM utility program has to be first installed and loaded it. This way I don't have to reinstall Vista.

get the total number of cmdlets

It is interesting to know each v1.0 for XP, Server 2003/2008, Vista has different total number of CmdLets:

PS> (get-command -CommandType cmdlet).count

Vista Simplified Chinese KB928439 v1.0 has 130; XP English KB926139 v1.0 has 129; WS2008 Std Ed SP1 v1.0 has 129; English SQLPS v1.0 has 130; XP English V2CTP2 has 180; and, XP English v2CTP3 has 235.