Always A-HEAD, By being ahead you are always master of time

Hits

BOOKS

Sunday, February 04, 2007

[DSQuery]-With PowerShell

[DSQuery]-With PowerShell

Below post talks about querying AD. However before you go through this post I strongly recommend you go through below link from

MOW : - http://mow001.blogspot.com/2006/09/powershell-rc2-and-active-directory.html

Let me admit it that below post are original ideas and concept by MOM, here at the most I using better formatting and pulling out corollary out of it.


Connect to AD

[adsi]''
$root=[adsi]'' or $root=new-object directoryservices.directoryentry


List properties of AD Objects

$root fl *


List methods of AD Objects

$root.psbase gm -membertype method # Get all methods

Walk to the Domain structure to wanted OU

$root.psbase.Children

distinguishedName
-----------------
{CN=Builtin,DC=Zarays,DC=com}
{CN=Computers,DC=Zarays,DC=com}
{OU=Domain Controllers,DC=Zarays,DC=com}
{CN=ForeignSecurityPrincipals,DC=Zarays,DC=com}
{OU=France,DC=Zarays,DC=com}
{OU=India,DC=Zarays,DC=com}
{CN=Infrastructure,DC=Zarays,DC=com}
{CN=LostAndFound,DC=Zarays,DC=com}
{CN=NTDS Quotas,DC=Zarays,DC=com}
{CN=Program Data,DC=Zarays,DC=com}
{OU=Singapore,DC=Zarays,DC=com}
{CN=System,DC=Zarays,DC=com}
{OU=UK,DC=Zarays,DC=com}
{CN=Users,DC=Zarays,DC=com}

$users=$root.psbase.children.find('CN=Users') or $users=new-object directoryservices.directoryentry("LDAP://CN=Users,DC=Zarays,DC=com")

-To get properties of user containers

$users fl *

-To find user in a container

$users.psbase.Children.Find('cn=Preetam')

$users.psbase.Children.Find('cn=Preetam') fl *

Corollary 01

Lets use this feature.

$preetam=$users.psbase.Children.Find('cn=Preetam')

$shilpa=$users.psbase.Children.Find('cn=shilpa')

Compare-Object $preetam.memberOf $shilpa.memberOf

Output is

InputObject SideIndicator
----------- -------------
CN=Domain Admins,CN=Users,DC=Zarays,DC=com <=
CN=Enterprise Admins,CN=Users,DC=Zarays,DC=com <=
CN=Schema Admins,CN=Users,DC=Zarays,DC=com <=

Which means Shilpa is not member of above group

Corollary 02

$OU=new-object directoryservices.directoryentry("LDAP://ou=Singapore,dc=zarays,dc=com")

$b=$ou.psbase.children
foreach($c in $b) {
$c.mail
}

output is Email address of all users inside OU singapore. And these address are generally required when you need to communicate back with your colleagues when you leave you current job cool

Friday, February 02, 2007

ACTIVE DIRECTORY AND POWERSHELL

I want to devote this and may be next month on Active directory and powershell.Just a simple search on google will lead you to very good posts by MOW.

I checked the datestamps and they where way back mid 2006.It is the best thing to start. Also Arul writes a lot on Ad mgmt. But lots of things changed with RC2. I'm looking forward to put same stuff in better format. And these are not only reference but there are lots articles on AD. However I'm looking forward to use powershell's power get proper format, in short MOre with less.

Broadly speaking there are always two things you do with Active directoy, Querying AD and committing changes to AD.

Both of these are very very interesting and I'm loving it with powershell by your side.

Within System.DirectoryServices there are two main classess

  • DirectoryEntry for creating objects [Committing changes]
  • DirectorySearcher for searching objects [Querying]

Let first create OU's

Out of it I got little things done by myself. I have created multiple OU's in one go.

$objUser = [ADSI]"LDAP://localhost:389/Ou=India,dc=zarays,dc=com" # Connection established with LDAP port
$readfile=get-content "E:PowerShellActiveDirectoryOUList.txt" # Reading file

foreach($readf in $readfile) {
$ou=$objUser.create("organizationalunit", "ou=$readf") #Creating OU
$ou.setinfo() # Committing changes
}

Following OU's are created assuming India ou is already there

  • Bangalore
  • Chennai
  • NewDelhi
  • Mumbai


Let's edit properties of OU here

