## Thursday, November 11, 2010

### Net stop command does not work in batch file

We have a batch file with essentially below two lines

net stop ikeext & NET start ikeext

Usually, this should stop the service  ikeext & then start it again, but it failed to stop the dependent services and thus could not restart. Same sequence works perfect on command prompt.

SOLUTION
Add few timeout commands in between and break processing in mulpiple commands. Timeout command is natively available on windows vista onwards.

TIMEOUT /T 5
net stop ikeext
TIMEOUT /T 15
sc query ikeext   |   findstr   /i   RUNNING   2> NUL   1> NUL
IF  %ERRORLEVEL%   EQU  1  (  NET start "ikeext"  )   else   (  echo "ikeext service already running"  )

## Wednesday, November 3, 2010

### Single line Commands on Windows

Check if a domain user exists. Add user if it does not exist.
Check if a share exists. Create share if it does not exist.
• Net Share | findstr  /i  %SystemDrive%\Temp  |  findstr /i my > NUL  &  IF %ERRORLEVEL%  NEQ 0  ( net share My=%SystemDrive%\Temp /GRANT:Users,FULL )
Change File permissions inside a folder
• Applicable vista onwards.
• DIR C:\Temp\WinTest-*.log 2> NUL 1> NUL & IF %ERRORLEVEL% EQU 0 FOR %I in (C:\Temp\WinTest-*.log) do ICACLS %I /grant EveryOne:(F)

There will definitely be Powershell, WMI and Vbscript way of doing same thing, but sometimes we do need CMD commands.

## Wednesday, October 13, 2010

### Recent miscellaneous experiences and observations

• Adobe is adding too much junk in our recycle bin folders. It is seriously hampering the work by reducing HDD available size heavily.
• When seeing downloaded videos like NPTEL from YouTube, it is good to use a wireless headphone. Keep laptop away and turn off wireless service. This way a good video can be finished much quicker than the laptop kept nearby. This becomes possible due to avoidance of constant itching to use internet and neck being in comfortable position.
• Facebook is so ubiquitous that it is appearing even on restaurant menus. And even on http://licindia.in, an insurance company, homepage. Google must be having real tough time seeing first big loss on online space where they were first movers.
• When installing new OS, it is better to remove secondary HDD from machine. I am stuck with an IDE drive on machine that cannot be removed since SATA based OS has its boot loader on IDE drive.
• In India, it is good to open your PC every 2nd month and clean cabinet fan and SMPS fan. SMPS fans are inside the warranty seal, but if it is Rs 400-500 one, then why to bother with warranty. Dirt accumulated on them made PC makes too much noise. Do general brushing on other parts also.
• Regularly use DVD writer, else they will fail when you really need them.
• All available indications shows that WP7 will continue to be also-ran, but no market leader in near future.
• Recent DDR3 & N455 powered netbooks are high on performance, but not on battery power compared to widespread DDR2 N450 powered ones.

## Sunday, October 10, 2010

### Windows problems with heavily loaded machine

Mixing boot device
I have a 3 HDD machine now, one of which is IDE drive. IDE drive is original drive on machine. Other two are SATA drives. Even though no OS exists on IDE drive as well as both drives in it are formatted, windiws continue to keep critical boot loading files in this hard disk. Removing this results in boot failure. I am still searching for the soultion after banging my head for around 8 hours. Lets see when that solution comes? Some blog post are offering solutions, but need to be in correct bend of mind to pursue them.

Unable to recognize USB ports.
Once I attached 3rd HDD which is SATA, windows stopped recognizing any USB ports except those used for mouse & keyboard. All front and back USB went bad and haywire. FInally, I had to go into BIOS and do "Load default optimized settings" which turned off VT support. This is intel DP8545SG motherboard. But, USB started getting recognized after that. After that, I enabled VT support and things are still fine. Let see how long, since seagate manager still has issue recognizing external HDD when opened. Some delay seems to be there.

