Tuesday, April 24, 2007

An error has occurred in the script on this page

regsvr32 msscript.ocx
regsvr32 dispex.dll
regsvr32 vbscript.dll

Monday, April 23, 2007

Problem https connexion

Regsvr32 Initpki.dll /s
Regsvr32 Dssenh.dll /s
Regsvr32 Gpkcsp.dll /s
Regsvr32 Sccbase.dll /s
Regsvr32 Slbcsp.dll /s
Regsvr32 Mssip32.dll /s
Regsvr32 Cryptdlg.dll /s
Regsvr32 Softpub.dLL /s
Regsvr32 Wintrust.dll /s
Regsvr32 Rsaenh.dll /s

Monday, April 16, 2007

Evolution

Powershell

Wednesday, April 11, 2007

JavaScript Dropdown Menu

// Copyright (C) 2005 Ilya S. Lyubinskiy. All rights reserved.
// Technical support: http://www.php-development.ru/
//
// YOU MAY NOT
// (1) Remove or modify this copyright notice.
// (2) Distribute this code, any part or any modified version of it.
// Instead, you can link to the homepage of this code:
// http://www.php-development.ru/javascripts/dropdown.php.
//
// YOU MAY
// (1) Use this code on your website.
// (2) Use this code as a part of another product provided that
// its main use is not creating javascript menus.
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind, either
// expressed or implied, including, but not limited to, the implied warranties
// of merchantability and fitness for a particular purpose. You expressly
// acknowledge and agree that use of this code is at your own risk.


// ----- Popup Control ---------------------------------------------------------