$readfile=get-content "E:PowerShellActiveDirectoryOUList.txt"
foreach($ou in $readfile) {
$u=$ou + " Operations"
$OUC=new-object directoryservices.directoryentry("
LDAP://OU=$ou,OU=India,Dc=zarays,dc=com") #connect to OU
$ouc
$oUc.Put("description", $u) #Description but there is one more way to do this.
$oUc.SetInfo() # very important line, this where you says please commit what has been said above.
}

Descriptions changes to

  • Bangalore Operations
  • Chennai Operations
  • NewDelhi Operations
  • Mumbai Operations



Contents of oulist.txt

  • Bangalore
  • Chennai
  • NewDelhi
  • Mumbai

REF:

MOW

http://mow001.blogspot.com/2006/06/powershel-and-active-directory-part-1.html

ARULK

http://blogs.msdn.com/arulk/

Monday, January 29, 2007

Hotfix by Powershell

Script is actually not about Hotfix but more about formatting. How you customize the format of output.

$Hotfix=Get-WmiObject Win32_quickfixengineering
$Bulk=@()
foreach($hotf in $hotfix) {

if($hotf.hotfixid -like "KB*") {
$Bulk += $Hotf
}
}

$Bulk format-table @{Label="HotFixID" Expression={$_.HotFixID}},
@{Label="InstalledBy"Expression={$_.InstalledBy}},
@{Label="InstalledOn"Expression={$_.InstalledOn}},
@{Label="Descr" Expression={$_.Description}} -autosize

The way you customize label and more important use of expression

To get more on this, I have two CSV files and my goal is to append data from both these files. I have imported here CSV but I 'm appending this csv file based on some critiera and that criteria here is Name.

Contents of Name-NC.csv

Name,NC
Shilpa,1
Paatu,1
Anju,2
Mom,3
Papa,3
Preetam,1

Contents of Name-City.csv

Name,City,Age
Preetam,Sng,30
Shilpa,Sng,26
Paatu,Ah,33
Anju,Kh,38
Mom,Ah,56
Papa,Ah,66

So I will check Name in Name-NC and append all the data if the name is present in Name-City.csv.

$NC=import-csv Name-NC.csv
$NCT=import-csv Name-City.csv
$BT =@()
$CT =@()
$Tot =@()
foreach ($Name in $NC) {
# write-host $Name.name `t $Name.NC
$CT =$Name.NC
$BT =$NCT where {$_.name -eq $Name.name}
$BT format-table @{Label="Name" Expression={$_.name}}, @{Label="City" Expression={$_.city}},
@{Label="Age"Expression={$_.Age}},
@{Label="Printer"Expression={$Name.NC}} }

above code I've mark it as bold. actually I got the whole data (again based on name)from one file and only got one detail from other file(Name-city) . Hope you would be able to use this funda somewhere.

Output:

Name City Age Printer
---- ---- --- -------
Shilpa Sng 26 1

Name City Age Printer
---- ---- --- -------
Paatu Ah 33 1

Name City Age Printer
---- ---- --- -------
Anju Kh 38 2

Name City Age Printer
---- ---- --- -------
Mom Ah 56 3

Name City Age Printer
---- ---- --- -------
Papa Ah 66 3

Name City Age Printer
---- ---- --- -------
Preetam Sng 30 1

Technorati tags:

IceRocket tags:

Wednesday, January 24, 2007

SurPriZED

hoey, I'm surprised to find me script on Microsoft site. Not because I don't know from where they came to know but I forgot I've send script to win some Goodies on occassion Powershell scripts. Certainly it is Goodies for me. It is very inspiring for me. This continues to fire my senses. http://www.microsoft.com/technet/scriptcenter/csc/scripts/media/itunes/index.mspx

Tuesday, January 23, 2007

Memory Dump configuration check

How to check if Server is configured to capture memory dump . Answer is in the code. From my personal experience whenever Servers faced Bluescreen, we check if the Memory dump file is created if not then we check few things if they are configured properly. Script below simply does it.

______________________________________________________________________

Write-Host ""

# ----------------->Get free space on C Drive where generally memory dump file is configured
$Cdrive=get-wmiobject -class win32_logicaldisk where {$_.deviceid -eq "c:"}
$CSpace=($Cdrive.FreeSpace/1MB)

#------------------->Converted it in KB's Since all other values are in KB's
Write-Host Free Space on C:\ $CSpace MB

#------------------>Lets get memory details of the computer
$TotalMemory=get-wmiobject win32_logicalmemoryconfiguration
$MEM=($totalmemory.TotalPhysicalMemory/1KB)
$PAGE=($totalmemory.Totalpagefilespace/1KB)
Write-host Physical RAM :- $MEM MB
Write-host Pagefile Size :- $Page MB

#------------------>Page file size should be atleast 12MB more than Physical RAM
$Recsize=($MEM+12)

if ($PAGE -ge $Recsize) {

#------------------>There should be enough free space on to capture memory dump.

if ($CSpace -ge $Recsize ) {
write-host "Machine should be able to generate kernel dump"
}
else {
write-host "Check disk Space on C: drive if memory dump file is configured on it"
}

#------------------>Crash control values are enumerated here
$CrashControl="hklm:\SYSTEM\CurrentControlSet\Control\CrashControl"
$CrashProp=$CrashControl Get-itemproperty
$CrashNo=$CrashProp.CrashDumpEnabled

#---------------->Switch used over here.

Switch($CrashNo) {

0 { "Memory is NOT configured" }
1 {"Complete memory dump is configured" }
2 {"Kernel memory dump is configured"}
3 {"Small memory dump (64KB)"}

}

Write-host Dump file location $CrashProp.DumpFile

$AutoNo=$CrashProp.AutoReboot
If ($AutoNo -eq "0") {write-host Auto Reboot is not enabled} else {write-host AutoReboot is enabled}

$CrashNo=$CrashProp.Overwrite
If ($CrashNo -eq "0") { write-host Overwrite Memory dump option is not enabled} else { write-host Overwrite Memory dump is enabled}

}

else {Write-Host "Page file size should be atleast 12MB more than RAM"}

Write-Host ""

______________________________________________________________________

OutPut:

Free Space on C:\ 4029056 KB
Physical RAM :- 1039744 KB
Pagefile Size :- 2500248 KB
Machine should be able to generate kernel dump
Kernel memory dump is configured
Dump file location C:\WINDOWS\MEMORY.DMP
Auto Reboot is not enabled
Overwrite Memory dump is enabled

----------------------------------------------------------

# References:
#
http://support.microsoft.com/kb/244139
#http://support.microsoft.com/kb/254649

#CrashDumpEnabled REG_DWORD 0x0 = None
#CrashDumpEnabled REG_DWORD 0x1 = Complete memory dump
#CrashDumpEnabled REG_DWORD 0x2 = Kernel memory dump
#CrashDumpEnabled REG_DWORD 0x3 = Small memory dump (64KB)

Technorati tags:

IceRocket tags:

Saturday, January 20, 2007

One Good Day

I discovered great thing today, you can divert the output of text file using out-file.

USAGE : .\RemoteSvc.ps1 . a* | Out-File services.txt

No big deal I know but it is always better to share it. I'm happy today as I was able to use powershell scripts in production enviornment and I was able to get satisfied results. Generally I don't check if the server is reachable, as result for few servers error was thrown. but script continued to work, for this to work in VBScript you will have to type

"On error resume next" at the top of text file or else script will exit

 

del.icio.us tags:

Technorati tags:

Wednesday, January 17, 2007

Computer Inventry with Powershell

I'm planning to put here series of code to get the computer inventory of machines. As you could remember last time I got the IP Address of the machine. This time I wanna know how many and what programs are installed on this machine.

$ALLPROGS=Get-ChildItem "hklm:\software\microsoft\windows\currentversion\uninstall" ForEach-Object {Get-ItemProperty $_.pspath}
if ($args -eq "sort" )

{
$ALLPROGS Select-Object displayname,publisher sort publisher

}
else

{

$ALLPROGS Select-Object displayname,publisher group publisher sort count

}

I've purposely left this code hanging whether you wish to have group programs or sort by name of the application publisher. Program is simple but fact that I would like to mentioned here, I tried the other way round, which I've pasted just for the sake of not to do do this.

USAGE: .\AllPrograms02.ps1 sort or .\AllPrograms02.ps1

$ALLPROG="hklm:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
$CHILDPROG=get-childitem $ALLPROG
$PROGNAME=$CHILDPROG select-object pschildname
for($i=0;$i -lt $PROGNAME.length; $i++) {
$EACHPROG=$PROGNAME[$i].pschildname
$PROGS="hklm:\Software\Microsoft\Windows\CurrentVersion\Uninstall\$EACHPROG"
$PROGS get-itemproperty select-object displayname,publisher sort displayname
}

Even though I have mentioned sort by displayname it won't work, sorting fails here because it has to be with POST here...

http://blogs.msdn.com/powershell/archive/2007/01/11/sorting-out-groupby.aspx, just though of keeping it in my mind. Please bear in mind this is not going to work on remote computer, But for me it doesn't matter. Because I'm going to run this everytime I built the server or someone asks me or Best one is to do by using psexec..hahaha. But certainly in future there is would be simpler way to run this across enterprise.

Technorati tags:

del.icio.us tags:

IceRocket tags:

Monday, January 15, 2007

Accessing Registry using PowerShell

Accessing registry is quite common in Powershell Now, so lets get into it. Idea was to gather inventory of entire computer. I thought lets start with simple code.

$regpath="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
$items=$regpath get-itemproperty
$items.RegisteredOwner
$items.systemroot
$items.SourcePath

Then I felt like exploring little more. I came with Idea of getting IP address of machine. When I wrote code I felt it was easy but it went too long than I felt.

$NICSPOOL="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards"
$NOSNIC=get-childitem $NICSPOOL
$EACHNIC=$NOSNIC select-object pschildname
for($i=0;$i -lt $EACHNIC.length; $i++) {
$CardName=$EACHNIC[$i].pschildname
#Write-host CNAME $CARDNAME
$NICCARDS="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\$CardName"
$NICPROP=$NICCARDS Get-ItemProperty
$SVCNAME=$NICPROP.ServiceName
#Write-host $SVCNAME
$Des=$NICPROP.Description
Write-host $Des
$IPPOOL="HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
$IPS=$IPPOOL + "\" + $SVCNAME
write-host IPS $IPS
$IPPROP=$IPS Get-itemproperty
#$IPPROP
if ($IPPROP.EnableDHCP -eq 1) {
Write-host IPAddress $IPPROP.DhcpIPAddress
Write-host SubnetMask $IPPROP.DhcpSubnetMask
Write-host DefaultGateway $IPPROP.DhcpDefaultGateway
Write-host DhcpServer $IPPROP.DhcpServer
}
if ($IPPROP.EnableDHCP -eq 0) {
Write-host IPAddress $IPPROP.ipaddress
Write-host SubnetMask $IPPROP.SubnetMask
Write-host DefaultGateway $IPPROP.DefaultGateway
Write-host DNSServer $IPPROP.NameServer
}
write-host ""
}

Few interesting things I discovered I've marked as pink.Above script assumes you have multiple NIC, nowadays it is more common. And I wanted this script to be enterprize compatible. Script would look for one parameter, DHCP if it is enabled it will get different out. Script did what I wished but only in parts. Again this won;t work across enterprize. So next step was googling.

Found

http://abhishek225.spaces.live.com/blog/cns!13469C7B7CE6E911!145.entry

http://mybsinfo.blogspot.com/2007/01/powershell-remote-registry-and-you-part.html

Both the blogs are quite interesting to an extend which explains remote registry access is possible.

Let's take simple example

LOCAL REGISTRY ACCESS

$regpath="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\2"
$items=$regpath get-itemproperty
$items.Servicename

REMOTE REGISTRY ACCESS

$Srv="Singaporelt"
$key = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards"
$type = [Microsoft.Win32.RegistryHive]::LocalMachine
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $Srv)
$regKey = $regKey.OpenSubKey($key)
Write-Host "Sub Keys"
Write-Host "--------"
Foreach($sub in $regKey.GetSubKeyNames()){
$NICPOOLS = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\$sub"
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $Srv)
$regKey = $regKey.OpenSubKey($NICPOOLS)
Foreach($val in $regKey.GetValueNames()) {
if ( $val -eq "Servicename") {
$Keyvalue= $regKey.GetValue("$val")
$Keyvalue
}
}
}

