Archive

Archive for the ‘Scripting Snippets’ Category

VB WMI Query Computer Attributes

August 2nd, 2009 No comments

By using a VB scripts we can perform a WMI (Windows Management Instrumentation) connection to a host to execute a query against.

Below is an example of a WMI query connecting to the host named “computer”, once connected will loop around each drive letter which is a hard drive displaying the drive letter and total disk space in GB

On Error Resume Next
Const HARD_DISK = 3

Set objWMIService = GetObject(“winmgmts:” & “{impersonationLevel=impersonate}!\\” & “computer” & “\root\cimv2″)

if Err.Number = 0 then
‘ Add WMI Query Script in here!

Set colDisks = objWMIService.ExecQuery (“Select * from Win32_LogicalDisk Where DriveType = ” & HARD_DISK & “”)
For Each objDisk in colDisks

Wscript.Echo objDisk.DeviceID + ” Disk Size (GB): ” + CStr(Round((((objDisk.Size / 1024)/1024)/1024),1))

Next

else
Wscript.echo “Could not connect to ” & “computer” & ” error ” & Err.Number
End If

Err.Clear

The above WMI query can be combined with an Active Directory query to make the script more versatile (further information is here), an example of this script is below:

On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
Const HARD_DISK = 3

Set objConnection = CreateObject(“ADODB.Connection”)
Set objCommand =   CreateObject(“ADODB.Command”)
objConnection.Provider = “ADsDSOObject”
objConnection.Open “Active Directory Provider”

Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = “Select Name from ‘LDAP://OU=MyServers,DC=Domain,DC=co,DC=uk’ ” & “Where objectClass=’computer’”
objCommand.Properties(”Page Size”) = 1000
objCommand.Properties(”Searchscope”) = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
Wscript.Echo “Computer Name: ” & objRecordSet.Fields(“Name”).Value

Set objWMIService = GetObject(“winmgmts:” & “{impersonationLevel=impersonate}!\\” & objRecordSet.Fields(“Name”).Value & “\root\cimv2″)

if Err.Number = 0 then

‘ Add WMI Query Script in here!

else
Wscript.echo “Could not connect to ” & objRecordSet.Fields(“Name”).Value & ” error ” & Err.Number
End If

Err.Clear
objRecordSet.MoveNext
Loop

A number of WMI queries used can be found in the reference page WMI_Queries

VB Query Active Directory Objects

June 13th, 2009 No comments

In an Active Directory environment there is often a requirement to query objects within the AD  database, either returning selected attribute values or using this information to for further queries.

The same principles apply across any object type, the script below connects via LDAP, performs a query and returns selected values from Active Directory.

The below script will query all objects in the OU MyServers and subtree, in the domain Domain.co.uk, of type computer, returning the attributes Name and Location.

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject(”ADODB.Connection”)
Set objCommand = CreateObject(”ADODB.Command”)
objConnection.Provider = “ADsDSOObject”
objConnection.Open “Active Directory Provider”

Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = “Select Name, Location from ‘LDAP://OU=MyServers,DC=Domain,DC=co,DC=uk’ ” & “Where objectClass=’computer’”
objCommand.Properties(”Page Size”) = 1000
objCommand.Properties(”Searchscope”) = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF

‘ Insert Operators here
objRecordSet.MoveNext

Loop

Once the query has been run the results can then be used for any requirement, a simple example below is to display  the name of the computer followed by the Location attribute stored in AD.

……
Do Until objRecordSet.EOF

‘ Insert Operators here
Wscript.Echo “Computer Name: ” & objRecordSet.Fields(”Name”).Value
Wscript.Echo “Location: ” & objRecordSet.Fields(”Location”).Value

objRecordSet.MoveNext
Loop

Any attribute of the object can be displayed as long as it was requested in the initial query; Select Name, Location from…. , attribute names are LDAP attributes rather than field names seen in the Active Directory Users and Computers mmc. A list of attributes can be found here; Active Directory LDAP Attributes

One way to enhance this script further is for each computer selected perform a WMI query against it; VB WMI Query

AD Command Line Queries

February 16th, 2009 1 comment

There are a number of ways to query the Active Directory database to export objects and there attributes. One of the most common groups of tools are provided by Microsoft; dsget and dsquery.

Query Group Members

To display the member of a specific group use the dsget group command

dsget group “CN=My Group,OU=Domain Groups,DC=Domain,DC=co,DC=uk” -members

The above command will list the UPN of the users in My Group, if more information is required from each of the users within My Group the output can be piped into another dsget command

To display the member of a specific group use the dsget group command

