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

Hits

BOOKS

Labels

Showing posts with label Techincal. Show all posts
Showing posts with label Techincal. Show all posts

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:

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: ,

Tuesday, December 19, 2006

Power Shell Folder Size

Yesterday I was going through the Virtual Labs for powershell, and found few more powers of shell. I will posting that in different post soon, I just need to format it. Live writer from MS makes life easy in formatting blogs. Here we go. I wished to find out folder size, similiar like treesize (But not tree size)

$TotalFoldSZ=0 #total folder size
$foltree=get-childitem "C:\Program Files\iTunes" #Which fold size you wish to check out, this can be easily turn into user's by using read-host

foreach ($folt in $foltree) {

if($folt.mode -match "d") { #I used mode attribute to get only directories, so what about files in the parent directory...hmm coming to in...:-)
$fsz=((get-childItem $folt.fullname -recurse Measure-object length -sum).sum)/1MB #Got the size in MB
FSize="{0:N2}" -f $fsz #Formatted to two decimals
write-host $folt.name $fsize MB # wrote to screen FolderName,FolderSize
$TotalFSZ=$TotalFSZ+$fsize #To get the total folder size
}
}
$filesize=(($foltree measure-object length -sum).sum)/1MB #This is where I check if there are files present in the parent folder. If there are #only files then I will get folder size zero, not to miss that out, I've to include it.
$fsizeMB="{0:N2}" -f $filesize #Formatted it get in MB
Write-host Total Size of Folder is ($TotalFSZ+$fsizeMB) MB #here finally I add each folder size and files inside parent folder.

Most important thing in this script is the usage of ((get-childItem $folt.fullname -recurse Measure-object length -sum).sum)/1MB . It is just makes life easy, you get powershell to add the file size and report it.

Try this PS E:\> Get-ChildItem E:\PowerShell measure-object length -Average -Sum -Maximum -Minimum and you will be pleased to see ..yeah it gives number of files in the folder,Average size of the file and maxmimum file size and Minimum file size. Just a thing to note, you can manipulate only file items, I've to checkout if there is something which can do for folders as well.Next thing I would like someone to helpout with the sorting stuff.


Technorati: ,

Powershell to view EventLogs

I was actually expecting to see some noted difference in event viewer in Vista. If you are core System Admin your job is mostly revolved around finding out in digging logs and then relate it to some meaning full Unexpected Shutdown root cause analysis. And everytime we open event logs we normally tend to open error or warning logs around 6008, unexpected reboot. And then starts the double click attack on every event log in around...to delve in message details. I wonder if there is some better solutions planned in future OS's...just for time being I have got a work around with PowerShell, this is again one Length one liner....

Get-EventLog -LogName application where{$_.Entrytype -eq "error"} convertto-html -property timegenerated,Index,Source,Message -title "ErrorLogs" -body "Errors on Server" > log.htm;invoke-item log.htm

Lets get into details, in fact there is not much technical into, it is straight forward.

Get-Eventlog -logname Application -------with this line we are in Application log. (Just imagine how many lines you will require to get into appln log via VBSCript)

We piped it to get only error with $_.Entrytype...Hmmm I was searching for long where is eventtype embedded..in the help file.

for example: get-eventlog -logname application get-member..

finally I got it. I would like this help to be more descriptive, it says everything in greek to non-programmer like me.

With above line we got all errors. Here you again have choice how many error/Warning/Information you wish to have. Just modify first line as "Get-EventLog -LogName application -newest 10"

Once I have all errors, I asked Powershell to converto-html and with properties as Header I selected TimeGenerated,Message,Source..you select as per your requirement.

Now last step here is to re-direct the output to htm file and then invoke the same with Invoke-item.



Thursday, December 14, 2006

PowerShell -Great Computer Shell and Not just another



I know there are lots of better and much better articles on Power shell, But still powers of powershell are so much immense that I can't resist tell you what I learnt so far.

As per Jeffery there are 5 things you must know before you start powershell

So let's start
Get-Help
Get-Command
Get-alias
Get-PSdrives
Get-Member


Any Get-Help (command name) has following option
1) Syntax reference
2) -Detail gives detail information
3) –full everything plus more examples

For example:

Get-help wmi-object
get-help WmiObject –full
get-help WmiObject -detail

Get-Help wmi -Examples out-file c:\wmiexa
(Above command get the results and push over bridge(Pipe) to out-file wmiexa.txt )

Get-command: this command not only show what command are available in PS but also can help in search any file on your C-drive. Just try get-command *.dll and see for yourself.

Get-PSDrives: one of the most daring innovations of PS. You can actually browse into registry using this command and check out what is stored over there and that too much much better format.

First run get-psdrives and then simple CD into HKLM to get into registry. If you can get into registry sure there is specific way to modify it as well.