See the difference in code. No No....it is not about lines in the code but it is property and methods available in local registry are not easily available while accessing remote registry. I was able to get the IP address using remote registry class but output was not quite satisfying and code manipulation was nothing but another vbscript. Yeah I can't expect best of both the worlds...not so early. For simple reason, without .net knowledge struggle will continue.

Friday, January 12, 2007

iPHONE

With due release of iPhone, mobile phone market is going to change. Innovation always takes lead. Competitive product O2,HP PDA’s will also need to change their game in order to stay in Market.

Another Article here is cool

I'm already planning one for me due in Asia 2008. It is pretty cheap when I compare with O2 Model.

Full specification of iPhone could be found at http://www.apple.com/iphone.


Thursday, January 11, 2007

Managing remote/local services with Pow6r Sh6ll

When I was exploring various possibilites from Admin point of view in Powershell, I was never aware that such CMDLET would not work for managing servers remotely. However it was not difficult to implement it when blogs like http://thepowershellguy.com/blogs/posh/ are available on the Internet. I happen to see MOW blog entry on blogspot (http://mow001.blogspot.com/)and there I realized yeah it is possible to do everything remotely same as sysinternal tools can do it. Again .NET Classes.With this idea in my mind, I was able to convert my all existing CMDLETS for managing stuff remotely. For doing this you should be aware of one very important thing, which classes to load. For example if you run this script as it, it will error out