Since friday 9th oct 2010, I was facing issue accessing my rediffmail account. And it happened on 4 places, 2 desktops (one at home, another at office), my personal netbook at home as well as my mobile. Everywhere, rediff told me to try after a while and it went on for 2 days. Then checking some forums clicked an eureka moment. In all of these places, I had enabled "Keep me signed in". So, I signed out from rediff.com page and then signed in again. This resulted in things starting to work again. It seems some cookie was in stale mood and not in sync with server. Whatever, problem is resolved !!!!!!!!

But, rediff could seriously do with some good PMs and testers. Just asking users to tryu after a while when it is cookie expired issues is really bad designing.

## Monday, September 13, 2010

### Rebooting machine via standard user on Windows

While trying to write an automation, I needed to reboot machine using non-administrator user on server 2003 and windows xp. General way to do the same is to use one of the following ways

InitiateSystemShutdownEx API
Shutdown /r /f

Both of these failed with "Access denied" error. In case of  API, OpenProcessToken returned the error. OpenProcessToken is first step to acquire privilege SE_SHUTDOWN_NAME. Access denied error in this API. Obvious answer is to use impersonation APIs and then  attempt. Still same failure. It seems simple impersonation cannot help acquire required permissions, even in server 2003 & XP.

Next attempt was to check some sysinternal tool to be able to reboot. Mind it, I know all passowrds in plaintext as it is test automation. Even PsShutdown tool had same issue.

Finally, A hacky solution was found and that is add our standard user to "Backup operators" group which can be easily done through the API "NetLocalGroupAddMembers". Problem solved. No security issues either and achieved my shutdown work within same application.

## Sunday, May 16, 2010

### Issue with Airtel Broadband: Network not getting detected after reboot

I had this issue since last 2 months. On rebooting the machine, network address was not getting acquired. Airtel probably made some setting change and my connection got screwed up.

To get around the issue, I was running below power shell script on reboot every time. Since it needs to be run as administrator, there is no point putting it as login script. A pain for long time. Or manually, I needed to disable and enable network interface to get network address.