function at_display(x)
{
var win = window.open();
for (var i in x) win.document.write(i+' = '+x[i]+'
');
}

// ----- Show Aux -----

function at_show_aux(parent, child)
{
var p = document.getElementById(parent);
var c = document.getElementById(child );

var top = (c["at_position"] == "y") ? p.offsetHeight+2 : 0;
var left = (c["at_position"] == "x") ? p.offsetWidth +2 : 0;

for (; p; p = p.offsetParent)
{
top += p.offsetTop;
left += p.offsetLeft;
}

c.style.position = "absolute";
c.style.top = top +'px';
c.style.left = left+'px';
c.style.visibility = "visible";
}

// ----- Show -----

function at_show()
{
var p = document.getElementById(this["at_parent"]);
var c = document.getElementById(this["at_child" ]);

at_show_aux(p.id, c.id);

clearTimeout(c["at_timeout"]);
}

// ----- Hide -----

function at_hide()
{
var c = document.getElementById(this["at_child"]);

c["at_timeout"] = setTimeout("document.getElementById('"+c.id+"').style.visibility = 'hidden'", 333);
}

// ----- Click -----

function at_click()
{
var p = document.getElementById(this["at_parent"]);
var c = document.getElementById(this["at_child" ]);

if (c.style.visibility != "visible")
at_show_aux(p.id, c.id);
else c.style.visibility = "hidden";

return false;
}

// ----- Attach -----

// PARAMETERS:
// parent - id of visible html element
// child - id of invisible html element that will be dropdowned
// showtype - "click" = you should click the parent to show/hide the child
// "hover" = you should place the mouse over the parent to show
// the child
// position - "x" = the child is displayed to the right of the parent
// "y" = the child is displayed below the parent
// cursor - Omit to use default cursor or check any CSS manual for possible
// values of this field

function at_attach(parent, child, showtype, position, cursor)
{
var p = document.getElementById(parent);
var c = document.getElementById(child);

p["at_parent"] = p.id;
c["at_parent"] = p.id;
p["at_child"] = c.id;
c["at_child"] = c.id;
p["at_position"] = position;
c["at_position"] = position;

c.style.position = "absolute";
c.style.visibility = "hidden";

if (cursor != undefined) p.style.cursor = cursor;

switch (showtype)
{
case "click":
p.onclick = at_click;
p.onmouseout = at_hide;
c.onmouseover = at_show;
c.onmouseout = at_hide;
break;
case "hover":
p.onmouseover = at_show;
p.onmouseout = at_hide;
c.onmouseover = at_show;
c.onmouseout = at_hide;
break;
}
}

10 Steps to Solving Any Problem

Ten Steps To Solving Any Problem - by Brian Tracy and Colin Rose

The more organized and systematically you deal with any problem, the more positive and creative you will be in solving it. Here is a 10-step method you can use to think systematically. With this method, you develop your creativity to genius levels.

1. Change your language from negative to positive. Instead of using the word "problem," use the word "situation," or call it a challenge or an opportunity. If a sale falls through, you can say something like this is an interesting challenge. It's an opportunity for me to improve my sales effectiveness so this doesn't happen again in the future?

2. Define your situation or difficulty clearly. What exactly is the challenge you are facing? What is causing you the stress and anxiety? What is causing you to worry? Why are you unhappy? Write it out clearly in detail.

3. Ask, what else is the problem??Don't be satisfied with a superficial answer. Look for the root cause of the problem, rather than getting sidetracked by the symptom. Approach the problem from several different directions.

4. Ask yourself, what are my minimum boundary conditions??What must the solution accomplish? What ingredients must the solution contain? What would your ideal solution to this problem look like? Define your parameters clearly.

5. Pick the best solution by comparing your various possible solutions against your problem, on one hand, and your ideal solution, on the other. What is the best thing to do at this time under the circumstances?

6. Before you implement your decision, ask, what's the worst possible thing that can happen if this decision doesn't work??Before you make any expenditure of money or effort in trying to achieve your goal, you should evaluate what would happen if your decision were a complete failure.

7. Set measures on your decision. How will you know you are making progress? How will you measure success? How will you compare the success of this solution against the success of another solution? How will you define a success? Make it measurable, and then monitor it on a regular basis.

8. Accept complete responsibility for implementing the decision. Many of the most creative ideas never materialize because no one is specifically assigned the responsibility for carrying out the decision.

9. Set a deadline. A decision without a deadline is just a meaningless discussion. If it's a major decision and will take some time to implement, set a series of short-term deadlines and a schedule for reporting.

10. Take action. Get busy. Get going. Develop a sense of urgency. The faster you move in the direction of your clearly defined goals, the more creative you will be, the more energy you will have, the more you will learn and the faster you will develop your capacity to achieve even more in the future.

The world is full of creative individuals who have wonderful ideas, but almost all of them fall down when it comes to implementation. And this is where you can excel. The future belongs to the creative minority who can not only think but also take action and put their ideas into effect.

Now, here are three things you can do immediately to put these ideas into action. First, take your biggest problem or worry situation today, and ask yourself, what exactly is the problem? What am I worrying about?? Second, analyze your situation creatively and ask yourself, what else is the problem??Sometimes the real problem is not what you thought. Third, make a decision ?any decision. Assign responsibility or accept responsibility, and then take action on your ideas. The busier you work to solve your problems, the smarter you will become.

Tuesday, April 10, 2007

Wake-On-LAN with PowerShell

$POWEROFFEXE = "E:\poweroff.exe"

Import-Csv PCs.csv Foreach-Object { $params = (" wol -ip " + $_.Ip + " -subnet 255.255.0.0 -mac " + $_.Mac);
[diagnostics.process]::start($POWEROFFEXE, $params)
}
Reference:
Wake-On-LAN Script
Download PowerOff

Monday, April 9, 2007

HTML Color Code Chart

#990033
R:153
G:000
B:051
#FF3366
R:255
G:051
B:102
#CC0033
R:204
G:000
B:051
#FF0033
R:255
G:000
B:051
#FF9999
R:255
G:153
B:153
#CC3366
R:204
G:051
B:102
#FFCCFF
R:255
G:204
B:255
#CC6699
R:204
G:102
B:153
#993366
R:153
G:051
B:102
#660033
R:102
G:000
B:051
#CC3399
R:204
G:051
B:153
#FF99CC
R:255
G:153
B:204
#FF66CC
R:255
G:102
B:204
#FF99FF
R:255
G:153
B:255
#FF6699
R:255
G:102
B:153
#CC0066
R:204
G:000
B:102
#FF0066
R:255
G:000
B:102
#FF3399
R:255
G:051
B:153
#FF0099
R:255
G:000
B:153
#FF33CC
R:255
G:051
B:204
#FF00CC
R:255
G:000
B:204
#FF66FF
R:255
G:102
B:255
#FF33FF
R:255
G:051
B:255
#FF00FF
R:255
G:000
B:255
#CC0099
R:204
G:000
B:153
#990066
R:153
G:000
B:102
#CC66CC
R:204
G:102
B:204
#CC33CC
R:204
G:051
B:204
#CC99FF
R:204
G:153
B:255
#CC66FF
R:204
G:102
B:255
#CC33FF
R:204
G:051
B:255
#993399
R:153
G:051
B:153
#CC00CC
R:204
G:000
B:204
#CC00FF
R:204
G:000
B:255
#9900CC
R:153
G:000
B:204
#990099
R:153
G:000
B:153
#CC99CC
R:204
G:153
B:204
#996699
R:153
G:102
B:153
#663366
R:102
G:051
B:102
#660099
R:102
G:000
B:153
#9933CC
R:153
G:051
B:204
#660066
R:102
G:000
B:102
#9900FF
R:153
G:000
B:255
#9933FF
R:153
G:051
B:255
#9966CC
R:153
G:102
B:204
#330033
R:051
G:000
B:051
#663399
R:102
G:051
B:153
#6633CC
R:102
G:051
B:204
#6600CC
R:102
G:000
B:204
#9966FF
R:153
G:102
B:255
#330066
R:051
G:000
B:102
#6600FF
R:102
G:000
B:255
#6633FF
R:102
G:051
B:255
#CCCCFF
R:204
G:204
B:255
#9999FF
R:153
G:153
B:255
#9999CC
R:153
G:153
B:204
#6666CC
R:102
G:102
B:204
#6666FF
R:102
G:102
B:255
#666699
R:102
G:102
B:153
#333366
R:051
G:051
B:102
#333399
R:051
G:051
B:153
#330099
R:051
G:000
B:153
#3300CC
R:051
G:000
B:204
#3300FF
R:051
G:000
B:255
#3333FF
R:051
G051:
B:255
#3333CC
R:051
G:051
B:204
#0066FF
R:000
G:102
B:255
#0033FF
R:000
G:051
B:255
#3366FF
R:051
G:102
B:255
#3366CC
R:051
G:102
B:204
#000066
R:000
G:000
B:102
#000033
R:000
G:000
B:051
#0000FF
R:000
G:000
B:255
#000099
R:000
G:000
B:153
#0033CC
R:000
G:051
B:204
#0000CC
R:000
G:000
B:204
#336699
R:051
G:102
B:153
#0066CC
R:000
G:102
B:204
#99CCFF
R:153
G:204
B:255
#6699FF
R:102
G:153
B:255
#003366
R:000
G:051
B:102
#6699CC
R:102
G:153
B:204
#006699
R:000
G:102
B:153
#3399CC
R:051
G:153
B:204
#0099CC
R:000
G:153
B:204
#66CCFF
R:102
G:204
B:255
#3399FF
R:051
G:153
B:255
#003399
R:000
G:051
B:153
#0099FF
R:000
G:153
B:255
#33CCFF
R:051
G:204
B:255
#00CCFF
R:000
G:204
B:255
#99FFFF
R:153
G:255
B:255
#66FFFF
R:102
G:255
B:255
#33FFFF
R:051
G:255
B:255
#00FFFF
R:000
G:255
B:255
#00CCCC
R:000
G:204
B:204
#009999
R:000
G:153
B:153
#669999
R:102
G:153
B:153
#99CCCC
R:153
G:204
B:204
#CCFFFF
R:204
G:255
B:255
#33CCCC
R:051
G:204
B:204
#66CCCC
R:102
G:204
B:204
#339999
R:051
G:153
B:153
#336666
R:051
G:102
B:102
#006666
R:000
G:102
B:102
#003333
R:000
G:051
B:051
#00FFCC
R:000
G:255
B:204
#33FFCC
R:051
G:255
B:204
#33CC99
R:051
G:204
B:153
#00CC99
R:000
G:204
B:153
#66FFCC
R:102
G:255
B:204
#99FFCC
R:153
G:255
B:204
#00FF99
R:000
G:255
B:153
#339966
R:051
G:153
B:102
#006633
R:000
G:102
B:051
#336633
R:051
G:102
B:051
#669966
R:102
G:153
B:102
#66CC66
R:102
G:204
B:102
#99FF99
R:153
G:255
B:153
#66FF66
R:102
G:255
B:102
#339933
R:051
G:153
B:051
#99CC99
R:153
G:204
B:153
#66FF99
R:102
G:255
B:153
#33FF99
R:051
G:255
B:153
#33CC66
R:051
G:204
B:102
#00CC66
R:000
G:204
B:102
#66CC99
R:102
G:204
B:153
#009966
R:000
G:153
B:102
#009933
R:000
G:153
B:051
#33FF66
R:051
G:255
B:102
#00FF66
R:000
G:255
B:102
#CCFFCC
R:204
G:255
B:204
#CCFF99
R:204
G:255
B:153
#99FF66
R:153
G:255
B:102
#99FF33
R:153
G:255
B:051
#00FF33
R:000
G:255
B:051
#33FF33
R:051
G:255
B:051
#00CC33
R:000
G:204
B:051
#33CC33
R:051
G:204
B:051
#66FF33
R:102
G:255
B:051
#00FF00
R:000
G:255
B:000
#66CC33
R:102
G:204
B:051
#006600
R:000
G:102
B:000
#003300
R:000
G:051
B:000
#009900
R:000
G:153
B:000
#33FF00
R:051
G:255
B:000
#66FF00
R:102
G:255
B:000
#99FF00
R:153
G:255
B:000
#66CC00
R:102
G:204
B:000
#00CC00
R:000
G:204
B:000
#33CC00
R:051
G:204
B:000
#339900
R:051
G:153
B:000
#99CC66
R:153
G:204
B:102
#669933
R:102
G:153
B:051
#99CC33
R:153
G:204
B:051
#336600
R:051
G:102
B:000
#669900
R:102
G:153
B:000
#99CC00
R:153
G:204
B:000
#CCFF66
R:204
G:255
B:102
#CCFF33
R:204
G:255
B:051
#CCFF00
R:204
G:255
B:000
#999900
R:153
G:153
B:000
#CCCC00
R:204
G:204
B:000
#CCCC33
R:204
G:204
B:051
#333300
R:051
G:051
B:000
#666600
R:102
G:102
B:000
#999933
R:153
G:153
B:051
#CCCC66
R:204
G:204
B:102
#666633
R:102
G:102
B:051
#999966
R:153
G:153
B:102
#CCCC99
R:204
G:204
B:153
#FFFFCC
R:255
G:255
B:204
#FFFF99
R:255
G:255
B:153
#FFFF66
R:255
G:255
B:102
#FFFF33
R:255
G:255
B:051
#FFFF00
R:255
G:255
B:000
#FFCC00
R:255
G:204
B:000
#FFCC66
R:255
G:204
B:102
#FFCC33
R:255
G:204
B:051
#CC9933
R:204
G:153
B:051
#996600
R:153
G:102
B:000
#CC9900
R:204
G:153
B:000
#FF9900
R:255
G:153
B:000
#CC6600
R:204
G:102
B:000
#993300
R:153
G:051
B:000
#CC6633
R:204
G:102
B:051
#663300
R:102
G:051
B:000
#FF9966
R:255
G:153
B:102
#FF6633
R:255
G:102
B:051
#FF9933
R:255
G:153
B:051
#FF6600
R:255
G:102
B:000
#CC3300
R:204
G:051
B:000
#996633
R:153
G:102
B:051
#330000
R:051
G:000
B:000
#663333
R:102
G:051
B:051
#996666
R:153
G:102
B:102
#CC9999
R:204
G:153
B:153
#993333
R:153
G:051
B:051
#CC6666
R:204
G:102
B:102
#FFCCCC
R:255
G:204
B:204
#FF3333
R:255
G:051
B:051
#CC3333
R:204
G:051
B:051
#FF6666
R:255
G:102
B:102
#660000
R:102
G:000
B:000
#990000
R:153
G:000
B:000
#CC0000
R:204
G:000
B:000
#FF0000
R:255
G:000
B:000
#FF3300
R:255
G:051
B:000
#CC9966
R:204
G:153
B:102
#FFCC99
R:255
G:204
B:153
#FFFFFF
R:255
G:255
B:255
#CCCCCC
R:204
G:204
B:204
#999999
R:153
G:153
B:153
#666666
R:102
G:102
B:102
#333333
R:051
G:051
B:051
#000000
R:000
G:000
B:000

Saturday, April 7, 2007

awk change a column to a row

awk '{printf("%s,",$1)}' filename 

pgrep vs ps

[root@localhost X]# pgrep -d, -u root
1,2,3,4,5,18,28,29,31,19,30,105,181,190,1002,1475,1811,1815,1890,1958,2035,2066,2108,2123,2142,2161,2216,2326,2331,2342,2352,2401,2468,2534,2535,2536,2671,2820,2826,2958,2986,3019,3020,3025,3028,3030,3032,3038,3070,3074,3076,3078,3080,3082,3084,3086,3088,3097,3101,3143,3145,3147,3149,3151,3152,3153,6209,6213,6215,6217,6223,6225,6227,6232,6239,6449,6482,6483,6490,6491,6498,6499,6500,6501,6505,6506,6513,6536,6576,6583,6590,6595,6597,6600,6644
[root@localhost X]# ps -ef | egrep '^root ' | awk '{print $2}' | awk '{printf("%s,",$1)}'
1,2,3,4,5,18,28,29,31,19,30,105,181,190,1002,1475,1811,1815,1890,1958,2035,2066,2108,2123,2142,2161,2216,2326,2331,2342,2352,2401,2468,2534,2535,2536,2671,2820,2826,2958,2986,3019,3020,3025,3028,3030,3032,3038,3070,3074,3076,3078,3080,3082,3084,3086,3088,3097,3101,3143,3145,3147,3149,3151,3152,3153,6209,6213,6215,6217,6223,6225,6227,6232,6239,6449,6482,6483,6490,6491,6498,6499,6500,6501,6505,6506,6513,6536,6576,6583,6590,6595,6597,6600,6644

Thursday, April 5, 2007

Performs an LDAP Search Based on Given Criteria

'********************************************************************
'*
'* File: SEARCH.VBS
'* Created: August 1998
'* Version: 1.0
'*
'* Main Function: Performs an LDAP search based on given criteria.
'* Usage: SEARCH.VBS adspath [/C:criteria] [/S:scope] [/P:properties]
'* [/O:outputfile] [/U:username] [/W:password] [/Q]
'*
'* Copyright (C) 1998 Microsoft Corporation
'*
'********************************************************************

OPTION EXPLICIT
ON ERROR RESUME NEXT

'Define constants
CONST CONST_ERROR = 0
CONST CONST_WSCRIPT = 1
CONST CONST_CSCRIPT = 2
CONST CONST_SHOW_USAGE = 3
CONST CONST_PROCEED = 4

'Declare variables
Dim strOutputFile, intOpMode, blnQuiet, i
Dim strADsPath, strCriteria, strProperties, strScope, strUserName, strPassword
ReDim strArgumentArray(0)

'Initialize variables
strArgumentArray(0) = ""
blnQuiet = False
strADsPath = ""
strCriteria = "ObjectCategory=*"
strProperties = "ADsPath;"
strScope = "OneLevel"
strUserName = ""
strPassword = ""
strOutputFile = ""

'Get the command line arguments
For i = 0 to Wscript.arguments.count - 1
ReDim Preserve strArgumentArray(i)
strArgumentArray(i) = Wscript.arguments.Item(i)
Next

'Check whether the script is run using CScript
Select Case intChkProgram()
Case CONST_CSCRIPT
'Do Nothing
Case CONST_WSCRIPT
WScript.Echo "Please run this script using CScript." & vbCRLF & _
"This can be achieved by" & vbCRLF & _
"1. Using ""CScript SEARCH.vbs arguments"" for Windows 95/98 or" & vbCRLF & _
"2. Changing the default Windows Scripting Host setting to CScript" & vbCRLF & _
" using ""CScript //H:CScript //S"" and running the script using" & vbCRLF & _
" ""SEARCH.vbs arguments"" for Windows NT."
WScript.Quit
Case Else
WScript.Quit
End Select


'Parse the command line
intOpMode = intParseCmdLine(strArgumentArray, strADsPath, strCriteria, strProperties, _
strScope, blnQuiet, strUserName, strPassword, strOutputFile)
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred in parsing the command line."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
WScript.Quit
End If

Select Case intOpMode
Case CONST_SHOW_USAGE
Call ShowUsage()
Case CONST_PROCEED
Call Search(strADsPath, strCriteria, strProperties, _
strScope, strUserName, strPassword, strOutputFile)
Case CONST_ERROR
'Do nothing.
Case Else 'Default -- should never happen
Print "Error occurred in passing parameters."
End Select

'********************************************************************
'*
'* Function intChkProgram()
'* Purpose: Determines which program is used to run this script.
'* Input: None
'* Output: intChkProgram is set to one of CONST_ERROR, CONST_WSCRIPT,
'* and CONST_CSCRIPT.
'*
'********************************************************************

Private Function intChkProgram()

ON ERROR RESUME NEXT

Dim strFullName, strCommand, i, j

'strFullName should be something like C:\WINDOWS\COMMAND\CSCRIPT.EXE
strFullName = WScript.FullName
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred."
If Err.Description <> "" Then
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
End If
intChkProgram = CONST_ERROR
Exit Function
End If

i = InStr(1, strFullName, ".exe", 1)
If i = 0 Then
intChkProgram = CONST_ERROR
Exit Function
Else
j = InStrRev(strFullName, "\", i, 1)
If j = 0 Then
intChkProgram = CONST_ERROR
Exit Function
Else
strCommand = Mid(strFullName, j+1, i-j-1)
Select Case LCase(strCommand)
Case "cscript"
intChkProgram = CONST_CSCRIPT
Case "wscript"
intChkProgram = CONST_WSCRIPT
Case Else 'should never happen
Print "An unexpected program is used to run this script."
Print "Only CScript.Exe or WScript.Exe can be used to run this script."
intChkProgram = CONST_ERROR
End Select
End If
End If

End Function

'********************************************************************
'*
'* Function intParseCmdLine()
'* Purpose: Parses the command line.
'* Input: strArgumentArray an array containing input from the command line
'* Output: strADsPath ADsPath of the root of the search
'* strCriteria the search criteria
'* strProperties properties to be retrieved
'* strScope the search scope
'* strUserName name of the current user
'* strPassword password of the current user
'* strOutputFile an output file name
'* blnQuiet specifies whether to suppress messages
'* intParseCmdLine is set to one of CONST_ERROR, CONST_SHOW_USAGE, CONST_PROCEED.
'*
'********************************************************************

Private Function intParseCmdLine(strArgumentArray, strADsPath, strCriteria, _
strProperties, strScope, blnQuiet, strUserName, strPassword, strOutputFile)

ON ERROR RESUME NEXT

Dim strFlag, i

strFlag = strArgumentArray(0)

If strFlag = "" then 'No arguments have been received
Print "Arguments are required."
intParseCmdLine = CONST_ERROR
Exit Function
End If

If (strFlag="help") OR (strFlag="/h") OR (strFlag="\h") OR (strFlag="-h") _
OR (strFlag = "\?") OR (strFlag = "/?") OR (strFlag = "?") OR (strFlag="h") Then
intParseCmdLine = CONST_SHOW_USAGE
Exit Function
End If

strADsPath = FormatProvider(strFlag) 'The first parameter must be the ADsPath.

For i = 1 to UBound(strArgumentArray)
strFlag = LCase(Left(strArgumentArray(i), InStr(1, strArgumentArray(i), ":")-1))
If Err.Number Then 'An error occurs if there is no : in the string
Err.Clear
If LCase(strArgumentArray(i)) = "/q" Then
blnQuiet = True
Else
Print strArgumentArray(i) & " is not recognized as a valid input."
intParseCmdLine = CONST_ERROR
Exit Function
End If
Else
Select Case strFlag
Case "/c"
strCriteria = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/p"
strProperties = Right(strArgumentArray(i), Len(strArgumentArray(i))-3) & ";"
Case "/s"
strScope = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/u"
strUserName = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/w"
strPassword = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/o"
strOutputFile = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case else
Print "Invalid flag " & """" & strFlag & """" & "."
Print "Please check the input and try again."
intParseCmdLine = CONST_ERROR
Exit Function
End Select
End If
Next

intParseCmdLine = CONST_PROCEED

End Function

'********************************************************************
'*
'* Sub ShowUsage()
'* Purpose: Shows the correct usage to the user.
'* Input: None
'* Output: Help messages are displayed on screen.
'*
'********************************************************************

Private Sub ShowUsage()

Wscript.Echo ""
Wscript.Echo "Performs an LDAP search based on a given criteria." & vbCRLF
Wscript.Echo "SEARCH.VBS adspath [/C:criteria] [/S:scope] [/P:properties]"
Wscript.Echo "[/O:outputfile] [/U:username] [/W:password] [/Q]"
Wscript.echo " /C, /S, /P, /O, /U, /W"
Wscript.Echo " Parameter specifiers."
Wscript.echo " adspath ADsPath of a user object container."
Wscript.echo " criteria Criteria of the search."
Wscript.echo " scope Sope of the search."
Wscript.echo " properties Properties to be retrieved."
Wscript.Echo " outputfile The output file name."
Wscript.echo " username Username of the current user."
Wscript.echo " password Password of the current user."
Wscript.echo " /Q Suppresses all output messages." & vbCRLF
Wscript.Echo "DEFAULT VALUES:"
Wscript.Echo " If /C is not specified the default is ObjectCategory=*."
Wscript.Echo " If /S is not specified the default is OneLevel."
Wscript.Echo " If /P is not specified the default is ADsPath." & vbCRLF
Wscript.Echo "EXAMPLE:"
Wscript.Echo "SEARCH.VBS ""LDAP://DC=FooFoo,DC=Foo,DC=Com"""
Wscript.Echo " /C:""&(ObjectCategory=user)(cn=b*)"" /P:Name /S:SubTree"
Wscript.Echo " lists names of all users in domain FooFoo with"
Wscript.Echo " cn starting with ""b""." & vbCRLF
Wscript.Echo "NOTE:"
Wscript.Echo " This script requires an LDAP provider."

End Sub

'********************************************************************
'*
'* Sub Search()
'* Purpose: Performs an LDAP search based on a given criteria.
'* Input: strADsPath ADsPath of the root of the search
'* strCriteria the search criteria
'* strProperties properties to be retrieved
'* strScope the search scope
'* strUserName name of the current user
'* strPassword password of the current user
'* strOutputFile an output file name
'* Output: Results of the search are either printed on screen or saved in strOutputFile.
'*
'********************************************************************

Private Sub Search(strADsPath, strCriteria, strProperties, _
strScope, strUserName, strPassword, strOutputFile)

ON ERROR RESUME NEXT

Dim strProvider, strSearchPath, objConnect, objCommand
Dim objFileSystem, objOutputFile, objRecordSet, intResult

'Make sure that the provide is LDAP
strProvider = Left(strADsPath, InStr(1, strADsPath, ":"))
If strProvider <> "LDAP:" then
Print "The provider is not LDAP:."
Wscript.Quit
End If

If strOutputFile = "" Then
objOutputFile = ""
Else
'Create a filesystem object
set objFileSystem = CreateObject("Scripting.FileSystemObject")
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " opening a filesystem object."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Exit Sub
End If
'Open the file for output
set objOutputFile = objFileSystem.OpenTextFile(strOutputFile, 8, True)
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " opening file " & strOutputFile
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Exit Sub
End If
End If

strSearchPath = "<" & strADsPath & ">;"
strCriteria = "(" & strCriteria & ");"

Set objConnect = CreateObject("ADODB.Connection")
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " ocurred in opening a connection."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Exit Sub
End If

Set objCommand = CreateObject("ADODB.Command")
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " ocurred in creating the command object."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Exit Sub
End If

objConnect.Provider = "ADsDSOObject"
If strUserName = "" then
objConnect.Open "Active Directory Provider"
Else
objConnect.Open "Active Directory Provider", strUserName, strPassword
End If
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " ocurred opening a provider."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Exit Sub
End If

Set objCommand.ActiveConnection = objConnect

'Set the query string and other properties
objCommand.CommandText = strSearchPath & strCriteria & strProperties & strScope
objCommand.Properties("Page Size") = 100000 'reset search properties
objCommand.Properties("Timeout") = 300000 'seconds
' objCommand.Properties("SearchScope") = 2

'After setting all the parameter now execute the search and display the results.
intResult = intExecuteSearch(objRecordSet, objCommand, objOutputFile)

If strOutputFile <> "" Then
objOutputFile.Close
If intResult > 0 Then
Wscript.Echo "Results are saved in file " & strOutputFile & "."
End If
End If

End Sub

'********************************************************************
'*
'* Function intExecuteSearch()
'* Purpose: Performs an LDAP search based on given criteria
'* Input: objRecordSet a recordset to store the info returned
'* objCommand the query command object
'* objOutputFile an output file object
'* Output: Results of the search are either printed on screen or saved in objOutputFile.
'* intExecuteSearch is set to -1 if the search failed or the number of objects
'* found if succeeded.
'*
'********************************************************************

Private Function intExecuteSearch(objRecordSet, objCommand, objOutputFile)

ON ERROR RESUME NEXT

Dim intNumObjects, i, j , k, intUBound, strMessage

intNumObjects = 0
intUBound = 0
intExecuteSearch = 0

'Let the user know what is going on
Print objCommand.CommandText

'Execute the query
Set objRecordSet = objCommand.Execute
Print "Finished the query."
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " ocurred during the query."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Err.Clear
intExecuteSearch = -1 'failed
Exit Function
End If

'Get the total number of objects found.
objRecordSet.MoveLast
intNumObjects = objRecordSet.RecordCount
intExecuteSearch = intNumObjects 'Succeeded

If intNumObjects Then 'If intNumObjects is not zero
Wscript.Echo "Found " & intNumObjects & " objects."
objRecordSet.MoveFirst
k = 1
While Not objRecordSet.EOF
For i = 0 To objRecordSet.Fields.Count - 1
intUBound = UBound(objRecordSet.Fields(i).Value)

If Err.Number Then
'This means that it is a single valued property.
Err.Clear
strMessage = objRecordSet.Fields(i).Name & " " & k & " = " _
& objRecordSet.Fields(i).Value
Else 'It is a multivalued property.
If intUBound = 0 Then 'There is only one implemented
strMessage = objRecordSet.Fields(i).Name & " " & k & " = " _
& objRecordSet.Fields(i).Value(0)
Else 'It is truely multivalued.
strMessage = objRecordSet.Fields(i).Name & " " & k
For j = 0 to intUBound
strMessage = strMessage & vbCRLF & " " & j+1 & " " _
& objRecordSet.Fields(i).Value(j)
Next
End If
End If
WriteLine strMessage, objOutputFile
Next
objRecordSet.MoveNext
k = k + 1
Wend
Else
Wscript.Echo "No object satisfying the criteria has been found within " _
& strADsPath & "."
End If

End Function

'********************************************************************
'*
'* Sub WriteLine()
'* Purpose: Writes a text line either to a file or on screen.
'* Input: strMessage the string to print
'* objFile an output file object
'* Output: strMessage is either displayed on screen or written to a file.
'*
'********************************************************************

Sub WriteLine(ByRef strMessage, ByRef objFile)

If IsObject(objFile) then 'objFile should be a file object
objFile.WriteLine strMessage
Else
Wscript.Echo strMessage
End If

End Sub

'********************************************************************
'*
'* Sub Print()
'* Purpose: Prints a message on screen if blnQuiet = False.
'* Input: strMessage the string to print
'* Output: strMessage is printed on screen if blnQuiet = False.
'*
'********************************************************************

Sub Print(ByRef strMessage)
If Not blnQuiet then
Wscript.Echo strMessage
End If
End Sub

'********************************************************************
'*
'* Function FormatProvider
'* Purpose: Formats Provider so it is not case sensitive
'* Input: Provider a string
'* Output: FormatProvider is the Provider with the correct Case
'*
'********************************************************************

Private Function FormatProvider(Provider)
FormatProvider = ""
I = 1
Do Until Mid(Provider, I, 1) = ":"
If I = Len(Provider) Then
'This Provider is Probabaly not valid, but we'll let it pass anyways.
FormatProvider = Provider
Exit Function
End If
I = I + 1
Loop

Select Case LCase(Left(Provider, I - 1))
Case "winnt"
FormatProvider = "WinNT" & Right(Provider,Len(Provider) - (I - 1))
Case "ldap"
FormatProvider = "LDAP" & Right(Provider,Len(Provider) - (I - 1))
End Select


End Function


'********************************************************************
'* *
'* End of File *
'* *
'********************************************************************

'********************************************************************
'*
'* Procedures calling sequence: SEARCH.VBS
'*
'* intParseCmdLine
'* ShowUsage
'* Search
'* intExecuteSearch
'* WriteLine
'*
'********************************************************************

'********************************************************************

DACL : Set Filesystem and Registry ACL

Option Explicit

' Set Filesystem and Registry ACL
' ===============================
'
' Author: Tobias Oetiker
' based on code by Nick Pearce, Craig Paterson and Rich Ellis
'
' Version: 1.2 -- 2001/05/08
'
' Changes: 1.1 Handle non-existing registry keys gracefully.
' Changes: 1.2 Added "K" option for simulating 1777 permission
'
' The purpose of this script is to allow ACL maniputlations
' to be performed by Microsoft Installer Packages (.msi)
'
' Add your ACL modification instructions to this script
' and integrate it as a Custom Action into the MSI.
'
' SETUP
' =====
'
' Note aclfix needs ADsSecurity.dll and RegObj.dll to work.
' You can get ADsSecurity from ADSI SDK 2.5 under (/ResourceKit/ADsSecurity.dll)
'
' Get the sdk from
' http://msdownload.microsoft.com:80/msdownload/adsi/2.5/sdk/x86/en/Sdk.zip
' copy the dll to a place in your path and run
'
' RegObj.dll is included in Office 2000 SR2 or also available directly from
' MS for registered VB users.
'
' regsvr32 regobj.dll
' regsvr32 adssecurity.dll
'
' Usage with WISE for Windows Installer
' =====================================
' * add a copy of the two dlls to the package and install them somewhere
' below the INSTALLDIR of the package. Make sure you click Self register in
' the file property dialog
'
' * customize the dacl.vbs according to the needs of the application and add it
' to the msi somewhere below INSTALLDIR. Maybe next to the dlls
'
' * Add a custom action: Type: Call Exe File
' Source: File on destination machine
' Name: DACL
' InstDir: SystemFolder
' Exe Cmd: wscript.exe "[!dacl.vbs]"
' Sequenc: Install Execute Sequence (Before InstallFinalize)'
' Condition: NOT REMOVE~="ALL"
' I-S Opt: System Context
' Process: Asynch, Wait at end of sequence
'
' TODO
' ====
' Using Add with the Registry creates working results, but somehow the ACEs are
' not in the proper order, and regedt32 complains when you look at them ...
' it also seems that maybe I am not adding all the reg entries necessary ...
' lack of docu ... sorry ... help appreciated. I guess it has something todo
' with inheritance ...
'
' USAGE
' -----
'
' DACL function, url, "ace, ace, ..."
'
' function -- Add, Rm, Set
'
' url -- FILE://.... change this File/Folder
' FILE://c:\home\ change this Folder and everything below
' FILE://c:\home\\ change this Folder and Folders below
' RGY://\HKEY_LOCAL_MACHINE\SOFTWARE change this property
' RGY://...\ and RGY://\...\\ are the same as indiviual
' registry values have no acls assigned
'
' ace -- account:rights
'
' account -- user or group
'
' rights (file) -- F - Full, C - Change, R - Read + Execute,
' S - Read + Write + Execute, L - List
' K - Special Case, like 1777. Create file and work with your own only
' rights (registry) -- F - Full, R - Read
'
' EXAMPLES
' --------
' DACL "Add", "FILE://w:\hello.txt", "users:F,moetiker:F"
' DACL "Add", "FILE://w:\hello\", "users:R,oetiker:F,moetiker:F"
' DACL "Rm", "FILE://w:\oops.txt", "user" 'remove whatever is there under user
' DACL "Add", "FILE://w:\oops.txt", "user:F" ' add Full control for user
' DACL "Add", "RGY://\HKEY_CURRENT_USER\SOFTWARE\ipswitch\ws_ftp\", "users:F"
'=============================================================================
DumpAcl "FILE://C:"
DACL "Rm", "FILE://C:", "users,CREATOR OWNER"
DACL "Add", "FILE://C:", "users:R"
DACL "Add", "FILE://C:", "users:K"
DumpAcl "FILE://C:"
'=============================================================================
' Implementation
' --------------
Sub DumpAcl (url)
Dim sd, dacl, ace, sec
Print url
Set sec = Wscript.CreateObject("ADsSecurity")
Set sd = sec.GetSecurityDescriptor( CStr(url) )
Set dacl = sd.DiscretionaryAcl
For Each ace In dacl
Print " " & ace.trustee & _
" Type: " & ace.AceType & _
" Mask: " & ace.AccessMask & _
" AceFlags: " & ace.AceFlags & _
" Flags: " & ace.Flags & _
" OType: " & ace.ObjectType & _
" IOTyp: " & ace.InheritedObjectType

Next

set sec = Nothing
set sd = Nothing
set dacl = Nothing

End Sub

Sub AclEdit( action, url, acl, UType )
Dim acls, dacl, dummy, sec, sd, ace, acea, usera, user, perm, acsplit
Const ADS_ACETYPE_ACCESS_ALLOWED = 0
Const ADS_ACETYPE_ACCESS_DENIED = 1
Const ADS_ACEFLAG_INHERIT_ACE = 2
Const ADS_ACEFLAG_INHERIT_ONLY_ACE = 8
Const ADS_ACEFLAG_SUB_NEW = 9

Print "Edit: " & action & " " & url & " " & acl & " " & utype
acls = split(acl,",")

Set sec = Wscript.CreateObject("ADsSecurity")
on error resume Next

' without cstr this will break ... !!!
Set sd = sec.GetSecurityDescriptor( CStr(url) )

If ErrHandler("Get SD for " & url ) Then
On Error GoTo 0
Exit Sub
End If

Set dacl = sd.DiscretionaryAcl
dummy = dacl.AceCount ' this will throw an error if there is no DACL
If ErrHandler("Get DACL for " & url ) Then
On Error GoTo 0
Exit Sub
End If

' DumpAcl url

' If action = "Rm" Or action = "Add" Then
If action = "Rm" Then
' for Add we remove the ACEs for the folks for whoom need new ones
For Each ace In dacl
acea = split (LCase(ace.trustee & "\" & ace.trustee),"\")
If acea(0) <> "nt authority" Then
For Each user In acls
usera = split (LCase(user),":")
If acea(1) = usera(0) Then
Print "Remove ACE: " & ace.trustee
dacl.RemoveACE ace
ErrHandler("Remove ACE for " & ace.trustee & _
" from " & url)
End If
Next
End if
Next

ElseIf action = "Set" Then
For Each ace In dacl
acea = split (LCase(ace.trustee & "\" & ace.trustee),"\")
If acea(0) <> "nt authority" Then
dacl.RemoveACE ace
ErrHandler("Remove ACE for " & ace.Trustee & " from " & url)
Print "Remove ACE: " & ace.trustee
End if
Next
Elseif action <> "Add" Then
Wscript.Echo "Unknown Action: " & action
End If

If action = "Set" Or action = "Add" Then
For Each dummy In acls
acsplit = split (dummy,":")
user = acsplit(0)
perm = acsplit(1)
Print action & " " & utype & " " & user & " " & perm
Select Case UType
Case "DIRECTORY"
' folders require 2 aces for user (to do with inheritance)
AddFileAce dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED, _
ADS_ACEFLAG_SUB_NEW
if ucase(perm) <> "K" then
AddFileAce dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED, _
ADS_ACEFLAG_INHERIT_ACE
end if
case "FILE"
AddFileAce dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED,0
case "REGISTRY"
AddRegAce dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED, _
ADS_ACEFLAG_INHERIT_ACE
End Select
Next

End If


sd.DiscretionaryAcl = dacl
If ErrHandler("Get SD for " & url ) Then
On Error GoTo 0
Exit Sub
End If

sec.SetSecurityDescriptor sd

If ErrHandler("Get SD for " & url ) Then
On Error GoTo 0
Exit Sub
End If

Set sd = Nothing
Set dacl = Nothing
Set sec = Nothing

' DumpAcl url

On Error GoTo 0
End Sub

Sub AddRegACE(dacl, user, perm , acetype, aceflags)
' Add registry ACE
Dim ace

Const ADS_ACETYPE_ACCESS_ALLOWED = 0
Const RIGHT_REG_READ = &H20019
Const RIGHT_REG_FULL = &HF003F


Set ace = CreateObject("AccessControlEntry")
ace.Trustee = user

Select Case UCase(perm)
' specified rights so far only include FC & R. Could be expanded though
Case "F"
ace.AccessMask = RIGHT_REG_FULL
Case "R"
ace.AccessMask = RIGHT_REG_READ
End Select

ace.AceType = acetype
ace.AceFlags = aceflags
dacl.AddAce ace
ErrHandler("Add Ace for " & user )

set ace=Nothing

End Sub

Sub AddFileAce(dacl,user, perm, acetype, aceflags)
' add ace to the specified dacl
Dim ace

Const RIGHT_LIST = &H4
Const RIGHT_READ = &H80000000
Const RIGHT_EXECUTE = &H20000000
Const RIGHT_WRITE = &H40000000
Const RIGHT_DELETE = &H10000
Const RIGHT_FULL = 2032127 ' &H10000000
Const RIGHT_CHANGE_PERMS = &H40000
Const RIGHT_TAKE_OWNERSHIP = &H80000


Set ace = CreateObject("AccessControlEntry")
ace.Trustee = user

select case ucase(perm)
' specified rights so far only include FC & R. Could be expanded though
case "F"
ace.AccessMask = RIGHT_FULL
case "C"
ace.AccessMask = RIGHT_READ or RIGHT_WRITE Or _
RIGHT_EXECUTE or RIGHT_DELETE
case "R"
ace.AccessMask = RIGHT_READ or RIGHT_EXECUTE
case "S" 'Special
ace.AccessMask = RIGHT_READ or RIGHT_WRITE or RIGHT_EXECUTE
case "L" 'List
ace.AccessMask = RIGHT_LIST
case "K" ' User can Create and work files in the dir specified and nothing else
ace.AceType = 0
ace.AccessMask = 1048582 ' create files
ace.AceFlags = 0
dacl.AddAce ace
set ace=Nothing
Set ace = CreateObject("AccessControlEntry")
ace.Trustee = "CREATOR OWNER"
ace.AccessMask = RIGHT_FULL
acetype=0
aceflags=9
end select

ace.AceType = acetype
ace.AceFlags = aceflags
dacl.AddAce ace
ErrHandler("Add Ace for " & user )

set ace=Nothing

End Sub

Sub DACL(action,url,acl)
Dim argarry, utype, upath, walk, ftype, fs, rfldr, file, sfldr
Dim ro, rk, regval,skey
argarry = split(url,"://")
utype = argarry(0)
upath = argarry(1)

Print "Action: " & action & " " & utype & "--" & upath & " " & acl

If Right(upath,2) = "\\" Then
walk = "\\" ' folders only
upath = Left(upath, Len(upath)-2)
ElseIf Right(upath,1) = "\" Then
walk = "\" ' files and folders
upath = left(upath, len(upath)-1)
End If

If utype = "FILE" Then

Set fs=Wscript.CreateObject("Scripting.FileSystemObject")
Print "---" & upath
If fs.FileExists(upath) Then
Set rfldr=fs.GetFile(upath)
ftype = "FILE" 'directory
ElseIf fs.FolderExists(upath) Then
Set rfldr=fs.GetFolder(upath)
ftype = "DIRECTORY" 'file
Else
' its neither file nor folder ... maybe it does not exist ...
wscript.echo "Can't find " & upath
Exit Sub
End If

AclEdit action, "FILE://" & rfldr.path, acl, ftype

If ftype = "FILE" Then 'if this is a file our work is done
Exit Sub
End If

If walk = "\" then
For Each file In rfldr.files
AclEdit action, "FILE://" & file , acl, "FILE"
Next
End If

if walk = "\" or walk = "\\" then
for each sfldr in rfldr.subfolders
DACL action, "FILE://" & sfldr & walk, acl
next
end if

elseif utype = "RGY" Then

Set ro = CreateObject("RegObj.Registry")
on error resume Next
Set rk = ro.RegKeyFromString( upath )
If ErrHandler("Get Registry Key " & upath ) Then
On Error GoTo 0
Exit Sub
End If

AclEdit action, "RGY://" & rk.FullName, acl,"REGISTRY"

if walk = "\" or walk = "\\" then
for each skey in rk.Subkeys
DACL action,"RGY://" & skey.FullName & walk, acl
next
end If

else
Wscript.Echo "Unsupported URL Type: " & utype
end If
On Error GoTo 0

End Sub

Function ErrHandler(what)
If Err.Number > 0 Then
WScript.Echo what & " Error " & Err.Number & ": " & Err.Description
Err.Clear
Return True
End If
ErrHandler = False
End Function

Sub Print(Str)
'strip when debugging
'wscript.echo Str
End Sub

Monday, April 2, 2007

Set Date and Time on Solaris

date mmddhhmmyy

The date command takes the syntax mmddhhmmyy, or “month day hour minute year”. You have to be superuser to set the time.

Example:
# date 0329092207
Thu Mar 29 09:22:00 PST 2007

To set the time to 5:43:15 PM (17:43:15) :
date 1743.15

To set the time to 9:05 AM:
date 0905

Display Number of Processors on Linux

cat /proc/cpuinfo grep processor wc -l

Delete Windows Patch Install Folders

Const WINDOWS = &H24&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(WINDOWS)
Set objFolderItem = objFolder.Self
' Wscript.Echo objFolderItem.Path

Set FSO = CreateObject("Scripting.FileSystemObject")
ShowSubfolders FSO.GetFolder(objFolderItem.Path)

Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
If Right(Subfolder.Name,1) = "$" AND Left(Subfolder.Name,1) = "$" Then
' Wscript.Echo Subfolder.Name
Subfolder.Delete
End If
' Wscript.Echo Subfolder.Path
' ShowSubFolders Subfolder
Next
End Sub

Configure Computer Rights in Active Directory

'**********************************************************************
'
' Configure Computer Rights in AD
'
'**********************************************************************

'**********************************************************************
'Connecting to the default naming context
'**********************************************************************
Set oRootDSE = GetObject("LDAP://RootDSE")
strNamingContext = oRootDSE.Get("defaultNamingContext")
set oSubscription = GetObject("LDAP://"&strNamingContext)


'**********************************************************************
'Getting the security descriptor of the domain root
'**********************************************************************
on error resume next
set oSecDesc = oSubscription.Get("ntSecurityDescriptor")
set oACL = oSecDesc.DiscretionaryACL
if err.number<>0 then
wscript.echo "Error : "&error.number&" "&error.description
wscript.quit(1)
end if


'**********************************************************************
'Create a new ACE giving write access to the comment field of computer objects
'**********************************************************************
Set objACE = CreateObject("accessControlEntry")
objACE.Trustee = "Domain Computers"
objACE.AccessMask = 32
objACE.AceType = 5
objACE.AceFlags = 10
objACE.Flags = 3
objAce.ObjectType="{BF967A6A-0DE6-11D0-A285-00AA003049E2}"
objACE.InheritedObjectType="{BF967A86-0DE6-11D0-A285-00AA003049E2}"

oACL.AddAce(objACE)
oSecDesc.DiscretionaryACL = oACL


'**********************************************************************
'Write back the security descriptor
'**********************************************************************
oSubscription.Put "ntSecurityDescriptor",oSecDesc
oSubscription.SetInfo
if err.number<>0 then
wscript.echo "Error : "&error.number&" "&error.description
wscript.quit(1)
end if

Repair Image Preview in Windows 2000/XP

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.art\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.bmp\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.dib\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.gif\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.jfif\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.jpe\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.jpg\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.jpeg\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.png\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

[HKEY_CLASSES_ROOT\.wmf\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
@="{7376D660-C583-11d0-A3A5-00C04FD706EC}"

Sunday, April 1, 2007

Install WinZIP 8.0/9.0 in Silent Mode

ECHO Install WinZIP 8.0/9.0
if not exist "C:\Program Files\WinZip" md "C:\Program Files\WinZip"
echo d|xcopy /E /C /Q /H /K /O /Y "E:\Install\WinZip" "C:\Program Files\WinZip"
"C:\Program Files\WinZip\WINZIP32.EXE" /noqp /notip /autoinstall

Install .NET Framework 1.1 in Silent Mode

ECHO Install .NET Framework 1.1
L:\IE6F\dotnetfx.exe /q:a /c:"install /l /q"

Install MDAC 2.8 in Silent Mode

ECHO Install MDAC 2.8
D:\MDAC28.exe /Q:A /R:N /C:"DASETUP.EXE /Q /N"

Install Internet Explorer 6 SP1 in Silent Mode

ECHO Install Internet Explorer 6 SP1
"D:\ie6setup.exe" /Q:A /R:N /C:"ie6wzd /S:""#e"" /Q:A /R:N"

Install Windows 2000 MUI in Silent Mode

ECHO Install Windows 2000 french MUI
"E:\W2KMUIFR\MUISETUP.exe" /i 0411 0c0a 040c /d 040c /r /s

REM /i Specifies the user interface language(s) to be installed.
REM 0411 Japanese 0c0a Spanish 040c French
REM /d Specifies the default user interface language (applied to all new user accounts and used in places such as the Winlogon screen)
REM /u Specifies the user interface language(s) to be uninstalled
REM /r Specifies that the reboot message should not be displayed
REM /s Specifies that the installation complete message should not be displayed

Install Oracle 8.1.7 in Silent Mode

ECHO Install Oracle 8.1.7
"D:\install\win32\setup.exe" -responsefile "E:\clientappuser.rsp" -silent

REM SETUP.EXE -RESPONSEFILE FILENAME [-SILENT] [-NOWELCOME]
REM FILENAME = Identifies the specific response file
REM -SILENT = Runs Oracle Universal Installer in complete silent mode. The Welcome window is suppressed automatically.
REM -NOWELCOME = Suppresses the Welcome window that appears during installation

French Keyboard for All Language

Use the same Keyboard System File kbdfr.dll for all language. If you want to use US Keyboard, replace kbdfr.dll by kbdus.dll, if you use German Keyboard, replace kbdfr.dll by kbdgr.dll, etc. Thanks to M. Jacques BEGAINT for this post.



REGEDIT4

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\00000404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\00000804]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0010404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0010804]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0020404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0020804]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0030404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0030804]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0040404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0050404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0050804]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0060404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0070404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0080404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E0090404]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E00E0804]
"Layout File" = "kbdfr.dll"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\E01F0404]
"Layout File" = "kbdfr.dll"