"Unable to find type [System.ServiceProcess.ServiceController]: make sure that the assembly containing this type is loaded."

It means nothing but load the revelant classes before I can do anything. Let me admit it I don't know which class to load but to get it work you just run get-services before running the script below. It will internally load the relevant classes. Of course if the information comes from POWERSHELL GURU's, I will post it here.

Write-host $args[0]
$LikeVar= $args[1]
$remSVC=[System.ServiceProcess.ServiceController]::GetServices($args[0])
$remSVC where {$_.name -like $LikeVar}

Let's come to the script.

$args[0] which is standard variable(default) will pick first word which I have assigned for computername and second variable is your servicename string. Remember I have selected servicename not displayname to query.Above CMDLET is similiar to sc query findstr /i al*

NOW it is .\svcvar.ps1 computername al*. Much simpler.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Now there is scenario where in you need to stop three services on 200 servers across Enterprize. In fact I got this idea because I had dealt with it in reality and I have us SC STOP stuff which was quite murky in a way.

$Services=get-content "E:\PowerShell\MakesSense\Ser-ices.txt"
$Servers=get-content "E:\PowerShell\MakesSense\Servers.txt"
ForEach($Server in $Servers) {
$LOADSVC=[System.ServiceProcess.ServiceController]::GetServices($Server)
foreach($service in $services) {
$REMSVC=$LOADSVC where {$_.name -eq $service}
if ($REMSVC.status -eq "Running") {
Write-host $REMSVC.stop()
$REMsvc.WaitForStatus("stopped", (New-TimeSpan -seconds 3))
Write-host $REMsvc.displayname been successfully stopped on $server
}
elseif ($REMSVC.status -eq "Stopped") {
Write-host $REMsvc.displayname is already in $REMsvc.status state on $server -foregroundcolor "RED"
}
else {
write-host Please check if $service Service exists on $server -foregroundcolor "RED"
}
}
}

Write services which you wish to stop in ser-ices.txt and servers in servers.txt on which you wish to manage services. And then code is typical VBSCript code. Most important (new) thing here is how INFANTLY (Simply) I can manage output with $REMsvc.displayname, $REMsvc.status which Re-emphasize DO MORE WITH LESS Principle.

Technorati tags:
del.icio.us tags:
IceRocket tags:

Monday, January 08, 2007

Reading Eventlog before and after shutdown

$gener=Get-EventLog -LogName system where{$_.eventid -eq "6005"} sort timegenerated Select-Object -last 1
$timegen=$gener.timegenerated
$afterReb=get-eventlog -logname system where{$_.timegenerated -gt $timegen}
Write-host "-------------------------Error Type --------------------------- " -foregroundcolor "WHITE"
$afterReb Group-Object entrytype
#Start-Sleep -m 500
Write-host " "
Write-host "-------------------------ERRORS --------------------------- " -foregroundcolor "WHITE"
#Start-Sleep -m 500
$afterReb where{$_.entrytype -eq "error"} Select-Object timegenerated,Source,EventID,Message format-list out-host -paging
#$afterReb sort-Object entrytype format-list Out-Host -Paging
Write-host " "
$BforeShtdn=$timegen.addhours(-1)
Write-host "-------------------------Error 1 Hour Before ShutdownType --------------------------- " -foregroundcolor "WHITE"
$LsbforeShtdn=Get-EventLog -LogName system where{(($_.timegenerated -gt $BforeShtdn) -and ($_.timegenerated -lt $timegen))}
$LsbforeShtdn sort-Object entrytype format-list Out-Host -Paging