NetworkInterfaceSetting.ps1
1. #==============================================================================
2. # 3 ways to enable and disable a physical network interface using WMI.
3. # All boils down to finding device id of a relevant interface
4. # All gets into a single function as you see, so this function can be
5. # used in pipeline out of this script also.
6. # 17 May, 2010
7. # Tested using Powershell 2.0 on windows 7 x64 ultimate.
8. #==============================================================================
9.
10. # Function to check if PowerShell is running elevated
11. function Check-Elevated
12. {
13.   $wid=[System.Security.Principal.WindowsIdentity]::GetCurrent() 14.$prp=new-object System.Security.Principal.WindowsPrincipal($wid) 15.$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
16.   $IsAdmin=$prp.IsInRole($adm) 17. if ($IsAdmin){
18.     Set-Variable -Name elevated -Value $true -Scope 1 19. } 20. } 21. 22. function EnableDisableIF() 23. { 24. begin { 25. "Enabling and disabling few nw interfaces" 26.$Script:Total = 0
27.     }
28.     process{
29.         $Script:Executed=$true
30.         if ($_.GetType() -eq [Int] ) {$DevID = $_ } else {$DevID = $_.DeviceID} 31. (gwmi win32_networkadapter -filter ("deviceid=" +$DevID)).disable()
32.         trap {$Script:Executed =$false; continue}
33.         if ($Script:Executed) { 34. (gwmi win32_networkadapter -filter ("deviceid=" +$DevID)).enable()
35.             trap {$Script:Executed =$false; continue}
36.         }
37.         if ($Script:Executed) {$Script:Total += 1}
38.     }
39.     end{ ("Tried to Modify " + $Script:Total + " Interfaces") } 40. } 41. 42. Check-Elevated 43. if (!$elevated) {Write-Warning "Not much advantage running as non-admin"; return}
44.
45. #This should work in most cases even when network interface has been disabled for some reason
46. $(gwmi win32_networkadapter) | ?{$_.MACAddress -ne $null} | EnableDisableIF 47. 48. #I will prefer using above one, but this one can alse be used 49. #gwmi win32_networkadapter -Filter "NetEnabled=true" | EnableDisableIF 50. 51. # Use below if you know interface id. Uncomment & change interface id to use it 52. # 7 | EnableDisableIF Today, while fixing some other issue, I tried Airtel NetXpert trouble-shooter randomly and issue got fixed !!! Airtel NetXpert is @ "E:\Program Files (x86)\Airtel\NetXpert\agent\bin\bcont.exe" /p nxpclient” in my x64 system. Most of the people may have it @ “C:\Program Files\Airtel\NetXpert\agent\bin\bcont.exe" /p nxpclient”. In windows 7 & windows vista, it will require to be run from inside administrator login. This is bad design choice, but anyway. Run it when there is no network available. That should show below screens in succession Be patient here for some time to get below screen. Click on “Get Connected” and that should take you to Be patient with “Connection detection” screen and very soon you will see this screen offering to reset your network connection. Allow it to do so and done. Reboot machine to believe yourself. ## Thursday, May 13, 2010 ### Powershell Scenario: Convert Non-tabular Text file to tabular structured file I had a file structured like this. ================ Item ID: 1 Item Name: abc1\def1\ Item Child ID: 1 , Item Child path: child11 \ child 12 ================ Item ID: 2 Item Name: abc2\def2\ Item Child ID: 1 , Item Child path: child11 \ child 12 Item Child ID: 2 , Item Child path: child21 \ child 22 ================ Item ID: 3 Item Name: abc3\def3\ Item Child ID: 1 , Item Child path: child31 \ child 32 It was a big file with this hierarchical structure. I wanted to see this as  Item ID Item Name Item Child ID Item Child path 1 abc1\def1\ 1 child11 \ child 12 2 abc2\def2\ 1 child11 \ child 12 2 abc2\def2\ 2 child21 \ child 22 3 abc3\def3\ 1 child31 \ child 32 New Powershell features used 1. Custom objects 2. ConvertTO-HTML This is specific to Powershell 2 on windows 7. Convert-HiearchyToTable.ps1 1. param ($FileName)
2.
3. if (!$FileName) {Write-Error "It would be nice to have some input file."; return} 4. 5. Add-Type @' 6. public class TaggingObject 7. { 8. public string ItemID = ""; 9. public string ItemName = ""; 10. public string ChildID = ""; 11. public string ChildPath = ""; 12. } 13. '@ 14. 15.$LineList = Get-Content $FileName 16. trap {Write-Error "Check file name"; break} 17.$TagInstanceList = @()
18.
19. $ItemID = "" 20.$ItemName = ""
21. foreach ($LineTemp in$LineList){
22.     $Line =$LineTemp.Trim()
23.     if (($Line.StartsWith("=====")) -or  24. ($Line.Trim().length -eq 0)){
25.         continue
26.     }
27.
28.     if ($Line.ToLower().StartsWith("job name")){ 29.$ItemName = ($Line.Split(":", [StringSplitOptions]::RemoveEmptyEntries))[1] 30. continue 31. } 32. 33. if ($Line.ToLower().StartsWith("item child id")){
34.         $TagInstance = New-Object TaggingObject 35.$TagInstance.ItemID = $ItemID 36.$TagInstance.ItemName = $ItemName 37. 38.$CategoryValues = $Line.Split(@(':',','), [StringSplitOptions]::RemoveEmptyEntries) 39.$TagInstance.ItemChildID = $CategoryValues[1] 40.$TagInstance.ItemChildPath = $CategoryValues[3] 41. 42.$TagInstanceList += $TagInstance 43. continue 44. } 45. } 46. 47.$FileNameHTML = $FileName.replace(".txt", ".htm") 48.$TagInstanceList | ConvertTo-Html > FileNameHTML Save this as Convert-HiearchyToTable.ps1 and call as Convert-HiearchyToTable.ps1 [TEXT_FILE.TXT] If will generate TEXT_FILE.htm in the same path as TEXT_FILE.TXT. Off course, you should have write access to that folder. Now this HTML file will show as very nice tabular structure which can be opened in excel also for some formatting. When it is opened in excel, excel will complain that this files i used by ‘another user’ for modification. Workaround is to open that file as read only and then save as excel to continue modification. ## Tuesday, April 20, 2010 ### Visual studio 2010 Premium from MSDN subscription Following components installs as part of this on windows 7 x64 box. It is pre-pidded, so no key needs to be entered. I used WinRAR to extract ISO file in one folder. Previous installation of Beta version though left two components on machine. Strangely on one machine in office where Beta was installed earlier, reboot was required fairly early in setup process. This home machine which had RC earlier is not asking for reboot though. ## Saturday, April 3, 2010 ### How does a C program work Being a new user in stack overflow, I cannot post more than one link, hence ended up writing answer here. Question is Some general C questions. It seemed intriguing, so I did some research and then found few things, which are explained below. MSDN has some material on C language. Check out [C langugae reference on MSDN][1] . In general, in my view, when you are programming on Windows, it is good to search MSDN using Google. You will find many useful samples of OS APIs along the way making your job much easier. The new MSDN layout of related links of left side of a help page can also help discover things. Now, as for the structure of program and how it executes. When compiling, your compiler will look into standard location for standard c library calls. When using Visual studio on Windows, those functions will be found inside msvcrtxxx.dll. On VS 2010, XXX is 100 or version 10. In VS 2010, you can tell it to use VC90 also. More is [here][2] and @ [Run time library reference][3]. This DLL will not be linked inside your program. Only a reference or stub will be inserted inside using the corresponding .lib file. At runtime, the DLL that actually implemented this function will be loaded into memory and stub will be extended to the address of function in DLL. This DLL is part of your program's virtual memory. BTW, A DLL is like shared library of UNIX. Once loaded into memory, other programs too can reference its functions. You can used [depends.exe][4] to see the implicit dependency of your program. In windows, you can use loadlibrary to explicitly load dll at runtime also and then use its functions. For non-standard C functions or OS APIs, you will need to see help to find the library name that implemented it. So, if you need to get system information, [GetSystemInfo][5] will need to be called. Seeing its help on MSDN, you notice that it asks you to use kernel32.dll/kernel32.lib. During compilation, you will refer to kernel32.lib using a compiler (cl.exe for VS) switch and during runtime, kernel32.dll will be located by VC runtime as this is standard OS library. Runtime mostly does this de-referencing only once for each function call. You can use Cl.exe switches to specify the custom location of dll & lib files also. For non-standard C functions and non-standard OS APIs, you will need to see their help to find the library name that implemented it and put/locate that DLL on system running the application. Usually, setup project of VS does all this and put things in nice package for you to deploy on target machine. You can choose to do static binding of libraries also. This saves times in loading DLLs as well as runtime de-referencing, but increase program size since library code is embedded inside your exe. For EXE structure, check out [Peering inside the PE][6] and [Portable Executable structure][7]. All windows EXE are structured in this way or a slight variant. For your executable created by C program, exact entry point will not be main() function. Compiler creates another functions known as initialization and termination functions inside your executable. See [GNU CC Init/Terminate][8] & [Sun Init/Terminate][9]. As you continue working on C programs, you will get to know these things better. In short, Init functions do stack & static data space setup, required dll loading and in general setting up environment. They also process arguments received. After all this is done, main is called with arguments. Once main exits, again terminate routines are called which handles passing back return values, closing open handles & general cleanup. Implementation is very much compiler and OS dependent. PS: Even though Stack overflow did not allow me to post this thing on their site, I like their editor which creates a nice structure. I will consider writing my entries on their site in future and then copy-paste in windows live writer for better alignment and further posting. Toughest thing to search was Initialization and termination routines reference. Definitely, their is a lack of a standard documentation on windows platform for internals of tools used by us. ## Friday, April 2, 2010 ### Powershell: Play with Media files Code Snippet 1. function MediaObjects(FolderName=".")
2. {
3.     #http://huddledmasses.org/editing-media-tags-from-powershell/
4.     #http://developer.novell.com/wiki/index.php/TagLib_Sharp
5.     if (![AppDomain]::CurrentDomain.GetAssemblies() | ?{$_.fullname -like "taglib-sharp*"}){ 6. Write-Host$("taglib-sharp is not loaded. use below command to load it");
7.         Write-Host $("[Reflection.Assembly]::LoadFrom( (Resolve-Path <Path of \taglib-sharp.dll>) )"); 8. return (@()) 9. } 10. if (![System.IO.Directory]::Exists($FolderName)){
11.         Write-Host $($FolderName + " : Media directory does not exist.");
12.         return (@())
13.     }
14.     $mediaExtensionList = @(".asf",".avi",".flac",".m4a",".m4p",".m4v",  15. ".mp+",".mp3",".mp4",".mpc",".mpe",".mpeg",".mpg",  16. ".mpp",".mpv2",".ogg",".wav",".wma",".wmv",".wv") 17. 18.$FileList = dir -Recurse -Include "*.*" -Path $FolderName |  19. ?{($_ -is [IO.FileSystemInfo]) -and ($mediaExtensionList -contains$_.Extension)}
20.     if (!$FileList){ 21. return (@()) 22. }else{ 23.$ObjList=@()
24.         foreach ($Item in$FileList)
25.         {
26.             #http://huddledmasses.org/trap-exception-in-powershell/
27.             #Excellent article
28.             trap [Exception]{
29.                 Write-Host $($Item.FullName + " threw exception.");
30.                 write-host $("tTRAPPED: " +$_.Exception.GetType().FullName);
31.                  write-host $("tTRAPPED: " +$_.Exception.Message);
32.                 continue
33.             }
34.             $ObjList += [TagLib.File]::Create($Item.FullName)
35.         }
36.         return ($ObjList) 37. } 38. } 39. 40. function modifyMediaFiles($FolderName=".", $TagName="Genres",$NewTagValue="Hindi Movie")
41. {
42.     Write-Host $("Only display the name of those which are getting modified"); 43. foreach ($media in @(MediaObjects($FolderName))) 44. { 45. if (($media.tag.$TagName -contains$NewTagValue) `
46.          -and ($media.tag.$TagName.length -eq 1 ) )
47.         {
48.             continue;
49.         }
50.         $media.tag.$TagName=@($NewTagValue) 51.$media.save()
52.         $media.name 53. } 54. } 55. 56. function showMediaTags($FolderName=".", $TagName="Genres") 57. { 58. foreach ($media in @(MediaObjects($FolderName))) 59. { 60. Write-Host$(([String]::Join(";=;",$media.tag.$TagName)+" : "+$media.Name)); 61. } 62. } 63. 64. #showMediaTags 65. #modifyMediaFiles "G:\Music\HindiMovies\2005" 66. #modifyMediaFiles "G:\Music\HindiMovies\2006" 67. #showMediaTags "G:\Music\HindiMovies\2006" 68. #showMediaTags "G:\Music\HindiMovies\2009\Aagey Se Right" Some attribution first Original Explanation: http://huddledmasses.org/editing-media-tags-from-powershell/ Media Toolset: http://developer.novell.com/wiki/index.php/TagLib_Sharp Nice one to work with media files How to handle exception: http://huddledmasses.org/trap-exception-in-powershell/ Good discussion on how to return arrays: http://blogs.msdn.com/powershell/archive/2007/01/23/array-literals-in-powershell.aspx Power GUI: http://powergui.org/index.jspa . A nice tool. It took some iterations, but final thing came pretty easy. MediaObjects as shown below can be saved in our profile script. At the same time, we can add loading of taglib-sharp also in profile folder. Anyway, function will warn you if not loaded. showMediaTags & modifyMediaFiles are two examples, but we can use many more such small function once we get System.Array of TagLib.Mpeg.AudioFile from MediaObjects. Notice how I am returning empty array and how exception is handled. Above links have more explanation on each of these. Using the functions, I could make modification in lot of files. Code highlighter plugin in windows live writer ## Friday, March 26, 2010 ### WMI Permissions & SDDL ## Tuesday, March 23, 2010 ### Powershell: Find Process User name without using WMI function get-ProcUser ([System.String]$procname)
{
if (!$procname) {return "Provide some process name"}$proclist=get-process $procname.trim() -ErrorAction silentlycontinue if(!$proclist -and ($procname.contains("."))){$proclist=get-process $procname.split(".")[0].trim() -ErrorAction silentlycontinue } if(!$proclist) {return "Provide some proper process name"}

foreach($proc in$proclist)
{
$procprop=tasklist /V /FO List /FI ("PID eq "+$proc.id)
foreach ($field in$procprop)
{
if ($field -match "user name") {$field.split(":")[1].trim()
}
}
}
}

I have tried to handle the minimal errors here. You can add more if you wish.

Parameter can be made to pass id also, but that won’t be too useful.

Error handling is in small fonts.

Checked only on Windows 7 RTM x64. ErrorAction may not be valid on V1.

Tried hard on C#, but could not find any options.

Versions of Installed applications

gwmi -query "Select name,version from Win32_Product" | format-table name,version

## Monday, March 8, 2010

### UPS Assisted home network settings

Facts

• Power goes down frequently. It is India.
• In a 3 BHK flat, network cable from DSL company, Airtel, is coming into a corner room.
• I own a PC which needs UPS backup, but my flatmates own laptop and need to share this connection.
• Airtel wireless router is not so cheap.

Solution

Create above configuration using the following

• Two 10 meters network Ethernet cables.
• A UPS that can support network load for extended period. In this case, it is Back-UPS ES 650Y-IN from APC, which gives me enough backup to keep router+modem running for around 2 hours at least.
• A simple electrical wire of 10 meters with a male and a female sockets on either side.
• A Power-strip.
• A DSL modem & and a wi-fi enabled router. Wi-Fi enabled router in this case is from Linksys and Modem is provided by Airtel.

Procedure

• Connect Modem to UPS through Power strip.
• Keep Wi-Fi router in drawing room where from every part of flat can receive good signal.
• Attach Wi-Fi power plug to female part of electrical wire and extend that wire to power strip kept near UPS.
• Now take out Ethernet output of Modem using one of 10 meter NW cables to Wi-Fi router’s input.
• Use one 10 meter NW cable from Router’s output to bring network to PC which is attached to UPS directly.
• Use steps in the post, Linksys wireless router setup with Airtel broadband, to setup Router.
• Above Green connectors are NW cables and red ones shows power lines to UPS.

Cautions

• Avoid running PC during power outage as this draws power fast and irritates due to warning sound.

## Tuesday, February 9, 2010

### Powershell ISE does not honour scope operators

Write this in a script file and open that in Powershell ISE.

$Script:Abc=10 function abc {$k = 10

}

# Do some processing

\$Script:Abc = 20

abc

Execute above statements using Run button in ISE and check get-variable. you will find that Abc is still set in. Next invocation of script will start with Abc being set as 20. Reason being that powershell ISE calls scripts using dot-sourcing.

Alternate for this trouble can be using all variables inside some functions.

### in.sun.com still available when sun.com went into oblivion

sun.com now takes us to oracle.com. But, sun worldwide is still displaying sun.com address :-) Lot much needs to be done than front page eyewash only.

## Sunday, January 17, 2010

### How to control IDT audio panel

This is on Intel DP45SG motherboard which has inbuilt Audio support.

It took me almost 3 months to figure out finally the quirks associated with IDT audio panel. I am not still very sure though, but just noting down the same here.

Task is to keep both headphone and rear speaker connected, but control those through the IDT panel.

STEP 1: Connect both rear and headphone jacks.

STEP 2: Open IDT panel from system tray. In windows 7, this is hidden near clock icon. Select Speaker option from left side and then go to settings page. That will show below screen.

STEP 3: Select Preference tab which will show below screen. In the end of screen, there is option to mute rare speakers.

I am yet to find a way to turn of headphone while it is still connected. The only way seems to be taking out jack. However this action destabilizes IDT panel when it is running in foreground. Hence, it is better to remove any jacks only when panel is in background.

Also, it takes this panel a while to recognize the jack inserted in front jacks.