dsget group “CN=My Group,OU=Domain Groups,DC=Domain,DC=co,DC=uk” -members | dsget user -upn -display -disabled -acctexpires

This commnd above will list the users in the group My Group with there UPN, display name, if the account is disabled and when the account expires.

Batch File – For Loop

February 9th, 2009 No comments

I will commonly write small batch files to automate tasks that are repetitive, due to this I find myself using the for loop a lot. Below are a few examples of when and where the for loop can be used effectively.

Looping through entries in a file

This example will take a standard text file (MyTextFile.txt) and then loop through all lines until the end of the file is reached. For each of the lines the first word (represented by %%A) will be printed out to the screen and ping’ed.

FOR /F “tokens=1″ %%A IN (C:\MyTextFile.txt) DO (

echo %%A

ping %%A

)

An example of the text file is simply:

COMPUTER01
COMPUTER02
COMPUTER03
COMPUTER04

By changing the tokens value, which word on a line that is used will change. By setting the value of tokens from 1 to 1,2 both the first and second words per line will be available via the parameters %%A and %%B. When using the following input file, within the loop %%A will be the computer name and %%B will be the IP address.

COMPUTER01 192.168.1.100
COMPUTER02 192.168.1.101
COMPUTER03 192.168.1.102

To ignore selected lines, i.e. lines that are actually comments use the eol parameter, the following for loop will ignore all lines that start with a colon:

FOR /F “tokens=1 eol=:” %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

If the input file has a number of header lines that should not be included the skip parameter should be used, for following will exclude the first 3 files of the input file:

FOR /F “tokens=1 eol=: skip=3″ %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

To override the default delimiters (space and tab) the delims parameter should be used. The following will ignore the space delimiter and instead delimiter by comma:

FOR /F “tokens=1 delims=,” %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

PHP – Advanced

February 8th, 2009 No comments

This article will guide you through some of the more complex features of PHP. a more basic introduction article is also available.

User Data

When browsing the internet you will come across some websites that store information about you or your visits to the site. There are two main methods of storing this data, these are through Cookies and Sessions.

Cookies

Cookies are the older of the two methods, it consists of a client side file that the browser writes to. With PHP you can create new cookies and also retrieve existing values, examples of both are below

To create new cookies the setcookie function is used, the main parameters are:

  • Name – The Name of the cookie
  • Value – Data that the cookie is to store
  • Expire – Time & Date when the cookie will expire

When creating cookies in PHP you must call the setcookie function before any HTML tags are used in the page, an example is shown below:

<?PHP
setcookie(“yeltuor”, “MyValue”, time()+86400);
?>
<HTML>
<BODY>
The cookie named yeltuor has been ’set’
It will expire 24 Hours (86400 seconds) from now.
</BODY>
</HTML>

With the cookie now created, the next stage is to read back the values stored in it. The values in the cookie can be called in the same way variables are:

<HTML>
<BODY>
<?PHP
//Check whether the cookie named yeltuor is set
if (isset($_COOKIE["yeltuor"]))
echo “Welcome back ” . $_COOKIE["yeltuor"] . “<br>”;
else
echo “Welcome newbe <br>”;
?>
</BODY>
</HTML>

Sessions

A Sessions is a server side file that is written to, again PHP support the creation and retrieval of session data. When a session is created a unique session ID is used to reference it, this is all taken care within the underlying PHP code.

The advantage of using sessions is that the user can’t view or edit the data within them; unlike the client side cookie’s. Before using sessions on a PHP page, the session_start(); function must be called, after this a session can be created, however like the cookie functions all session calls must be done before any HTML code on the page:

Below is an example of setting up a server side session:

<?PHP
//start session
session_start();
//if session variable total doesn’t exist create one
if(!isset($_SESSION['total']))
$_SESSION['total'] = ‘0′;
?>
<HTML>
<BODY>
The session variable total set to 0, unless it already existed.
</BODY>
</HTML>

To reference existing session variables and dispose of variables that are no longer required, the following code can be used:

<?PHP
//start session
session_start();
?>
<HTML>
<BODY>
<?PHP
echo “The total is ” . $_SESSION['total'];
//Finished with session variable, disposing of it
unset($_SESSION['total']);
?>
</BODY>
</HTML>

For the security minded individuals, a list of more advanced session functions that are available can be seen here.

Files

PHP supports various file related operations, some examples are below:

Opening a file is done with the fopen( ); function, the first parameter is the filename, the second is the mode to open the file in:

Mode Description
r Read Only, pointer at the beginning of the file
r+ Read and Write, pointer at the beginning of the file
w Write Only, existing file will be truncated or new file will be created.
w+ Write and Read, existing file will be truncated or new file will be created.
a Write Only, Places pointer at end of the file or new file will be created.
a+ Write and Read, Places pointer at end of the file or new file will be created.
x Write Only, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.
x Write and Read, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.

Some examples of using the fopen( ) function are below:

<HTML>
<BODY>
<?PHP
//Open file hello.txt, in the case of an error exit
$f=fopen(“hello.txt”,”r”) or exit(“Cant open file”);
//if reached the end of the file
if (feof($f))
echo “End of file”;
//Loop through file 1 char at a time, echo value
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
//Close file handle when finished
fclose($f) ;
?>
</BODY>
</HTML>

This function below accepts a parameter of a filename and location and returns the file data as a variable called contents:

function fileContents($filename){
// get contents of a file into a string
$f = fopen($filename, “r”);
$contents = fread($f, filesize($filename)) ;
fclose ($f);
return $contents;
}

Functions

Functions are used in the same way that procedures are used in other programming languages, they are used to aid with the re-use of code. examples of using functions can be seen below:

<HTML>
<BODY>
<?PHP
function echoHelloWorld($name)
{
echo “Hello World my name is ” . $name;
}
//Using the created function
echoHelloworld(“Borris”)
?>
</BODY>
</HTML>

Functions can also return values as an output by the return command from within the function.

<HTML>
<BODY>
<?PHP
function addnum($num1,$num2)
{
$tot = $num1 + $num2;
return $tot;
}
//Using the function addnum
echo “1 + 2 = ” . addNum(1,2);
?>
</BODY>
</HTML>

Require

The require function works in the same way as a function, except that it is used to call another file which is inserted into the current page. This is useful when a header is being used;

<HTML>
<BODY>
<?PHP
require(“header.php”)
?>
<h3>More text here.</h3>
</BODY>
</HTML>

Email

PHP has built in email support by using the mail() function, it requires the usual email parameters;

Parameter Description
to The recipients address in the form of abc@xyz.com
subject Subject of the email
message Content of the email; use the \n command for a new line
headers An optional parameter which may contain and Cc’s of Bcc’s
parameters Additional parameters that the sendmail program accepts i.e. From

An example of the code for a mail function with error checking is shown below, to send emails to multiple recipients, a comma: , should be used as a delimiter.

<HTML>
<BODY>
<?PHP
$to = “bob@email.com”;
$subject = “Test email”;
$message = “Hello! World \n this is a test email”;
$from = “tom@email.com”;
$headers = “From: $from”;
if (mail($to,$subject,$message,$headers))
echo “Mail Sent sucessfully”;
else
echo “Failed to Send Mail”;
?>
</BODY>
</HTML>

This is very basic example of using emailing, however for a more complete guide to PHP emailing please see PHP Mail article.

PHP – Basic

February 8th, 2009 No comments

PHP is a server-side scripting language which allow for the creation dynamic and interactive webpages, standing for PHP: Hypertext Preprocessor

It is the widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP. PHP is perfectly suited for Web development and can be embedded directly into the HTML code of a page.

PHP is often used together with the Apache web server on various operating systems. It also supports ISAPI and can be used with Microsoft’s IIS on Windows.

This article will go through some useful PHP syntax and uses.

Basic Syntax

Basic Syntax included in a PHP page and how in integrates with HTML

A piece of PHP code will always start with the tag <?php and end with ?>

Using the echo ” ” ; tag displays standard HTML that the browser will display. To echo multiple strings of variables (explained later) use a dot . <HTML> <BODY> <?php echo “<h1> Hello World </h1>”; echo “Hello” . “World”; ?> </BODY> </HTML>

Comments

Adding comments in PHP is just as important as any other programming language. within PHP there are two different methods for adding comments, through the // syntax for a single line, or to add a block of comment use /* to start, and */ to finish the block

<HTML>
<BODY>
<?php
//Single Comment
/*
Start of comment block
Still commenting
*/
?>
</BODY>
</HTML>

Variables

Variables are not typed in PHP, when referencing variables in PHP they just start with the $ symbol.

The snippet of code assigns a variable, then uses the echo command to output its value

<HTML>
<BODY>
<?php
$var1=”Hello World”;
echo $var1;
?>
</BODY>
</HTML>

Operators

PHP has the several standard operators which can be used, see table below

PHP Operators
Operator Action
+ Add
- Subtract
* Multiply
/ Divide
% Modulus
++ Increment
Decrement
= Equals
== Is equal to
!= Is NOT equal to
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
&& and
|| or
! not

Conditional Statements