Suppose you get a call from Helpdesk, that system has gone unexpected shutdown.And now system is up but you wish to know why it went down.So first thing you look is event log. And what is your area of concentration. Obiviously when system went down and if there were any errors before and after shutdown. Exactly same thing this script does. It gets all event logs when system went down unexpectedly. Event ID in this case should be either 6008/6005, you can certainly include that logic here.But not only this I also got event logs before system went down for 1 hour duration. And I'm again amazed by $BforeShtdn=$timegen.addhours(-1), it is simple mathematics. I don't have to do programatically subtraction. Simple Superb. Thanks to Powershell team.

Well the script is again very simple, But it should be unique.I parsed the eventlog and filtered out 6005. I got all logs from after this event. Logically all events after system is shutdown.

Apart from the script above I found a very simple method to detect the uptime of any computer across the network.

$wmip=get-wmiobject Win32_PerfFormattedData_PerfOS_System -computername "SystemName"
$time=$wmip.SystemUpTime
$uptime=new-timespan -seconds $time
$formattime="{0:N}" -f $uptime
Write-host $formattime [Days:Hours:Minutes:Seconds]

Technorati tags:

IceRocket tags:

Friday, January 05, 2007

PowerShell EventLog Parser

#you need Error-Patters.txt which can include any pattern for example terminated failed Stopped unexpected

#----------------CODE BEGINS-------------------
$Patterns=get-content "E:\Powershell\Makesense\Error-Patters.txt"
foreach($Pattern in $Patterns) {
$Errevents = get-eventlog -logname system -newest 1000 where{$_.entrytype -eq "error"}
$failedpattern=$Errevents Select-Object eventid,timegenerated,message,source Select-String -Pattern $Pattern
Write-host "________________________" $Pattern "_______________________" -Foregroundcolor "RED"
for($i=0;$i -lt $failedpattern.length; $i++) {
[string]$splitt=$failedpattern[$i]
$splitt.Split(';')
Write-Host "_____________________ " -foregroundcolor "GRAY"
}
}

#--------------------CODE ENDS---------------------------


Yesterday I was going through basic of Powershell again. Just to see If I could dig out more. I came across select-string, Wow..another beautiful feature. I just wanted to utilized it's full powerBelow example is just sleek and does what things which always expect.
C:\PS>$events = get-eventlog -logname application -newest 100$events select-string -inputobject {$_.message} -pattern "failed"
Below is example in powershell inbuilt help. GET-HELP SELECT-STRING -EXAMPLES
Let's talk about the script. I'm basically going into system event log and then filtering only errors.Once I have errors I check content of the message for text likefailed,stopped,unexpected,terminated. Since this strings might differ in individually cases, I have included them in text file. One I thing I noticed here, output which select-string produceincludes message,eventid,source seperated by ";" So I have to use split command to manipulate the output. I have used again color backgrounds to make it more readable. I'm delighted by the output. Do try out.

Monday, January 01, 2007

Schedule reboot with PowerShell

$now=get-date

$MachineName=read-host "Please Enter Machine Name you wish to reboot :"

$When=read-host "Please enter time when you wish to reboot the server Later THAN ($now) :"

$results=$now.subtract($when)

#write-host $Results Results

$time2act=$now.Subtract($results)

#Write-host $time2act is time2act

$action=$time2act.subtract($now)

$Sec2Act= $action.totalseconds

$totalsecs="{0:N0}" -f $Sec2Act

$SecINint=[int]$totalsecs

write-host $testint

if($results -le 0)
{
write-host "done"
Write-host $MachineName "will Reboot in next " $SecINint Seconds
shutdown -s -m $machineName -t $SecINint
}
else {
write-host "Time entered has already past,please enter time later than " [$now] -Background "RED"
}

Due you remember days when you have to apply patches on 1000 servers in phased manner. But in this scenario servers are not rebooted, they are rebooted only when customer/client gives downtime. Such scenario needs a schedule reboot for the server. But what happens when each client gives different reboot time. I thought lets write something on similiar lines, where in we can schedule a reboot of the server as per client's requirement. Above is just the logic, but the script requires few more additions. First is we need to read content of server name, time it is schedule to reboot, which is easily possible to read from text file. And certainly this is small step towards automation.

Here I was able to use shutdown.exe command without invoking wscript.shell, which I like the most, which was not possible to do with VBScript. If you run this command you would get computer name prompt, time to enter in specific format and that it. I have tested the script. But I think it will require little more finishing.

Technorati tags:
;
del.icio.us tags:
;
IceRocket tags:

Saturday, December 30, 2006

Review Year 2006

Review Year 2006

Year 2006, has been far far different than I can put in words. I certainly have experienced it in much different manner than I can imagine. January 2006 I have been to London Via Texaco. It was certainly great opportunity, to understand culture of UK. I liked the fact, people respect each other so much. I have certainly gone down and shared that experience with my friend. Lot of them really liked it. More I say of UK it will be less. But difficult circumstances lead me to leave Texaco, and I joined Sussee,Singapore. Culture of Singapore is so much different than UK. Two totally different countries. These experience goes far beyond in understanding not only culture but also working style,Architechure of city, Construction, Innovation and above all collating all this information, to do similar things in India at whatever level you can.I'm thankful to GOD and all other people who have helped me out time and when I needed them, to reach such places.