WMI Explorer in PowerShell

# WmiExplorer.ps1
#
# A GUI WMI explorer and WMI Method Help generator
#
# /\/\o\/\/ 2006
# www.ThePowerShellGuy.com

# load Forms NameSpace

[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

#region BuildTheForm build in C# then translated to powershell

#region Make the form

$frmMain = new-object Windows.Forms.form
$frmMain.Size = new-object System.Drawing.Size @(800,600)
$frmMain.text = "/\/\o\/\/'s PowerShell WMI Explorer"

#endregion Make the form

#region Define Used Controls

$MainMenu = new-object System.Windows.Forms.MenuStrip
$statusStrip = new-object System.Windows.Forms.StatusStrip
$FileMenu = new-object System.Windows.Forms.ToolStripMenuItem
$ToolMenu = new-object System.Windows.Forms.ToolStripMenuItem('&tools')

$miQuery = new-object System.Windows.Forms.ToolStripMenuItem('&Query (run)')

$miSelectQuery = new-object System.Windows.Forms.ToolStripMenuItem('&SelectQuery')
$miSelectQuery.add_Click({$sq | out-propertyGrid;$wmiSearcher.Query = $sq})
[void]$ToolMenu.DropDownItems.Add($miSelectQuery)

$miRelatedObjectQuery = new-object System.Windows.Forms.ToolStripMenuItem('&RelatedObjectQuery')
$miRelatedObjectQuery.add_Click({$roq | out-propertyGrid;$wmiSearcher.Query = $roq})
[void]$ToolMenu.DropDownItems.Add($miRelatedObjectQuery)

$miRelationshipQuery = new-object System.Windows.Forms.ToolStripMenuItem('&RelationshipQuery')
$miRelationshipQuery.add_Click({$rq | out-propertyGrid ;$wmiSearcher.Query = $rq})
[void]$ToolMenu.DropDownItems.Add($miRelationshipQuery)

$oq = new-object System.Management.ObjectQuery
$eq = new-object System.Management.EventQuery
$sq = new-object System.Management.SelectQuery
$roq = new-object System.Management.RelatedObjectQuery
$rq = new-object System.Management.RelationshipQuery
$wmiSearcher = [wmisearcher]''
[void]$ToolMenu.DropDownItems.Add($miQuery)

$miQuery.add_Click({

$wmiSearcher | out-propertyGrid
$moc = $wmiSearcher.get()
$DT = new-object System.Data.DataTable
$DT.TableName = $lblClass.text
$Col = new-object System.Data.DataColumn
$Col.ColumnName = "WmiPath"
$DT.Columns.Add($Col)

$i = 0
$j = 0 ;$lblInstances.Text = $j; $lblInstances.Update()

$MOC |
ForEach-Object {
$j++ ;$lblInstances.Text = $j; $lblInstances.Update()
$MO = $_

# Make a DataRow

$DR = $DT.NewRow()
$Col = new-object System.Data.DataColumn
$DR.Item("WmiPath") = $mo.__PATH

$MO.psbase.properties |
ForEach-Object {

$prop = $_

If ($i -eq 0) {

# Only On First Row make The Headers

$Col = new-object System.Data.DataColumn
$Col.ColumnName = $prop.Name.ToString()

$prop.psbase.Qualifiers |
ForEach-Object {
If ($_.Name.ToLower() -eq "key") {
$Col.ColumnName = $Col.ColumnName + "*"
}
}
$DT.Columns.Add($Col)
}

# fill dataRow

if ($prop.value -eq $null) {
$DR.Item($prop.Name) = "[empty]"
} ElseIf ($prop.IsArray) {
$DR.Item($prop.Name) =[string]::Join($prop.value ,";")
} Else {
$DR.Item($prop.Name) = $prop.value
#Item is Key try again with *
trap{$DR.Item("$($prop.Name)*") = $prop.Value.tostring();continue}
}

} #end ForEach

# Add the row to the DataTable

$DT.Rows.Add($DR)
$i += 1

}

$DGInstances.DataSource = $DT.psObject.baseobject
$status.Text = "Retrieved $j Instances"
$status.BackColor = 'YellowGreen'
$statusstrip.Update()

})#$miQuery.add_Click


$miQuit = new-object System.Windows.Forms.ToolStripMenuItem('&quit')

$miQuit.add_Click({$frmMain.close()})

$SplitContainer1 = new-object System.Windows.Forms.SplitContainer
$splitContainer2 = new-object System.Windows.Forms.SplitContainer
$splitContainer3 = new-object System.Windows.Forms.SplitContainer

$grpComputer = new-object System.Windows.Forms.GroupBox
$grpNameSpaces = new-object System.Windows.Forms.GroupBox
$grpClasses = new-object System.Windows.Forms.GroupBox
$grpClass = new-object System.Windows.Forms.GroupBox
$grpInstances = new-object System.Windows.Forms.GroupBox
$grpStatus = new-object System.Windows.Forms.GroupBox

$txtComputer = new-object System.Windows.Forms.TextBox
$btnConnect = new-object System.Windows.Forms.Button
$btnInstances = new-object System.Windows.Forms.Button

$tvNameSpaces = new-object System.Windows.Forms.TreeView
$lvClasses = new-object System.Windows.Forms.ListView

$clbProperties = new-object System.Windows.Forms.CheckedListBox
$clbProperties.CheckOnClick = $true
$lbMethods = new-object System.Windows.Forms.ListBox

$label1 = new-object System.Windows.Forms.Label
$label2 = new-object System.Windows.Forms.Label
$lblServer = new-object System.Windows.Forms.Label
$lblPath = new-object System.Windows.Forms.Label
$lblNameSpace = new-object System.Windows.Forms.Label
$label6 = new-object System.Windows.Forms.Label
$lblClass = new-object System.Windows.Forms.Label
$label10 = new-object System.Windows.Forms.Label
$lblClasses = new-object System.Windows.Forms.Label
$label12 = new-object System.Windows.Forms.Label
$lblProperties = new-object System.Windows.Forms.Label
$label8 = new-object System.Windows.Forms.Label
$lblMethods = new-object System.Windows.Forms.Label
$label14 = new-object System.Windows.Forms.Label
$lblInstances = new-object System.Windows.Forms.Label
$label16 = new-object System.Windows.Forms.Label

$dgInstances = new-object System.Windows.Forms.DataGridView
$TabControl = new-object System.Windows.Forms.TabControl
$tabPage1 = new-object System.Windows.Forms.TabPage
$tabInstances = new-object System.Windows.Forms.TabPage
$rtbHelp = new-object System.Windows.Forms.RichTextBox
$tabMethods = new-object System.Windows.Forms.TabPage
$rtbMethods = new-object System.Windows.Forms.RichTextBox
#endregion Define Used Controls

#region Suspend the Layout

$splitContainer1.Panel1.SuspendLayout()
$splitContainer1.Panel2.SuspendLayout()
$splitContainer1.SuspendLayout()
$splitContainer2.Panel1.SuspendLayout()
$splitContainer2.Panel2.SuspendLayout()
$splitContainer2.SuspendLayout()
$grpComputer.SuspendLayout()
$grpNameSpaces.SuspendLayout()
$grpClasses.SuspendLayout()
$splitContainer3.Panel1.SuspendLayout()
$splitContainer3.Panel2.SuspendLayout()
$splitContainer3.SuspendLayout()
$grpClass.SuspendLayout()
$grpStatus.SuspendLayout()
$grpInstances.SuspendLayout()
$TabControl.SuspendLayout()
$tabPage1.SuspendLayout()
$tabInstances.SuspendLayout()
$FrmMain.SuspendLayout()

#endregion Suspend the Layout

#region Configure Controls

[void]$MainMenu.Items.Add($FileMenu)
[void]$MainMenu.Items.Add($ToolMenu)
$MainMenu.Location = new-object System.Drawing.Point(0, 0)
$MainMenu.Name = "MainMenu"
$MainMenu.Size = new-object System.Drawing.Size(1151, 24)
$MainMenu.TabIndex = 0
$MainMenu.Text = "Main Menu"

#
# statusStrip1
#
$statusStrip.Location = new-object System.Drawing.Point(0, 569)
$statusStrip.Name = "statusStrip"
$statusStrip.Size = new-object System.Drawing.Size(1151, 22);
$statusStrip.TabIndex = 1
$statusStrip.Text = "statusStrip"

$splitContainer1.Dock = [System.Windows.Forms.DockStyle]::Fill
$splitContainer1.Location = new-object System.Drawing.Point(0, 24)
$splitContainer1.Name = "splitContainer1"
$splitContainer1.Panel1.Controls.Add($splitContainer2)

$splitContainer1.Panel2.Controls.Add($splitContainer3)
$splitContainer1.Size = new-object System.Drawing.Size(1151, 545)
$splitContainer1.SplitterDistance = 372
$splitContainer1.TabIndex = 2

$splitContainer2.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$splitContainer2.Dock = [System.Windows.Forms.DockStyle]::Fill
$splitContainer2.Location = new-object System.Drawing.Point(0, 0)
$splitContainer2.Name = "splitContainer2"
$splitContainer2.Orientation = [System.Windows.Forms.Orientation]::Horizontal

$splitContainer2.Panel1.BackColor = [System.Drawing.SystemColors]::Control
$splitContainer2.Panel1.Controls.Add($grpNameSpaces)
$splitContainer2.Panel1.Controls.Add($btnConnect)
$splitContainer2.Panel1.Controls.Add($grpComputer)

$splitContainer2.Panel2.Controls.Add($grpClasses)
$splitContainer2.Size = new-object System.Drawing.Size(372, 545)
$splitContainer2.SplitterDistance = 302
$splitContainer2.TabIndex = 0

#
# fileMenu
#
[void]$fileMenu.DropDownItems.Add($miQuit)
$fileMenu.Name = "fileMenu"
$fileMenu.Size = new-object System.Drawing.Size(35, 20)
$fileMenu.Text = "&File"

$grpComputer.Anchor = "top, left, right"
$grpComputer.Controls.Add($txtComputer)
$grpComputer.Location = new-object System.Drawing.Point(12, 3)
$grpComputer.Name = "grpComputer"
$grpComputer.Size = new-object System.Drawing.Size(340, 57)
$grpComputer.TabIndex = 0
$grpComputer.TabStop = $false
$grpComputer.Text = "Computer"

$txtComputer.Anchor = "top, left, right"
$txtComputer.Location = new-object System.Drawing.Point(7, 20)
$txtComputer.Name = "txtComputer"
$txtComputer.Size = new-object System.Drawing.Size(244, 20)
$txtComputer.TabIndex = 0
$txtComputer.Text = "."


$btnConnect.Anchor = "top, right"
$btnConnect.Location = new-object System.Drawing.Point(269, 23);
$btnConnect.Name = "btnConnect"
$btnConnect.Size = new-object System.Drawing.Size(75, 23)
$btnConnect.TabIndex = 1
$btnConnect.Text = "Connect"
$btnConnect.UseVisualStyleBackColor = $true

#
# grpNameSpaces
#
$grpNameSpaces.Anchor = "Bottom, top, left, right"
$grpNameSpaces.Controls.Add($tvNameSpaces)
$grpNameSpaces.Location = new-object System.Drawing.Point(12, 67)
$grpNameSpaces.Name = "grpNameSpaces"
$grpNameSpaces.Size = new-object System.Drawing.Size(340, 217)
$grpNameSpaces.TabIndex = 2
$grpNameSpaces.TabStop = $false
$grpNameSpaces.Text = "NameSpaces"
#
# grpClasses
#
$grpClasses.Anchor = "Bottom, top, left, right"

$grpClasses.Controls.Add($lvClasses)
$grpClasses.Location = new-object System.Drawing.Point(12, 14)
$grpClasses.Name = "grpClasses"
$grpClasses.Size = new-object System.Drawing.Size(340, 206)
$grpClasses.TabIndex = 0
$grpClasses.TabStop = $False
$grpClasses.Text = "Classes"
#
# tvNameSpaces
#
$tvNameSpaces.Anchor = "Bottom, top, left, right"

$tvNameSpaces.Location = new-object System.Drawing.Point(7, 19)
$tvNameSpaces.Name = "tvNameSpaces"
$tvNameSpaces.Size = new-object System.Drawing.Size(325, 184)
$tvNameSpaces.TabIndex = 0
#
# tvClasses
#
$lvClasses.Anchor = "Bottom, top, left, right"

$lvClasses.Location = new-object System.Drawing.Point(7, 19)
$lvClasses.Name = "tvClasses"
$lvClasses.Size = new-object System.Drawing.Size(325, 172)
$lvClasses.TabIndex = 0
$lvClasses.UseCompatibleStateImageBehavior = $False
$lvClasses.ShowItemToolTips = $true
$lvClasses.View = 'Details'
$colName = $lvClasses.Columns.add('Name')
$colname.Width = 160
$colPath = $lvClasses.Columns.add('Description')
$colname.Width = 260
$colPath = $lvClasses.Columns.add('Path')
$colname.Width = 260
#
# splitContainer3
#
$splitContainer3.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$splitContainer3.Dock = [System.Windows.Forms.DockStyle]::Fill
$splitContainer3.Location = new-object System.Drawing.Point(0, 0)
$splitContainer3.Name = "splitContainer3"
$splitContainer3.Orientation = [System.Windows.Forms.Orientation]::Horizontal
#
# splitContainer3.Panel1
#
$splitContainer3.Panel1.Controls.Add($grpStatus)
$splitContainer3.Panel1.Controls.Add($grpClass)
#
# splitContainer3.Panel2
#
$splitContainer3.Panel2.Controls.Add($TabControl)
$splitContainer3.Size = new-object System.Drawing.Size(775, 545)
$splitContainer3.SplitterDistance = 303
$splitContainer3.TabIndex = 0
#
# grpClass
#
$grpClass.Anchor = "Bottom, top, left, right"
$grpClass.Controls.Add($lblInstances)
$grpClass.Controls.Add($label16)
$grpClass.Controls.Add($lblMethods)
$grpClass.Controls.Add($label14)
$grpClass.Controls.Add($lblProperties)
$grpClass.Controls.Add($label8)
$grpClass.Controls.Add($lblClass)
$grpClass.Controls.Add($label10)
$grpClass.Controls.Add($lbMethods)
$grpClass.Controls.Add($clbProperties)
$grpClass.Controls.Add($btnInstances)
$grpClass.Location = new-object System.Drawing.Point(17, 86)
$grpClass.Name = "grpClass"
$grpClass.Size = new-object System.Drawing.Size(744, 198)
$grpClass.TabIndex = 0
$grpClass.TabStop = $False
$grpClass.Text = "Class"

#
# btnInstances
#
$btnInstances.Anchor = "Bottom, Left"
$btnInstances.Location = new-object System.Drawing.Point(6, 169);
$btnInstances.Name = "btnInstances";
$btnInstances.Size = new-object System.Drawing.Size(96, 23);
$btnInstances.TabIndex = 0;
$btnInstances.Text = "Get Instances";
$btnInstances.UseVisualStyleBackColor = $true
#
# grpStatus
#
$grpStatus.Anchor = "Top,Left,Right"
$grpStatus.Controls.Add($lblClasses)
$grpStatus.Controls.Add($label12)
$grpStatus.Controls.Add($lblNameSpace)
$grpStatus.Controls.Add($label6)
$grpStatus.Controls.Add($lblPath)
$grpStatus.Controls.Add($lblServer)
$grpStatus.Controls.Add($label2)
$grpStatus.Controls.Add($label1)
$grpStatus.Location = new-object System.Drawing.Point(17, 3)
$grpStatus.Name = "grpStatus"
$grpStatus.Size = new-object System.Drawing.Size(744, 77)
$grpStatus.TabIndex = 1
$grpStatus.TabStop = $False
$grpStatus.Text = "Status"
#
# label1
#
$label1.AutoSize = $true
$label1.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label1.Location = new-object System.Drawing.Point(7, 20)
$label1.Name = "label1"
$label1.Size = new-object System.Drawing.Size(62, 16)
$label1.TabIndex = 0
$label1.Text = "Server :"
#
# label2
#
$label2.AutoSize = $true
$label2.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label2.Location = new-object System.Drawing.Point(7, 41)
$label2.Name = "label2"
$label2.Size = new-object System.Drawing.Size(51, 16)
$label2.TabIndex = 1
$label2.Text = "Path :"
#
# lblServer
#
$lblServer.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblServer.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblServer.Location = new-object System.Drawing.Point(75, 20)
$lblServer.Name = "lblServer"
$lblServer.Size = new-object System.Drawing.Size(144, 20)
$lblServer.TabIndex = 2
#
# lblPath
#
$lblPath.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblPath.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblPath.Location = new-object System.Drawing.Point(75, 40)
$lblPath.Name = "lblPath"
$lblPath.Size = new-object System.Drawing.Size(567, 20)
$lblPath.TabIndex = 3
#
# lblNameSpace
#
$lblNameSpace.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblNameSpace.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblNameSpace.Location = new-object System.Drawing.Point(337, 20)
$lblNameSpace.Name = "lblNameSpace"
$lblNameSpace.Size = new-object System.Drawing.Size(144, 20)
$lblNameSpace.TabIndex = 5
#
# label6
#
$label6.AutoSize = $true
$label6.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label6.Location = new-object System.Drawing.Point(229, 20)
$label6.Name = "label6"
$label6.Size = new-object System.Drawing.Size(102, 16)
$label6.TabIndex = 4
$label6.Text = "NameSpace :"
#
# lblClass
#
$lblClass.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblClass.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblClass.Location = new-object System.Drawing.Point(110, 26)
$lblClass.Name = "lblClass"
$lblClass.Size = new-object System.Drawing.Size(159, 20)
$lblClass.TabIndex = 11
#
# label10
#
$label10.AutoSize = $true
$label10.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label10.Location = new-object System.Drawing.Point(6, 26)
$label10.Name = "label10"
$label10.Size = new-object System.Drawing.Size(55, 16)
$label10.TabIndex = 10
$label10.Text = "Class :"
#
# lblClasses
#
$lblClasses.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblClasses.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblClasses.Location = new-object System.Drawing.Point(595, 21)
$lblClasses.Name = "lblClasses"
$lblClasses.Size = new-object System.Drawing.Size(47, 20)
$lblClasses.TabIndex = 9
#
# label12
#
$label12.AutoSize = $true
$label12.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label12.Location = new-object System.Drawing.Point(487, 21)
$label12.Name = "label12"
$label12.Size = new-object System.Drawing.Size(76, 16)
$label12.TabIndex = 8
$label12.Text = "Classes :"
#
# clbProperties
#
$clbProperties.Anchor = "Bottom, top,left"
$clbProperties.FormattingEnabled = $true
$clbProperties.Location = new-object System.Drawing.Point(510, 27)
$clbProperties.Name = "clbProperties"
$clbProperties.Size = new-object System.Drawing.Size(220, 160)
$clbProperties.TabIndex = 1
#
# lbMethods
#
$lbMethods.Anchor = "Bottom, top, Left"
$lbMethods.FormattingEnabled = $true
$lbMethods.Location = new-object System.Drawing.Point(280, 27)
$lbMethods.Name = "lbMethods"
$lbMethods.Size = new-object System.Drawing.Size(220, 160)
$lbMethods.TabIndex = 2
#
# lblProperties
#
$lblProperties.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblProperties.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblProperties.Location = new-object System.Drawing.Point(110, 46)
$lblProperties.Name = "lblProperties"
$lblProperties.Size = new-object System.Drawing.Size(119, 20)
$lblProperties.TabIndex = 13
#
# label8
#
$label8.AutoSize = $true
$label8.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label8.Location = new-object System.Drawing.Point(6, 46)
$label8.Name = "label8"
$label8.Size = new-object System.Drawing.Size(88, 16)
$label8.TabIndex = 12
$label8.Text = "Properties :"
#
# lblMethods
#
$lblMethods.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblMethods.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblMethods.Location = new-object System.Drawing.Point(110, 66)
$lblMethods.Name = "lblMethods"
$lblMethods.Size = new-object System.Drawing.Size(119, 20)
$lblMethods.TabIndex = 15
#
# label14
#
$label14.AutoSize = $true
$label14.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label14.Location = new-object System.Drawing.Point(6, 66)
$label14.Name = "label14"
$label14.Size = new-object System.Drawing.Size(79, 16)
$label14.TabIndex = 14
$label14.Text = "Methods :"
#
# lblInstances
#
$lblInstances.BorderStyle = [System.Windows.Forms.BorderStyle]::Fixed3D
$lblInstances.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$lblInstances.Location = new-object System.Drawing.Point(110, 86)
$lblInstances.Name = "lblInstances"
$lblInstances.Size = new-object System.Drawing.Size(119, 20)
$lblInstances.TabIndex = 17
#
# label16
#
$label16.AutoSize = $true
$label16.Font = new-object System.Drawing.Font("Microsoft Sans Serif",9.75 ,[System.Drawing.FontStyle]::Bold)
$label16.Location = new-object System.Drawing.Point(6, 86)
$label16.Name = "label16"
$label16.Size = new-object System.Drawing.Size(82, 16)
$label16.TabIndex = 16
$label16.Text = "Instances :"
#
# grpInstances
#
$grpInstances.Anchor = "Bottom, top, left, right"
$grpInstances.Controls.Add($dgInstances)
$grpInstances.Location = new-object System.Drawing.Point(17, 17)
$grpInstances.Name = "grpInstances"
$grpInstances.Size = new-object System.Drawing.Size(744, 202)
$grpInstances.TabIndex = 0
$grpInstances.TabStop = $False
$grpInstances.Text = "Instances"
#
# dgInstances
#
$dgInstances.Anchor = "Bottom, top, left, right"

$dgInstances.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::AutoSize
$dgInstances.Location = new-object System.Drawing.Point(10, 19)
$dgInstances.Name = "dgInstances"
$dgInstances.Size = new-object System.Drawing.Size(728, 167)
$dgInstances.TabIndex = 0
$dginstances.ReadOnly = $true

# TabControl
#
$TabControl.Controls.Add($tabPage1)
$TabControl.Controls.Add($tabInstances)
$TabControl.Controls.Add($tabMethods)
$TabControl.Dock = [System.Windows.Forms.DockStyle]::Fill
$TabControl.Location = new-object System.Drawing.Point(0, 0)
$TabControl.Name = "TabControl"
$TabControl.SelectedIndex = 0
$TabControl.Size = new-object System.Drawing.Size(771, 234)
$TabControl.TabIndex = 0
#
# tabPage1
#
$tabPage1.Controls.Add($rtbHelp)
$tabPage1.Location = new-object System.Drawing.Point(4, 22)
$tabPage1.Name = "tabPage1"
$tabPage1.Padding = new-object System.Windows.Forms.Padding(3)
$tabPage1.Size = new-object System.Drawing.Size(763, 208)
$tabPage1.TabIndex = 0
$tabPage1.Text = "Help"
$tabPage1.UseVisualStyleBackColor = $true
#
# tabInstances
#
$tabInstances.Controls.Add($grpInstances)
$tabInstances.Location = new-object System.Drawing.Point(4, 22)
$tabInstances.Name = "tabInstances"
$tabInstances.Padding = new-object System.Windows.Forms.Padding(3)
$tabInstances.Size = new-object System.Drawing.Size(763, 208)
$tabInstances.TabIndex = 1
$tabInstances.Text = "Instances"
$tabInstances.UseVisualStyleBackColor = $true
#
# richTextBox1
#
$rtbHelp.Dock = [System.Windows.Forms.DockStyle]::Fill
$rtbHelp.Location = new-object System.Drawing.Point(3, 3)
$rtbHelp.Name = "richTextBox1"
$rtbHelp.Size = new-object System.Drawing.Size(757, 202)
$rtbHelp.TabIndex = 0
$rtbHelp.Text = ""
#
# tabMethods
#
$tabMethods.Location = new-object System.Drawing.Point(4, 22)
$tabMethods.Name = "tabMethods"
$tabMethods.Padding = new-object System.Windows.Forms.Padding(3)
$tabMethods.Size = new-object System.Drawing.Size(763, 208)
$tabMethods.TabIndex = 2
$tabMethods.Text = "Methods"
$tabMethods.UseVisualStyleBackColor = $true


$rtbMethods.Dock = [System.Windows.Forms.DockStyle]::Fill
$rtbMethods.Font = new-object System.Drawing.Font("Lucida Console",8 )
$rtbMethods.DetectUrls = $false
$tabMethods.controls.add($rtbMethods)

#endregion Configure Controls

# Configure Main Form

#region frmMain


#
$frmMain.AutoScaleDimensions = new-object System.Drawing.SizeF(6, 13)
$frmMain.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Font
$frmMain.ClientSize = new-object System.Drawing.Size(1151, 591)
$frmMain.Controls.Add($splitContainer1)
$frmMain.Controls.Add($statusStrip)
$frmMain.Controls.Add($MainMenu)
$frmMain.MainMenuStrip = $mainMenu
$FrmMain.Name = "frmMain"
$FrmMain.Text = "/\/\o\/\/ PowerShell WMI Browser"
$mainMenu.ResumeLayout($false)
$mainMenu.PerformLayout()
$MainMenu.ResumeLayout($false)
$MainMenu.PerformLayout()
$splitContainer1.Panel1.ResumeLayout($false)
$splitContainer1.Panel2.ResumeLayout($false)
$splitContainer1.ResumeLayout($false)
$splitContainer2.Panel1.ResumeLayout($false)
$splitContainer2.Panel2.ResumeLayout($false)
$splitContainer2.ResumeLayout($false)
$grpComputer.ResumeLayout($false)
$grpComputer.PerformLayout()
$grpNameSpaces.ResumeLayout($false)
$grpClasses.ResumeLayout($false)
$splitContainer3.Panel1.ResumeLayout($false)
$splitContainer3.Panel2.ResumeLayout($false)
$splitContainer3.ResumeLayout($false)
$grpClass.ResumeLayout($false)
$grpClass.PerformLayout()
$grpStatus.ResumeLayout($false)
$grpStatus.PerformLayout()
$grpInstances.ResumeLayout($false)
$TabControl.ResumeLayout($false)
$tabPage1.ResumeLayout($false)
$tabInstances.ResumeLayout($false)
$frmMain.ResumeLayout($false)
$FrmMain.PerformLayout()

$status = new-object System.Windows.Forms.ToolStripStatusLabel
$status.BorderStyle = 'SunkenInner'
$status.BorderSides = 'All'
$status.Text = "Not Connected"
[void]$statusStrip.Items.add($status)
$slMessage = new-object System.Windows.Forms.ToolStripStatusLabel
$slMessage.BorderStyle = 'SunkenInner'
$slMessage.BorderSides = 'All'
$slMessage.Text = ""
[void]$statusStrip.Items.add($slMessage)
#endregion frmMain
#endregion

#region Helper Functions

Function out-PropertyGrid {
Param ($Object,[switch]$noBase,[Switch]$array)

$PsObject = $null
if ($object) {
$PsObject = $object
}Else{
if ($Array.IsPresent) {
$PsObject = @()
$input |ForEach-Object {$PsObject += $_}
}Else{
$input |ForEach-Object {$PsObject = $_}
}
}

if ($PsObject){
$form = new-object Windows.Forms.Form
$form.Size = new-object Drawing.Size @(600,600)
$PG = new-object Windows.Forms.PropertyGrid
$PG.Dock = 'Fill'
$form.text = "$psObject"

if ($noBase.IsPresent) {"no";
$PG.selectedobject = $psObject
}Else{
$PG.selectedobject = $psObject.PsObject.baseobject
}
$form.Controls.Add($PG)
$Form.Add_Shown({$form.Activate()})
$form.showdialog()
}

} #Function out-PropertyGrid

Function Update-Status {
$script:computer = $Script:NameSpaces.__SERVER
$txtComputer.Text = $script:computer
$lblPath.Text = $Script:NameSpaces.__PATH
$lblProperties.Text = $Script:NameSpaces.__PROPERTY_COUNT
$lblClass.Text = $Script:NameSpaces.__RELPATH
$lblServer.Text = $script:Computer
$lblnamespace.Text = $Script:NameSpaces.__NAMESPACE
} # Function Update-Status

Function Set-StatusBar ([Drawing.Color]$Color,$Text) {
$status.BackColor = $color
$status.Text = $text
$statusstrip.Update()
}

#endregion Helper Functions

#################### Main ###############################

#region Global Variables

$FontBold = new-object System.Drawing.Font("Microsoft Sans Serif",8,[Drawing.FontStyle]'Bold' )
$fontNormal = new-object System.Drawing.Font("Microsoft Sans Serif",8,[Drawing.FontStyle]'Regular')
$fontCode = new-object System.Drawing.Font("Lucida Console",8 )

# Create Script Variables for WMI Connection

$Script:ConnectionOptions = new-object System.Management.ConnectionOptions
$script:WmiConnection = new-object system.management.ManagementScope
$script:WmiClass = [wmiClass]''

# NamespaceCaching , Make HashTable to store Treeview Items

$script:nsc = @{}

# Make DataSet for secondary Cache

$Script:dsCache = new-object data.dataset

if (-not ${Global:WmiExplorer.dtClasses}){
${Global:WmiExplorer.dtClasses} = new-object data.datatable
[VOID](${Global:WmiExplorer.dtClasses}.Columns.add('Path',[string]))
[VOID](${Global:WmiExplorer.dtClasses}.Columns.add('Namespace',[string]))
[VOID](${Global:WmiExplorer.dtClasses}.Columns.add('name',[string]))
[VOID](${Global:WmiExplorer.dtClasses}.Columns.add('Description',[string]))
${Global:WmiExplorer.dtClasses}.tablename = 'Classes'
}

#endregion

#region Control Handlers

# Add Delegate Scripts to finetune the WMI Connection objects to the events of the controls

$slMessage.DoubleClickEnabled = $true
$slMessage.add_DoubleClick({$error[0] | out-PropertyGrid})
$lblNameSpace.add_DoubleClick({$script:WmiConnection | out-PropertyGrid})
$lblserver.add_DoubleClick({$Script:ConnectionOptions | out-PropertyGrid})
$lblClass.add_DoubleClick({$script:WmiClass | out-PropertyGrid})


$btnConnect.add_click({ConnectToComputer})
$TVNameSpaces.add_DoubleClick({GetClassesFromNameSpace})
$lvClasses.Add_DoubleClick({GetWmiClass})
$btnInstances.add_Click({GetWmiInstances})
$dgInstances.add_DoubleClick({OutputWmiInstance})
$lbMethods.Add_DoubleClick({GetWmiMethod})

$clbProperties.add_Click({
trap{Continue}
$DGInstances.Columns.Item(($this.SelectedItem)).visible = -not $clbProperties.GetItemChecked($this.SelectedIndex)

})

$TVNameSpaces.add_AfterSelect({

if ($this.SelectedNode.name -ne $Computer){
$lblPath.Text = "$($script:WmiConnection.path.path.replace('\root',''))\$($this.SelectedNode.Text)"
}

$lblProperties.Text = $Script:NameSpaces.__PROPERTY_COUNT
$lblServer.Text = $Script:NameSpaces.__SERVER
$lblnamespace.Text = $this.SelectedNode.Text

if ($this.SelectedNode.tag -eq "NotEnumerated") {

(new-object system.management.managementClass(
"$($script:WmiConnection.path.path.replace('\root',''))\$($this.SelectedNode.Text):__NAMESPACE")
).PSbase.getInstances() | Sort-Object $_.name |
ForEach-Object {
$TN = new-object System.Windows.Forms.TreeNode
$TN.Name = $_.name
$TN.Text = ("{0}\{1}" -f $_.__NameSpace,$_.name)
$TN.tag = "NotEnumerated"
$this.SelectedNode.Nodes.Add($TN)
}

# Set tag to show this node is already enumerated
$this.SelectedNode.tag = "Enumerated"
}

$mp = ("{0}\{1}" -f $script:WmiConnection.path.path.replace('\root','') , $this.SelectedNode.text)
$lvClasses.Items.Clear()

if($Script:nsc.Item("$mp")){ # in Namespace cache
$lvClasses.BeginUpdate()
$lvClasses.Items.AddRange(($nsc.Item( "$mp")))
$status.Text = "$mp : $($lvClasses.Items.count) Classes"
$lvClasses.EndUpdate()
$lblClasses.Text = $lvClasses.Items.count
} else {
if(${Global:WmiExplorer.dtClasses}.Select("Namespace='$mp'")){ # In DataTable Cache
$status.BackColor = 'beige'
$status.Text = "$mp : Classes in Cache, DoubleClick NameSpace to retrieve Classes"
} else {
$status.BackColor = 'LightSalmon'
$status.Text = "$mp : Classes not recieved yet, DoubleClick NameSpace to retrieve Classes"
}
}

}) # $TVNameSpaces.add_AfterSelect

#endregion

#region Processing Functions

#region ConnectToComputer
# Connect to Computer
Function ConnectToComputer {

$computer = $txtComputer.Text
Set-StatusBar 'beige' "Connecting to : $computer"

# Try to Connect to Computer

&{
trap {
Set-StatusBar 'Red' "Connecting to : $computer Failed"
$slMessage.Text = "$_.message"
Continue
}

&{
# Connect to WMI root

$script:WmiConnection.path = "\\$computer\root"
$script:WmiConnection.options = $Script:ConnectionOptions
$script:WmiConnection.Connect()

# Get Avaiable NameSpaces

$opt = new-object system.management.ObjectGetOptions
$opt.UseAmendedQualifiers = $true

$Script:NameSpaces = new-object System.Management.ManagementClass(
$script:WmiConnection,[Management.ManagementPath]'__Namespace',$opt
)

Update-Status

# Create a TreeNode for the WMI Root found

$computer = $txtComputer.Text
$TNRoot = new-object System.Windows.Forms.TreeNode("Root")
$TNRoot.Name = $Computer
$TNRoot.Text = $lblPath.Text
$TNRoot.tag = "Enumerated"

# Create NameSpaces List

$Script:NameSpaces.PSbase.getInstances() | Sort-Object $_.name |
ForEach-Object {
$TN = new-object System.Windows.Forms.TreeNode
$TN.Name = $_.name
$TN.Text = ("{0}\{1}" -f $_.__NameSpace,$_.name)
$TN.tag = "NotEnumerated"
[void]$TNRoot.Nodes.Add($TN)
}

# Add to Treeview
$tvNameSpaces.Nodes.clear()
[void]$TVNamespaces.Nodes.Add($TNRoot)

# update StatusBar

Set-StatusBar 'YellowGreen' "Connected to : $computer"

}
}

} # ConnectToComputer

#endregion

#region GetClasseFromNameSpace

# Get Classes on DoubleClick on Namespace in TreeView

Function GetClassesFromNameSpace {

if ($this.SelectedNode.name -ne $script:computer){
# Connect to WMI Namespace

$mp = ("{0}\{1}" -f $script:WmiConnection.path.path.replace('\root','') , $this.SelectedNode.text)

# Update Status

$lvClasses.BeginUpdate()
$lvClasses.Items.Clear()
$i = 0 ;$lblClasses.Text = $i; $lblclasses.Update()

if($Script:nsc.Item("$mp")){ #in Namespace Cache, so just attach to ListView again

$lvClasses.Items.AddRange(($nsc.Item( "$mp")))
# $lvClasses.Items.AddRange(([System.Windows.Forms.ListViewItem[]]($nsc.Item( "$mp") |
# where {$_.name -like 'win32_*'})))
$status.Text = "$mp : $($lvClasses.Items.count) Classes"
$i = $lvClasses.Items.count
} else { #Not In NameSpace Cache

if(${Global:WmiExplorer.dtClasses}.Select("Namespace = '$mp'")){ # In DataTable cache, so get from there

$status.Text = "loading cache from $($this.SelectedNode.name)"
$statusStrip.Update()

${Global:WmiExplorer.dtClasses}.Select("Namespace = '$mp'") |
foreach {
$i++
$LI = New-Object system.Windows.Forms.ListViewItem
$li.Name = $_.name
$li.Text = $_.name
$li.SubItems.add($_.description)
$li.SubItems.add($_.path)
$li.ToolTipText = ($_.description)
$lvClasses.Items.add($li)
$status.Text = "$mp : $($lvClasses.Items.count) Classes"
$lblClasses.Text = $lvClasses.Items.count
}

} else { # Not in any Cache , Load WMI Classes

Set-StatusBar 'Khaki' "Getting Classes from $($this.SelectedNode.name)"

$mc = new-object System.Management.ManagementClass($mp,$opt)
$eo = New-Object system.management.EnumerationOptions
$eo.EnumerateDeep = $true
$eo.UseAmendedQualifiers = $true

$Mc.psbase.GetSubclasses($eo) |
ForEach-Object {
$i++ ; if ($i%10 -eq 0){$lblClasses.Text = $i;$lblclasses.Update() }
Trap{$script:Description = "[Empty]";continue}
$script:description = $_.psbase.Qualifiers.item("description").value
${Global:WmiExplorer.dtClasses}.Rows.Add($_.__path,$mp,$_.name,$description)
$LI = New-Object system.Windows.Forms.ListViewItem
$li.Name = $_.name
$li.Text = $_.name
$li.SubItems.add($description)
$li.SubItems.add($_.__path)
$li.ToolTipText = $description
$lvClasses.Items.add($li)
}

$status.Text = "Ready, Retrieved $i Classes from $mp"

} #if(${Global:WmiExplorer.dtClasses}.Select("Namespace = '$mp'"))

$lvClasses.Sorting = 'Ascending'
$lvClasses.Sort()
$script:nsc.Add($mp,(([System.Windows.Forms.ListViewItem[]]($lvClasses.Items)).clone()))

}

$lvClasses.EndUpdate()
$this.selectedNode.BackColor = 'AliceBlue'
$lblClasses.Text = $i;$lblclasses.Update()
$status.BackColor = 'YellowGreen'
$statusStrip.Update()

} #if($Script:nsc.Item("$mp"))

} # GetClassesFromNameSpace
#endregion

#region GetWmiClass
Function GetWmiClass {

# Update Status

$status.Text = "Retrieving Class"
$status.BackColor = 'Khaki'
$statusstrip.Update()
$lblClass.Text = $this.SelectedItems |ForEach-Object {$_.name}
$lblPath.text = $this.SelectedItems |ForEach-Object {"$($_.SubItems[2].text)"}

# Add HelpText

$rtbHelp.Text = ""
$rtbHelp.selectionFont = $fontBold
$rtbHelp.appendtext("$($lblClass.Text)`n`n")
$rtbHelp.selectionFont = $fontNormal
$rtbHelp.appendtext(($this.SelectedItems |ForEach-Object {"$($_.SubItems[1].text)"}))
$rtbHelp.appendtext("`n")
$path = $lblPath.text

$opt = new-object system.management.ObjectGetOptions
$opt.UseAmendedQualifiers = $true

$script:WmiClass = new-object system.management.ManagementClass($path,$opt)

# Add Property Help

$rtbHelp.selectionFont = $fontBold
$rtbHelp.appendtext("`n$($lblClass.Text) Properties :`n`n")
$rtbHelp.selectionFont = $fontNormal

$i = 0 ;$lblProperties.Text = $i; $lblProperties.Update()
$clbproperties.Items.Clear()
$clbProperties.Items.add('WmiPath',$False)

$script:WmiClass.psbase.properties |
ForEach-Object {
$i++ ;$lblProperties.Text = $i; $lblProperties.Update()
$clbProperties.Items.add($_.name,$true)
$rtbHelp.selectionFont = $fontBold
$rtbHelp.appendtext("$($_.Name) :`n" )
&{
Trap {$rtbHelp.appendtext("[Empty]");Continue}
$rtbHelp.appendtext($_.psbase.Qualifiers["description"].value)
}
$rtbHelp.appendtext("`n`n")
} # ForEach-Object


# Create Method Help

$rtbHelp.selectionFont = $fontBold
$rtbHelp.appendtext( "$($lblClass.Text) Methods :`n`n" )

$i = 0 ;$lblMethods.Text = $i; $lblMethods.Update()
$lbmethods.Items.Clear()

$script:WmiClass.psbase.Methods |
ForEach-Object {
$i++ ;$lblMethods.Text = $i; $lblMethods.Update()
$lbMethods.Items.add($_.name)
$rtbHelp.selectionFont = $fontBold
$rtbHelp.appendtext("$($_.Name) :`n")
&{
Trap {$rtbHelp.Text += "[Empty]"}
$rtbHelp.appendtext($_.Qualifiers["description"].value)
}
$rtbHelp.appendtext("`n`n" )
} #ForEach-Object

$tabControl.SelectedTab = $tabpage1
$status.Text = "Retrieved Class"
$status.BackColor = 'YellowGreen'
$statusstrip.Update()

} # GetWmiClass

#endregion

#region GetWmiInstances

Function GetWmiInstances {

$status.Text = "Getting Instances for $($lblClass.text)"
$status.BackColor = 'Red'
$statusstrip.Update()

$tabControl.SelectedTab = $tabInstances

$MC = new-object system.management.ManagementClass $lblPath.text
$MOC = $MC.PSbase.getInstances()

#trap{"Class Not found";break}

$DT = new-object System.Data.DataTable
$DT.TableName = $lblClass.text
$Col = new-object System.Data.DataColumn
$Col.ColumnName = "WmiPath"
$DT.Columns.Add($Col)

$i = 0
$j = 0 ;$lblInstances.Text = $j; $lblInstances.Update()
$MOC | ForEach-Object {
$j++ ;$lblInstances.Text = $j; $lblInstances.Update()
$MO = $_

# Make a DataRow
$DR = $DT.NewRow()
$Col = new-object System.Data.DataColumn

$DR.Item("WmiPath") = $mo.__PATH

$MO.psbase.properties |
ForEach-Object {
$prop = $_
If ($i -eq 0) {

# Only On First Row make The Headers

$Col = new-object System.Data.DataColumn
$Col.ColumnName = $prop.Name.ToString()
$prop.psbase.Qualifiers | ForEach-Object {
If ($_.Name.ToLower() -eq "key") {
$Col.ColumnName = $Col.ColumnName + "*"
}
}
$DT.Columns.Add($Col)
}

# fill dataRow

if ($prop.value -eq $null) {
$DR.Item($prop.Name) = "[empty]"
}
ElseIf ($prop.IsArray) {
$ofs = ";"
$DR.Item($prop.Name) ="$($prop.value)"
$ofs = $null
}
Else {
$DR.Item($prop.Name) = $prop.value
#Item is Key try again with *
trap{$DR.Item("$($prop.Name)*") = $prop.Value.tostring();continue}
}

}

# Add the row to the DataTable

$DT.Rows.Add($DR)
$i += 1

}

$DGInstances.DataSource = $DT.psObject.baseobject
$DGInstances.Columns.Item('WmiPath').visible = $clbProperties.GetItemChecked(0)
$status.Text = "Retrieved $j Instances"
$status.BackColor = 'YellowGreen'
$statusstrip.Update()

} # GetWmiInstances

#endregion

#region OutputWmiInstance
Function OutputWmiInstance {
if ( $this.SelectedRows.count -eq 1 ) {
if (-not $Script:InstanceTab) {$Script:InstanceTab = new-object System.Windows.Forms.TabPage
$Script:InstanceTab.Name = 'Instance'
$Script:rtbInstance = new-object System.Windows.Forms.RichTextBox
$Script:rtbInstance.Dock = [System.Windows.Forms.DockStyle]::Fill
$Script:rtbInstance.Font = $fontCode
$Script:rtbInstance.DetectUrls = $false
$Script:InstanceTab.controls.add($Script:rtbInstance)
$TabControl.TabPages.add($Script:InstanceTab)
}

$Script:InstanceTab.Text = "Instance = $($this.SelectedRows | ForEach-Object {$_.DataboundItem.wmiPath.split(':')[1]})"
$Script:rtbInstance.Text = $this.SelectedRows |ForEach-Object {$_.DataboundItem |Format-List * | out-String -width 1000 }
$tabControl.SelectedTab = $Script:InstanceTab
}

} # OutputWmiInstance

#endregion

#region GetWmiMethod

Function GetWmiMethod {

$WMIMethod = $this.SelectedItem
$WmiClassName = $script:WmiClass.__Class

$tabControl.SelectedTab = $tabMethods
#$rtbmethods.ForeColor = 'Green'
$rtbMethods.Font = new-object System.Drawing.Font("Microsoft Sans Serif",8)
$rtbMethods.text = ""

$rtbMethods.selectionFont = $fontBold

$rtbMethods.AppendText(("{1} Method : {0} `n" -f $this.SelectedItem , $script:WmiClass.__Class))
$rtbMethods.AppendText("`n")

$rtbMethods.selectionFont = $fontBold
$rtbMethods.AppendText("OverloadDefinitions:`n")
$rtbMethods.AppendText("$($script:WmiClass.$WMIMethod.OverloadDefinitions)`n`n")

$Qualifiers=@()
$script:WmiClass.psbase.Methods[($this.SelectedItem)].Qualifiers | ForEach-Object {$qualifiers += $_.name}
#$rtbMethods.AppendText( "$qualifiers`n" )
$static = $Qualifiers -Contains "Static"

$rtbMethods.selectionFont = $fontBold
$rtbMethods.AppendText( "Static : $static`n" )

If ($static) {

$rtbMethods.AppendText( "A Static Method does not an Instance to act upon`n`n" )
$rtbMethods.AppendText("`n")

$rtbMethods.SelectionColor = 'Green'
$rtbMethods.SelectionFont = $fontCode
$rtbMethods.AppendText("# Sample Of Connecting to a WMI Class`n`n")
$rtbMethods.SelectionColor = 'Black'
$rtbMethods.SelectionFont = $fontCode

$SB = new-Object text.stringbuilder
$SB = $SB.Append('$Computer = "') ; $SB = $SB.AppendLine(".`"")
$SB = $SB.Append('$Class = "') ; $SB = $SB.AppendLine("$WmiClassName`"")
$SB = $SB.Append('$Method = "') ; $SB = $SB.AppendLine("$WmiMethod`"`n")
$SB = $SB.AppendLine('$MC = [WmiClass]"\\$Computer\' + "$($script:WmiClass.__NAMESPACE)" + ':$Class"')
#$SB = $SB.Append('$MP.Server = "') ; $SB = $SB.AppendLine("$($MP.Server)`"")
#$SB = $SB.Append('$MP.NamespacePath = "') ; $SB = $SB.AppendLine("$($script:WmiClass.__NAMESPACE)`"")
#$SB = $SB.AppendLine('$MP.ClassName = $Class')
$SB = $SB.AppendLine("`n")
#$SB = $SB.AppendLine('$MC = new-object system.management.ManagementClass($MP)')
$rtbMethods.AppendText(($sb.tostring()))
$rtbMethods.SelectionColor = 'Green'
$rtbMethods.SelectionFont = $fontCode
$rtbMethods.AppendText("# Getting information about the methods`n`n")
$rtbMethods.SelectionColor = 'Black'
$rtbMethods.SelectionFont = $fontCode
$rtbMethods.AppendText(
'$mc' + "`n" +
'$mc | Get-Member -membertype Method' + "`n" +
"`$mc.$WmiMethod"
)

} Else {

$rtbMethods.AppendText( "This is a non Static Method and needs an Instance to act upon`n`n" )
$rtbMethods.AppendText( "The Example given will use the Key Properties to Connect to a WMI Instance : `n`n" )
$rtbMethods.SelectionColor = 'Green'
$rtbMethods.SelectionFont = $fontCode
$rtbMethods.AppendText("# Example Of Connecting to an Instance`n`n")

$rtbMethods.SelectionColor = 'Black'
$rtbMethods.SelectionFont = $fontCode
$SB = new-Object text.stringbuilder
$SB = $SB.AppendLine('$Computer = "."')
$SB = $SB.Append('$Class = "') ; $SB = $SB.AppendLine("$WmiClassName.`"")
$SB = $SB.Append('$Method = "') ; $SB = $SB.AppendLine("$WMIMethod`"")
$SB = $SB.AppendLine("`n# $WmiClassName. Key Properties :")

$Filter = ""
$script:WmiClass.psbase.Properties | ForEach-Object {
$Q = @()
$_.psbase.Qualifiers | ForEach-Object {$Q += $_.name}

$key = $Q -Contains "key"
If ($key) {
$CIMType = $_.psbase.Qualifiers["Cimtype"].Value
$SB = $SB.AppendLine("`$$($_.Name) = [$CIMType]")
$Filter += "$($_.name) = `'`$$($_.name)`'"
}
}

$SB = $SB.Append("`n" + '$filter=');$SB = $SB.AppendLine("`"$filter`"")
$SB = $SB.AppendLine('$MC = get-WMIObject $class -computer $Computer -Namespace "' +
"$($script:WmiClass.__NAMESPACE)" + '" -filter $filter' + "`n")
$SB = $SB.AppendLine('# $MC = [Wmi]"\\$Computer\Root\CimV2:$Class.$filter"')
$rtbMethods.AppendText(($sb.tostring()))

}

$SB = $SB.AppendLine('$InParams = $mc.psbase.GetMethodParameters($Method)')
$SB = $SB.AppendLine("`n")

# output Method Parameter Help

$rtbMethods.selectionFont = $fontBold
$rtbMethods.AppendText("`n`n$WmiClassName. $WMIMethod Method :`n`n")

$q = $script:WmiClass.PSBase.Methods[$WMIMethod].Qualifiers | foreach {$_.name}

if ($q -contains "Description") {
$rtbMethods.AppendText(($script:WmiClass.psbase.Methods[$WMIMethod].psbase.Qualifiers["Description"].Value))
}

$rtbMethods.selectionFont = $fontBold
$rtbMethods.AppendText("`n`n$WMIMethod Parameters :`n")

# get the Parameters

$inParam = $script:WmiClass.psbase.GetMethodParameters($WmiMethod)

$HasParams = $False
if ($true) {
trap{$rtbMethods.AppendText('[None]') ;continue}

$inParam.PSBase.Properties | foreach {
$Q = $_.Qualifiers | foreach {$_.name}

# if Optional Qualifier is not present then Parameter is Mandatory
$Optional = $q -contains "Optional"

$CIMType = $_.Qualifiers["Cimtype"].Value
$rtbMethods.AppendText("`nName = $($_.Name) `nType = $CIMType `nOptional = $Optional")

# write Parameters to Example script

if ($Optional -eq $TRUE) {$SB = $SB.Append('# ')}
$SB = $SB.Append('$InParams.');$SB = $SB.Append("$($_.Name) = ");$SB = $SB.AppendLine("[$CIMType]")
if ($q -contains "Description") {$rtbMethods.AppendText($_.Qualifiers["Description"].Value)}
$HasParams = $true
}
}

# Create the Rest of the Script

$rtbMethods.selectionFont = $fontBold
$rtbMethods.AppendText("`n`nTemplate Script :`n")

# Call diferent Overload as Method has No Parameters

If ($HasParams -eq $True) {
$SB = $SB.AppendLine("`n`"Calling $WmiClassName. : $WMIMethod with Parameters :`"")
$SB = $SB.AppendLine('$inparams.PSBase.properties | select name,Value | format-Table')
$SB = $SB.AppendLine("`n" + '$R = $mc.PSBase.InvokeMethod($Method, $inParams, $Null)')
}Else{
$SB = $SB.AppendLine("`n`"Calling $WmiClassName. : $WMIMethod `"")
$SB = $SB.AppendLine("`n" + '$R = $mc.PSBase.InvokeMethod($Method,$Null)')
}

$SB = $SB.AppendLine('"Result :"')
$SB = $SB.AppendLine('$R | Format-list' + "`n`n")

# Write Header of the Sample Script :

$rtbMethods.SelectionColor = 'Green'
$rtbMethods.SelectionFont = $fontCode

$rtbMethods.AppendText(@"

# $WmiClassName. $WMIMethod-Method Template Script"
# Created by PowerShell WmiExplorer
# /\/\o\/\/ 2006
# www.ThePowerShellGuy.com
#
# Fill InParams values before Executing
# InParams that are Remarked (#) are Optional
"@

)

$rtbMethods.SelectionColor = 'Black'
#$rtbMethods.SelectionFont = $fontCode
$rtbMethods.AppendText("`n`n" + $SB)

$rtbMethods.SelectionFont = new-object System.Drawing.Font("Lucida Console",6 )
$rtbMethods.AppendText("`n`n Generated by the PowerShell WMI Explorer /\/\o\/\/ 2006" )

} # GetWmiMethod

#endregion

#endregion

# Show the Form

$FrmMain.Add_Shown({$FrmMain.Activate()})

trap {Write-Host $_ ;$status.Text = "unexpected error";$slMessage.Text = "$_.message";continue}

& {
[void]$FrmMain.showdialog()
}

# Resolve-Error $Error[0] | out-string

 
visitors since March 26 2007
©2007