Conditional statements help make PHP a dynamic language, being able to put if statements into webpages allows for the generation of dynamic HTML. The common statements are described below:

If statement

The most common statement, the syntax for this is shown below

<HTML>
<BODY>
<?php
if ($x==$y)
echo $x . ” does equal ” . $y;
elseif ($x < $y)
echo $x . ” is less than ” . $y;
else
echo $x . ” does not equal ” . $y;
?>
</BODY>
</HTML>

Looping Statements

Loops are used to save repetition of code, instead a piece of code is used once and told to be repeated a number of times, or until a condition is met.

While statement

The While statement should be used when the number of iterations is unknown, the syntax is shown below

<HTML>
<BODY>
<?php
while ($x != $y)
{
$x++;
echo “X is ” . $x;
}
?>
</BODY>
</HTML>

The other method of writing a While loop is the dowhile loop. In this example the code is always run once before the do statement is reached.

<HTML>
<BODY>
<?php
do
{
$x–;
echo “X is ” . $x;
}
while ($x > 15);
?>
</BODY>
</HTML>

For Loop

This statement is used when the number of repetitions required is known.

<HTML>
<BODY>
<?php
for ($i=1; $i<=5; $i++)
{
echo “i is ” . $i;
}
?>
</BODY>
</HTML>

Foreach Loop

This is very similar to the For Loop above, however in this case the loop is done through an array which is passed into the loop.

<HTML>
<BODY>
<?php
$arr1=array(“dayone”, “daytwo”, “daythree”);
foreach ($arr1 as $value)
{
echo “Value is ” . $value;
}
?>
</BODY>
</HTML>

Arrays

Arrays are very useful data types which are commonly under used. an array can consist of any type of data that is required, is provides a better way of storing the data and opens up easier ways of using the data when in this format.

There are three different types of array:

  • Numeric Arrays – array where there is a number that references the position in the array when being accessed
  • Associative arrays – array where values are used to reference the location within the array
  • Multidimensional arrays – Simply an array with has more than one array within it

Numeric Array

Two different methods of creating these types of arrays, both yield the same result

<HTML>
<BODY>
<?php
$arr1=array(“dayone”, “daytwo”, “daythree”);

$arr2[0]=vaule1;
$arr2[1]=vaule2;
$arr2[2]=vaule3;

//Referencing the array is done the same way
echo $arr1[0];
echo $arr2[1];
?>
</BODY>
</HTML>

Associative Array

This array type does not use standard numbering that numeric array does (0, 1, 2, 3…), here the array entries are referenced by user defined values. Again there are two different ways of creating this array type.

<HTML>
<BODY>
<?php
$arr1=array(“dayone”=>28, “daytwo”=>25, “daythree”=>20);

$arr2['monday']= “11″;
$arr2['tuesday']=”12″;
$arr2['wednesday']=”13″;

//Referencing the array is done the same way
echo $arr1['dayone'];
echo $arr2['tuesday'];
?>
</BODY>
</HTML>

Multidimensional Array

The Multidimensional array is the most complicated of them all, when implemented a grid like array is formed. When implementing a multidimensional array the sub array of each array item does not have to be the same size, as shown below.

<HTML>
<BODY>
<?php
$streets = array(
“Highstreet”=>array(
“No1″,
“No5″,
“No10″,
),
“MiddleStreet”=>array(
“No100″
),
“LowStreet”=>array(
“No33″,
“No34″,
“No35″
)
);
?>
</BODY>
</HTML>

Forms

With the use of HTML forms and PHP, information can be passed between pages easily through using the different methods available.

A basic HTML form looks like the following:

<HTML>
<BODY>
<FORM action=”page2.php” method=”POST”>
Enter value1: <input type=”text” name=”value1″ />
Enter value2: <input type=”text” name=”value2″ />
<input type=”submit” />
</FORM>
</BODY>
</HTML>

Once submitted to page2.php the values can be shown with the following code:

<HTML>
<BODY>
Hello World<br>
<?php echo $_POST["value1"]; ?><br>
<?php echo $_POST["value2"]; ?>
</BODY>
</HTML>

The syntax $_POST changes to $_GET depending on the form method. The final piece of syntax is $_REQUEST, this contains values for $_GET, $_POST and $_COOKIE (discussed later)

Form Get method displays the data transferred between pages in the address bar, the advantage of this is the new page can be book-marked and each time opened the same data will appear. The disadvantage the limit of 100 characters per variable.

Form Post method does not display the data transferred between pages in the address bar, instead the data is piped directly between pages. in this case the new page can’t be book-marked successfully, however the variable size limit is not enforced.
Many thanks to the tutorials where this information came from, W3Schools & PHP