On career front, I've learnt VB Script, the fact that I felt need within myself to learn, has paid me a lot. Understanding of VB Script has not only increased my domain knowledge but also gave me edge over all other Admins. It was like one day I went to Shop and got the Book for 350 Rs (I'm surprised because I thought it was costly), Started learning from the Book daily. And what ...I made a daily schedule and started moving towards achieving the goal of finishing it in 3 months Flat. I did it. And during this journey I experienced how powerful,confident you feel when you are about to reach towards your goal. Joyful and pleasant to catch in lucid words. Multiple goal has potential to give this Kind of Happiness.

All those planning,daily schedules got inspired by Robin Sharma's book Monk who .....Great Book. As we all know if you understanding (learn)something and you don't implement it, then you have not understood. Based on this experience I've decided to come up on number of books I should be reading in year 2007. I feel proud to apply the same VB Script knowledge to make Admin life easier in previous and current Organizations. When power shell got released, it was like dream came true, Because my knowledge of VB Script has cultivated my Mind, which obviously saw advantage of PowerShell. As result I have come up with Idea of Blog. Techstarts has great ideas I had: To utilize power of shell.

Financially year 2006 more or less can compete with BSE Index growth,India. Next year's goal is to leverage on it.

Purchases: Laptop was major and most beneficial.

Trips: Ooty,Kodai Kanal,Mysore

Books Read: Cracking the Code of Millionaire;Monk who sold his Ferrari;Timeless Wisdom;The Man eater of Malgudi;The One Minute Manager;Adventures_of_Sherlock_Holmes.

Relations:This is the front, I have continued to be at lost, Because every time I change my serving point, I lost all relations which has been built in that organization. This is deeply felt by me.Every time I think of it, Blame game starts in my Mind.



I wanted to keep review as small as possible, since I don't think everyone would love to read this. I'm currently reading 8th Habit of highly effective people, inspired by one of the chapters I decided to share few things with you.Since we all know "Knowledge is a power which continues to grow unless you share it." These events were certainly not planned but had I planned I can't say anymore how much effectively year 2006 would've been utilized.

But I certainly take this as starting point and this is the place I always consider as base point. From where I would continue to accelerate in forward direction. I would suggest you all to start something like this, so your planning for entire year would start for 2007.

For example:

  1. How many books you are going to read this year
  2. How many days you are planning vacation this year
  3. How much you plan to save this year
  4. Where you want to be at the end of the year

Below mentioned article inspired me to review 2006 in my life...how about you?.........

Please feel free to comment. I would certainly look forward at least ONE.

Happy New Year 2007


So, this holiday season, I respectfully suggest that you take the time to review 2006. Find a sacred space, grab your journal and write down your answers to the following questions. First, write the story of the year. Describe how 2006 went for you in as much detail as possible. Open your journal and describe the year that just happened. What were your successes? Your disappointments? What experiences were breathtakingly great? Try to recall each month or season and describe all aspects of your life. Your career, your finances, your relationships, your health, your contribution. Yes, I know that this will take some time. However, leadership is about doing the right things not the easy things.

Second, look at your goal sheets, schedule and journal from the year. How did you do on your goals? Give yourself a mark for each of your goals. If you committed to running a faster 10k and you did then give yourself a ten out of ten. If you aimed to read 50 books and only read 40 then give yourself and 8 out of 10. After reviewing your performance (big idea: all great companies and leaders look at their past performance) look for patterns. Did you excel and business but let your health slide? Did you let disappointments get in the way? Did you make the necessary mid-course corrections when circumstances changed? Reflect on your decisions. How did you perform as a decision maker? Did later events confirm your assumptions? Did you act too quickly or not quickly enough?

- Robin Sharma

Friday, December 29, 2006

PowerShell RSS Reader

$oIE=new-object -com internetexplorer.application
$oIE.navigate2("About:blank")
while ($oIE.busy) {
sleep -milliseconds 50
}
#$oIE.visible=$true

$feed=[xml](new-object system.net.webclient).downloadstring("http://www.rediff.com/rss/newsrss.xml")