Now Get-member, I found this command very handy. You know to get details of methods of any class, I use to run scriptomatic if it was WMI Class or move to MSDN, where every min something keep changing, so after min change link goes dead. Don’t trust me, search for Media Player SDK and get proved. But now Jeffery and his team makes this very easy. I don’t mumble out any words check the screen shot below.

One of the major source of inspiration for me to go for Power Shell , is the Dotnet class can also be invoked from here. This was lacking in VBScript and as result I was actually going to learn VB.net. Thank GOD..And Many thanks to Jeffery Hicks and his book on Powershell, Please download Powershell sample chapter to learn.

I wanna put screen but it is not getting display properly...I will put in few days on my google pages.



Monday, November 27, 2006

Command Line experience shared

Few weeks back I discovered that you don't need to give anyone Join to domain account permission and neither you need to go to client's place to add the machine to domain, with Netdom you can easily achieve the purpose. Netdom command Microsoft introduced long back with Windows2003

netdom join /d:zarays.com clu_node_b /userd:zarayspzare_s07 /passwordd:* /usero:administrator /passwordo

Above command is explained.

d: domain name

clu_node_b: Machine name

Userd: who has permission to add machine to domain

usero: who has admin permission on the machine/Workstation

you also have a reboot option , if you use it entire process is automated.


Below mentioned commands are introduced starting WinXP SP2 I guess


systeminfo /S \wkstn1 "c:sysinfo.txt" this command will help you gather information of remote machine,especially the make/Model.Physical Memory and Page file size stuff, which helps you confirm if the machine is configured for dump analysis.


sc \server2 query this is of great help to control services running on remote machine. If it is way behind when you compare it with Sysinternal utilites.


eventquery /L application I don't want to put this command here but Ithought because it is waste of time using this command. So don't use it at all


openfiles /query –s server2 : This command will help you get open files on the remote computer. This is generally require when you user call IT Helpdesk Excel is saying file is locked and owner of the file is the owner(user who call IT Helpdesk). It is of great use in this case. But again sysinternal tools are way ahead of it.


tasklist /s server2 : This is good starting point to get information about what is happening on the remote server. Infact it is quickest way of checking things.


compmgmt.msc /computer=SERVERNAME Run this stuff in RUN Box and you don;t need those redundant clicks. You directly get the management console of remote machine. Infact there is one more way of it, I can't recall it right now.


Sysinternals tools are way beyond these few command line tools mentioned above but these tools are not only handy but also widely accepted by cooporate enivornment by default as approved tools by MS. But as far as sysinternal is considered it won't be case any longer since they are working for Microsoft now. But anyways I would be most happy to share few tips and tricks on Sysinternal tools which I have used and customised it. But Next Time

Technorati Profile

Saturday, November 04, 2006

Cluster Diagnostic Tool

Hello Guys,

I have been googling for long time to get hold of good guide for cluster diagnostic tool published by MS. I ended up with one link which gives only way how it works but it never tells you what it is does and what are things which you use to make best of it. And what you should never do. That fact that there aren’t clear guidelines on this tool I decided to explore the tool. You certainly can't explore this tool on production enviornment so created a virtual server and set cluster in i t.

CLUSDIAG: can be downloaded from Microsoft site or else if you have resource tool kit installed for windows 2003 then you just need to go to E:\Program Files\Windows Resource Kits\Tools and double click clusdiag.msi. Shortcut is automatically created for this tool on the desktop.

Doubleclick the shortcut and start working on it. There are two things in this tool, you can read logs of cluster online (live) or offline. Live is pretty clear to understand and offline is nothing but copy cluster log and paste it any directory and then point this tool to pick log file from that location.

Online will be very useful in doing pre-production activities. It gives you disk view and network view. In order to get disk view and network view you will have to run the diagnostic test available under Tools menu or simply press Ctrl+R.

Other useful feature of this tool is that you can bookmark and toggle very easily between bookmarks which gives very clear view of what has happened and will helps you in keeping tab of things. By default filter is applied to these logs. You can remove the filter which is of less use because cluster log file becomes more verbose and it is bit of less use right now. To remove default filter navigate to View -> Filer and clear (Shift+F4)

In the end you can also find error code, for example error code is 0 it means it was success, if the error code was 2 the source file couldn’t be located. In order to carry out this activity, open cluster log file, search for word status and check what is the number infront of it. Select only number (try not to select 0 it doesn’t like it) and go Tools and find win32 error it will give you what will decode the error for you. Here you can try zero. J

Things which are mentioned above are steps which you would certainly like to carry out only on test machine. I hope this log might be of some help to all.

I'm finding ways how can I put images which makes this whole blog more helpful.


When you open Clusdiag 1

When you open Online Log 1


Cluster Log file location 1

Cluster Log file view 1

Log file without filter 1#

Decode Win32 Error 1



If you try to click on Network View or Disk view without running the test you are more likely to get this error.