#$feed=[xml]$(get-content C:\Preetam\Money.xml)
$results=$feed.rss.channel.item Select-Object TITLE,DESCRIPTION ConvertTo-Html
$oDocBody=$oIE.document.documentelement.lastchild ;
#populate the document.body
$oDocBody.innerhtml=$results
$oDocBody.style.font="10pt Arial";
$oIE.document.bgcolor="#D7D7EA"
#Reading back from IE.
$oTBody=@($oIE.document.getElementsByTagName(">] ;
foreach ($oRow in $oTBody.childNodes)
{$oRow.bgColor="#AAAAAA" ;}
#Prepare a title.
$oTitle=$oIE.document.createElement("P")
$oTitle.style.font="bold 20pt Arial"
$oTitle.innerhtml="PowerShell NEWS Reader";
$oTitle.align="center" ;
#Display the title before the Table object.
$oTable=@($oIE.document.getElementsByTagName(">] ;
$oDocBody.insertBefore($oTitle,$oTable) > $null;

#$line=$oIE.document.createTextNode("MADEND")
#$Para=$oIE.document.createElement("HR")
#$oDocBody.appendchild($Para)
#$oDocBody.appendchild($Para)
#$oDocBody.appendchild($line)

#--------------------------------------------------------------

$feed01=[xml](new-object system.net.webclient).downloadstring("http://www.rediff.com/rss/moneyrss.xml")
$results01=$feed01.rss.channel.item Select-Object TITLE,DESCRIPTION ConvertTo-Html
$oDocBody=$oIE.document.documentelement.lastchild.firstchild ;
#populate the document.body
$oDocBody.innerhtml=$results01
$oDocBody.style.font="10pt Arial";
$oIE.document.bgcolor="#D7D7EA"
#Reading back from IE.
$oTBody=@($oIE.document.getElementsByTagName(">] ;
foreach ($oRow in $oTBody.childNodes)
{
$oRow.bgColor="#336600" ;

}
#Prepare a title.
$oTitle=$oIE.document.createElement("P")
$oTitle.style.font="bold 20pt Arial"
$oTitle.innerhtml="PowerShell NEWS Reader";
$oTitle.align="center" ;
#Display the title before the Table object.
$oTable=@($oIE.document.getElementsByTagName(">] ;
$oDocBody.insertBefore($oTitle,$oTable) > $null;
$oIE.visible=$true



Before I begin, what this script does, let me thank three people over here.

Scott Hansell --------> http://www.hanselman.com/blog : For giving such superb presentation on parsing XML via PowerShell ..worth watching...

Website Brainjar --------> http://www.brainjar.com/dhtml/intro/default2.asp This site tells us how to parse HTML tags; I’ was absolutely dumb about it before I visited it.

PowerShell Blos --------> Yuksel Akinci http://blogs.msdn.com/powershell/archive/2006/09/10/748883.aspx This where I got the hint of parsing and formatting html output.

Disclaimer: This is no way like a RSS reader, as you get on internet, it is just explains latent potential lies in Powershell to unleash power of XML, Non-programmer like me it has been very simple to prove it. Of course code can be made much more complex get our favourite RSS reader formatted in our own way. And there is already something like this on Wiki (http://en.wikipedia.org/wiki/Windows_PowerShell)

Code is nothing if you know DOM (document object modelling).

$feed=[xml](new-object system.net.webclient).downloadstring(http://www.rediff.com/rss/newsrss.xml)

I have pulled two separate XML file from the internet and pasted into HTML document using DOM. To do this I have to typecast which means to convert thing specifically into XML;if this is missing it is normal HTML document.

After that I have converted them into html format

$results=$feed.rss.channel.item Select-Object TITLE,DESCRIPTION ConvertTo-Html

After this everything is about formatting HTML in way it looks as attractive HTML page

$oDocBody=$oIE.document.documentelement.lastchild.firstchild ;

Above line is important since this line actually pulls the second link and drops it in first child of last child, it can get tricky if you more xml links.

Lastly how to run it, you will need to change ("http://www.rediff.com/rss/newsrss.xml") and get your favourite XML link, of course one you have it you don’t need to change everytime. Atleast I’ve made provision for two RSS links, further can be made easily

Technorati tags: , ,

del.icio.us tags: ,


Monday, December 25, 2006

Bulk Ping Via PowerShell

CODE:

$readfile=get-content "E:\PowerShell\MakesSense\Servers.txt"
foreach($readf in $readfile)
{
$ALive=get-wmiobject win32_pingstatus -Filter "Address='$readf'" | Select-Object statuscode

if($ALive.statuscode -eq 0)
{write-host $readf is REACHABLE -background "GREEN" -foreground "BLACk"}
else
{write-host $readf is NOT reachable -background "RED" -foreground "BLACk"}
}

OUTPUT:

I was reviewing my codes and I realise it would only start making difference only when I show the output. Also most of the codes in previous post might not work, because of formatting. But I want to know which are not actually working. Please let me know if you come across something like this.

Remember to create servers.txt file and put in all servers in txt file which you which to ping.

Apart from this, I'm getting question in similiar nature what can you do with powershell. Yes that is very simple to answer and believe it, if you go to the MS Site mentioned below.

Worth Visiting collection of Powershell Scripts, you are bound to love it.

What Can I Do With Windows PowerShell?

Flickr tags: ,

Technorati tags: ,

Friday, December 22, 2006

Windows Vista Capable and Premium Ready PCs

Please check the link below to get official guide in what exactly is VISTA's requirement.

 

A Windows Vista Premium Ready PC includes at least:

  • 1 GHz 32-bit (x86) or 64-bit (x64) processor1.
  • 1 GB of system memory.
  • Support for DirectX 9 graphics with a WDDM driver, 128 MB of graphics memory (minimum)2, Pixel Shader 2.0 and 32 bits per pixel.
  • 40 GB of hard drive capacity with 15 GB free space.
  • DVD-ROM Drive3.
  • Audio output capability.
  • Internet access capability.

Get Feeded here :Windows Vista Capable and Premium Ready PCs

Vista's Feature :Aero Feature   Let me know how many of them are requirment of daily use at the cost of Hardware.

Flickr tags: ,

Technorati tags: ,

PowerShell-MSClustering

PowerShell -MSCluster-WMI
Word multithreading itself is obfuscating for me, and then think what programming can be for me. But powershell renews interest in me to become one, specially when .Net classes are invoked from here.

Simple example is here
$shell=new-object -com shell.application
$shell.ShutdownWindows()


And not that, there are so many other Methods available which can of great use, to find them all here...just type

$shell get-member

There was some problem in watching recording of web cast, so I decided to download only PPT’s, since I was hungry of codes and the latent thinking that generates in me out of the codes. I saw foreground and background impact. Instantly I thought hmmm looks different. And then mind starts to think….as it is mentioned in
8th Habit
No thing is as powerful as the idea whose time has come…..

Lots of jabbering lets get to the code.



Write-Host "CLUSTER VIEW ONLY IN THE ORDER OF DEPENDANCY" -backgroundcolor "GREEN" -FOREGROUNDCOLOR "BLACK"
WRITE-HOST " " -backgroundcolor "YELLOW"
WRITE-HOST "RESOURCE: QUROUM" -backgroundcolor "DARKRED"
Get-WmiObject -namespace root\mscluster -computername CLUSTERNAME -class mscluster_resource where{$_.type -eq "Physical Disk"} Select-Object Name,description,State
WRITE-HOST " " -backgroundcolor "GRAY"
WRITE-HOST "RESOURCE: NON SYSTEM DRIVES" -backgroundcolor "DARKRED"
Get-WmiObject -namespace root\mscluster -computername CLUSTERNAME -class mscluster_resource where{$_.type -eq "Volume Manager Disk Group"}
WRITE-HOST " " -backgroundcolor "GRAY"
WRITE-HOST "RESOURCE: IP ADDRESS" -backgroundcolor "DARKRED"
Get-WmiObject -namespace root\mscluster -computername CLUSTERNAME -class mscluster_resource where{$_.type -eq "IP address"}
WRITE-HOST " " -backgroundcolor "GRAY"
WRITE-HOST "RESOURCE: NETWORK NAME" -backgroundcolor "DARKRED"
Get-WmiObject -namespace root\mscluster -computername CLUSTERNAME -class mscluster_resource where{$_.type -eq "Network Name"}
WRITE-HOST " " -backgroundcolor "GRAY"
WRITE-HOST "RESOURCE: FILE SHARE" -backgroundcolor "DARKRED"
Get-WmiObject -namespace root\mscluster -computername CLUSTERNAME -class mscluster_resource where{$_.type -eq "File Share"}



Code is very simple but results you get out of it are truly superb. Formatting makes life easier and interesting.I thought of using WMI/Clustering to get the results.

Lets get to first line
WRITE-HOST "RESOURCE: QUROUM" -backgroundcolor "DARKRED"
Get-WmiObject -namespace root\mscluster -computername CLUSTERNAME -class mscluster_resource where{$_.type -eq "Physical Disk"} Select-Object Name,description,State

My intention here is to sort cluster resource by type. In other words you puch below line on CMD prompt.

Cluster /cluster:CLUSTERNAME RESOURCE

And you would get cluster resources. I sorted these resources by type. Common types are file share,Network Name,Physical disk and third party would like Volume Manager Disk Group. In order to get cluster WMI you have to specifically connect to it. You simply can’t do get-wmiobject win32_Service.

Once that happen, next code is…

Write-host “ “ –foregroundcolor “DARKRED”

Above line, I have put lots of spaces to get you DARKRED thik border.

Not much…

I can't get you the output of it, or screen shot, But you won’t be feeling sorry if run similiar in any MSCluster enviornment.

Wednesday, December 20, 2006

Daily News

Google has come with top search for year 2006, have a look.

2006 Top Searchs


Firefox version update Firefox 2.0.0.1 is available, as per them it is must to update it. With every update some or other extension stops working.Now blog this is not working for me.


God and Bad of Year 2006 and whole lot of Trends which we have almost forgotten and certainly must read Time Person of the Year:YOU

Go to Time


To make things easier and faster always use Windows Live Writer, for latest version

Go Here

 

Technorati tags: , ,

PowerShell Lab Experience

Set-ExecutionPolicy

Get-ExecutionPolicy

PS E:\> Get-ChildItem E:\PowerShell | measure-object length -Average -Sum -Maximum -Minimum

Count : 4
Average : 19491
Sum : 77964
Maximum : 37856
Minimum : 768
Property : length

-------------------------------------- 

PS E:\> Get-ChildItem E:\PowerShell | Group extension

Count Name Group
----- ---- -----
2 {MakesSense, NeedtoTry}
4 .log {Ldisk.log, process.log, properties.log, service.log}

------------------------------------

PS E:\> ((Get-ChildItem C:\WINDOWS\system32 | Measure-Object length -sum).sum)/1MB
354.373404502869

------------------------------------

PS E:\> Get-ChildItem c:\ -Recurse -Include *.tmp | select-object pspath

PSPath
Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS\system32\CONFIG.TMP
Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS\system32\setb6.tmp
Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS\SET3.tmp
Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS\SET4.tmp
Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS\SET8.tmp

------------------

 

PS E:\> Get-ChildItem c:\ -Recurse -Include *.tmp | select-object fullname

FullName
--------
C:\WINDOWS\system32\CONFIG.TMP
C:\WINDOWS\system32\setb6.tmp
C:\WINDOWS\SET3.tmp
C:\WINDOWS\SET4.tmp
C:\WINDOWS\SET8.tmp

-----------------------------------

PS E:\> Get-ChildItem C:\Softwares -Recurse | where {$_.length -gt 100MB}

Directory: Microsoft.PowerShell.Core\FileSystem::C:\Softwares\SeverSupportTools\ServicePack01-Win2k3

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 14/10/2006 20:21 345322744 WindowsServer2003-KB889101-SP1-x86-ENU.exe

-------------------------------------

Get-ChildItem C:\WINDOWS\system32 | Select-Object extension | Sort-Object extension -Unique

 

-------------------------------------

 

Get-ChildItem C:\backupfiles.bak -Recurse | ForEach-Object{$D=get-date;$_.lastwritetime=$D}

Technorati Tags: