Powershell basics recap parts 1-7 Scripting

Hello readers,
In this post we will create a short script in which I will combine almost all the things that we’ve learned so far. It is not a complicated script and you will see that it is pretty easy to understand.
I have written comments all over the script to make the script easier to understand but if you have any misunderstanding please leave a comment and I will respond as soon as I can.

#******************************************************************************
#Script Name : Active Directory Users
#Description – this script was created to interact with Active Directory users
#Version : 1.0
#Created by : Popescu Dan-Alexandru
#Name : ADusr
#******************************************************************************
# If you have problem running the script write the following : Set-ExecutionPolicy unrestricted
# you can have problems running scripts if your workstation is configured not to accept malicious scripts
#******************************************************************************

#Variables that are used in the script are initialised
[int]$useranswer=0 # stores user answer

#Option1 variables
[string]$path  # path to organizational unit
[string]$exportpath # export path
[string]$opt1ans # answer from option 1
[string]$selcolumn #select column answer

#This is the first welcome screen when you run the script
function Welcome_screen
{
Write-Host “`n`n`n`n`t`tW E L C O M E T O T H E”
Write-Host “`n`t`t` Active Directory script”
Write-Host “`n`t`t`t By Popescu Dan-Alexandru”
Write-Host “`n`t`t`t`tPress Enter to continue.”
Read-Host
Clear-Host
}

#this function retrieves the users from active directory, you have to write the path to the OU
Function Get_users
{
Clear-Host
Write-Host “Enter path to objects:”
Write-Host “`n NOTE”
Write-Host “`n CN: common name”
Write-Host “`n C: country”
Write-Host “`n DC: domain”
Write-Host “`n OU: organizational unit”
Write-Host “`n O: organization”
Write-Host “`n C: country”
$path=read-host

#example OU=Users,DC=popesq,DC=ro

Get-ADUser -Filter * -SearchBase $path
}

#This function displays the options that you cand choose
function Show_answers
{
Clear-Host
Write-Host “`n`nPress 1) – export ADusers into a csv or display them”
Write-Host “`n`nPress 2) – quit”
$useranswer=Read-Host “`n`n`n1/2”
if ($useranswer -eq “1”)
{
Clear-Host
Write-Host “Want to export users in a file (Y) or just display them(N) ?”
$opt1ans=Read-Host “`n`n`n(Y/N)”
if ($opt1ans -eq “Y”)
{
Write-Host “Enter path to export:”
$exportpath=read-host
Get_users |Select-Object -Property Surname,SamAccountName | Export-Csv $exportpath

#Select one or multiple fields from below and separate them with comma:”
#DistinguishedName”
#nEnabled”
#nGivenName”
#nName”
#nObjectClass”
#nObjectGUID”
#nSamAccountName”
#nSID”
#nSurname”
#nUserPrincipalName”
break
}
else
{
if ($opt1ans -eq “N”)         # if you just want to see the users without exporting
{
Get_users
}
}

}
elseif ($useranswer -eq “2”)     # if you want to exit the script
{
Clear-Host
Write-host “ `n`n Thank you the script will exit”
exit
}
else
{
Write-Host “`n`n Select an option”
}
}

#Main program
cd $pshome     #sets the powershell home directory
cd modules
Import-Module ActiveDirectory  #imports active directory module
Welcome_screen  # runs the function welcome_screen
Show_answers    #displays the answer

OK, this is our script,now I will show you this script in action:
First save the script with the name ADusr then press right click and press “Run with PowerShell”.
The welcome screen appears, press enter:

Powershell script
Then the menu is displayed select one of the two options:
Powershell script
I have pressed 1 , if you press 2 the script will exit:
Powershell script
Now enter the path where you want the .csv file to be exported as you can see i have entered C:\users.csv. Now press enter:
Powershell script
Now you have to enter the path to the organisational unit of your Active Directory domain, I have given you an example in the image.
OK, that’s it for this script, I chose this example because it’s a type of script that you can use in real life if you work in a AD environment. I hope this script is helpful to you. Have a nice day and stay tuned for more powershell tutorials.

Powershell basics part 7 – Functions

Hello everyone,
In today’s post we will talk about functions, what are they and how can influence our scripting technique. First of all what is a functions? a function is a group of code lines that is seen as one entity. A function has a name, usually a name that describes what the function is doing for better understanding, and that function can be called from any location in our scripts. In practice functions help reduce code lines that are needed to a script. In a function you can group several lines of code and then you can recall those again and again just by calling the function’s name.
Function’s syntax : functions are declared pretty easy, you just have to type function followed by the name of the function and after that, the code:
function function-name
 {
  code
 }

I made a simple example of a function that calculates the sum of two numbers:

Functions in Powershell
As you can see in the image I have declared three variables a,b and s. Variable s will contain the sum of a and b. I’ve created the function called sum and inside it I actually calculated the sum and wrote it on the screen. Then I can call the function simple by typing it’s name and the result is displayed.
Remember that a functions have to be initialised before they are called upon. In the example if I called the function before I have created it, powershell would not know what to do.
 In our example we declared the numbers first and then we did the calculations. Function can also pass arguments, I will show you what I mean:
In our example we declared a,b and s before the function. Instead we can do the following:
Powershell function
In this example the two variables a and b are passed as arguments in the function, therefore we can call the function sum with any values that we want. Functions can also be called upon by specifying the arguments values. The following example will show you what I mean:
Powershell function
Also we can use the same function without specifying the variables in the function initialisation. We can do this by using the $args[] variables. They are inbuilt and they refer to the arguments that are passed to the function. Our example can be written as:
powershell function argument
In our example we have passed two arguments to the function, $args[0] and $args[1]. We can also specify in the function what types of variables do we use by writing param and the variable types. You can see what I mean in the following example:
Param Powershell
As you can see the two variables that we use, a and b are integer. Functions can also return a value. In our example we have written the answer by typing Write-Host “The sum equals:” $s. The same thing would happen if the variable $s would be written in the end of the function:
Powershell function
If you run this code you will see that the function returns the same thing.
OK, this is all about functions, in the next tutorials we will discus more complex things. I hope you’ve enjoyed it, have a nice day.

IIS installation options

I will write all the Web Server (IIS) installation options and a short description:


Web Server – Installs the IIS Web Server. Provides support for HTML Web sites, ASP, ASP.NET and Web server extensions.

Common HTTP Features – This option installs support for html static sites as well as directory browsing, error detection and redirection
– Default Document – this option enables to specify the first page displayed when opening a web page
– Static Content – is used when static .htm, .html and images are used on the web server
– WebDAV (Distributed Authoring and Versioning Publishing – this option enables you to publish files from the web server using http
– Directory Browsing – enables the viewers to see the contents of a directory on your web server
– HTTP Errors – enables you to customize error messages
– HTTP Redirection – grants you the possibility to send a client to a specified location

Performance – uses compression mechanism to reduce the bandwidth utilization
– Static Content Compression – used to compress static content to reduce bandwidth
– Dynamic Content Compression – used to compress dynamic content

Health & Diagnostics – enables the server to monitor server behavior
– HTTP Logging – enables the server to log http activity
– Logging Tools – installs logging tools
– Request Monitor – monitors the server health as well as site and application.
– Tracing – enables tracing applications and requests
– Custom Logging – this options enables the web server to create custom logs
– ODBC Logging – enables logging for databases

Security
– Basic Authentication – enables the authentication with username and password
– Windows Authentication – enables authentication by using NTLM or Kerberos.
– Digest Authentication – enables authentication with a domain controller by sending a hash from the password
– Centralized SSL Certificate Support – simplifies management of SSL certificates by using file sharing
– Client Certificate Mapping Authentication – enables authentication with Active Directory
– IIS Client Certificate Mapping Authentication – enables one-to-one or many-to-one mappings
– URL Authorization – enables authorization rules to the url of a web-site
– Request Filtering – enables the server to create rules to block different requests
– IP and Domain Restrictions – enables the server to create rules based on ip address or domain name

Application Development – enables support for development environment like ASP, ASP.NET, .NET, CGI, ISAPI etc.
– .NET Extensibility 3.5 – enables the web server to host .NET extensions 3.5
– .NET Extensibility 4.5 – enables the web server to host .NET extensions 4.5
– Application Initialization – enables the web server to perform initialization before serving web pages
– ASP – classic ASP support
– ASP.NET 3.5 – offers web server the possibility to host ASP.NET 3.5 applications
– ASP.NET 4.5 – offers web server the possibility to host ASP.NET 4.5 applications
– CGI – enables support for CGI executables
– ISAPI Extensions – enables the isapi extensions
– ISAPI Filters – enables the isapi filters
– Server Sides Includes – enables the SSI to dynamically generate HTML pages.
– WebSocket Protocol – enables the web server to run applications that uses the WebSocket protocol.

FTP Server – enables the web server to host ftp site
– FTP Service – enables FTP publishing
– FTP Extensibility – enables FTP extensibility features

Web Server Management Tools – enables the web server management tools
– IIS Management Console – enables IIS management console
– IIS Management Scripts and Tools – enables IIS management by using scripts or command line tools
– Management Service – enables the IIS web server to be managed remotely by another machine
– IIS 6 Management Compatibility –
– IIS 6 Metabase Compatibility – enables the web server to be able to run earlier versions of IIS
– IIS 6 Management Console – enables the web server to manage remotely IIS version 6 servers
– IIS 6 Scripting Tools – enables the web server to use scripts and tools from IIS version 6 in version 7.
– IIS 6 WMI Compatibility – provides Windows Management Instrumentation to manage a IIS version 8 web-server

IIS Hostable Web Core – enables the administrators the ability to create custom code that will work in the core of the IIS

OK, this is all about the first part of our IIS tutorial. I hope you’ve liked it and if you do please leave a comment. I am opened to any suggestions so don’t hesitate to contact me. Have a nice day and stay tuned for more IIS video tutorials.

Windows Server tcp port starvation problem

Hello everyone,
In this post I want to talk about a problem that can occur if you run out of free ports to open up connections on a server. This can happen in many situations, for example if you are using a web server that hosts multiple sites or a cluster of servers that uses different services to connect to the internet, or a page that is very accessed etc.
The thing is that every service or application that runs on a server, at layer 4 in the tcp/ip stack uses a so called port number. A port is used on a device to specify a specific service or applicaiton that runs on that particular device. There are many known well ports like 80 for http, 53 for dns, 110 for pop3 etc., that are reserved for applications that run on that particular port ony. The well known ports are from 0 to 1023. The ports from 1024 to 49151 are so called registered ports and are used by companies that released software that needs to connect to the internet in order to work. An example of such software is yahoo messenger or skype. The ports from 49152 through 65535 are dynamic or private ports (also called ephemeral ports read more about them on: http://www.ncftp.com/ncftpd/doc/misc/ephemeral_ports.html ) that are used by the local server/machine to connect to the internet or to establish connections locally by different services or applications. You can find out more about ports on sites like wikipedia :
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
http://en.wikipedia.org/wiki/Ephemeral_port
The thing is that when for example you have too many tcp connections, you can find yourself in the situation where there are no free ports available. One way to see that is by looking in the event viewer on the server for the event with the id of 4227:

Windows Event Viewer

If you open that particular event you can see a short description of the problem:

Microsoft Windows Event Viewer
A good site that describes different events is http://www.eventid.net/ . On this site you can find common reasons for many problems and also in many cases what can you do to get rid of that issue.
The thing is that in many cases there are one or few events in the event viewer with the 4227 id that signals you this problem so it’s hard to identify the cause.
The resolution to this problem is to increase the tcp port pool and in many cases to decrease the TcpTimedWaitDelay. TcpTimedWaitDelay is used by machines to specify the time that must pass in order to return a specified port to the dynamic tcp port pool. More about this parameter on http://technet.microsoft.com/en-us/library/cc938217.aspx.
Enter registry editor (regedit.exe) and follow the path : HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
The default value of the TcpTimedWaitDelay is 240 seconds. Make that value smaller (it is good 60 or even 30 seconds):

 

TcpTimedWaitDelay registry
OK, after you finish this try chaging the dynamic port rage pool in the command prompt. To do this first open up a cmd.exe and type the following:
Netsh command
You can see in the bottom of the image there is an example of using this command.
Now try to restart the server in order to apply the new port pool and see if the problem has been resolved. You can find more about port starvation in the links below:
If you want to see the active tcp ports you can type the following in a cmd.exe:
netstat command
This will export active ports in numerical order (-n) with the coresponding application (-b), in a .txt file. You can find out more about netstat command by typing netstat ? in cmd:
netstat command prompt
If you have followed the steps indicated above, your problem regarding the tcp port starvation should be resolved. I hope you enjoyed this post, don’t hesitate to leave a comment, have a nice day.

Powershell basics part 6 – Loops

Hello dear readers,
Sorry for the delay, because of Christmas I couldn’t post anything. By the way Merry Christmas to everyone, I hope you’ve enjoyed the holidays. In this post we will continue our journey discovering more interesting parts of Windows Powershell. Our main focus in this post is PS loops. Loops are used in scripting and in general programming languages for processing a piece of code over and over again. If you have encountered loops again then you know how important are they when writing code. We will talk about all the loops available in PS :

While the code is executed as long as a condition is met. The code is written under this statement
Do while – the code is executed as long as a condition is met. The code is written between do and while statements.
Do until – the code is executed until a condition is met.
For – the code is executed a number of times
Foreach – the code is executed for elements in a array or a collection.
Also we will talk a little bit about break and continue statements when working with loops.

How to use while loop:
while is used when a piece of code must be executed as long as a condition is fulfilled. The syntax of while statement is the following:

while (condition)   – the condition that has to be met
{
code                      – the code that is executed, it can be a single line or multiple lines of code.
}  

An example of using the while loop:

[int]$a = 4;                  – initializing variable a with value 4
[int]$b = 8;                  – initializing variable b with value 8
while($b -ne $a)           – while variable a is not equal to variable b execute the following:
{
$b–;                            – decrements variable b value
Write-Host $b;             – writes variable b value
}

Powershell script

You can find out more about while loop by writing Get-Help about_while in PS:

While statement Powershell

How to use do while loop:
do while is used to execute a piece of code as long as a condition is met. The difference between while and do while is that while executes the code after the condition is verified while do while executes the code first then the condition is verified. The code in do while statement is written between do and while. The syntax looks something like this:

do                              – the start of do while statement
{
code                           – the code that is executed, it can be a single line or multiple lines of code.
}
 while (condition)       – the condition that has to be met

To adapt do while syntax to our exercise from above we would write the following:

[int]$a = 4;
[int]$b = 8;
do
{
$a++;                        – this time the code is first executed then the condition is tested
Write-Host $a;
}
while($a -ne $b)

While Powershell

The do until statement:
You probably wondering why we use do until if we have the do while statement. Well do until is used to execute a code until a condition is met. It executes a code while the condition is false. When the condition becomes true then the do until statements ends.

do                            – start of statement
{
code                         – code to be executed
}
until (condition)      – end of statement. the code is executed until a condition is met

In order to get the same result in our example we would type the following:

[int]$a = 4;
[int]$b = 8;
do
{
$a++;
Write-Host $a;
}
until($a -eq $b)

Do until statement Powershell

 

More about do while and do until by typing Get-Help about_do:
Do while Powershell command
The for statement:
For is used to execute a piece of code until a condition becomes true. It is used generally when working with arrays. For statement uses the so called iterator to enumerate the values of an array. You will understand the meaning of iterator when we will write an example. The for statement looks something like:
for (start; condition; step)   – for statement
{
code                                    – code to be executed
}
As you see above for has three parameters, they are all optional because if you don’t put them the loop will execute over and over again until is manually stopped. The start parameter, as I wrote refers to the first position of the iterator, the condition is the one that has to become true and the step parameter refers to the number of hops executed at each iteration.
This example will clarify the for statement:
$array=@(3,5,7,8,10)      – declaration of the array with it’s values
$n=$array.length;            – n is the length of the array. in our example n is equal to 5 because we
                                        have 5 values in the array
for($i=0;$i -le $n;$i++)    – the for statement. the iterator starts at the position of 0 in our case
                                        array[0] is value 3. the condition that has to become true is that i has to
                                        to be lower or equal to n, in our case value 5. i++ is the number of
                                        steps that the for statement takes. this could be written as $i=$i+1
{
write-host $array[$i]        – the code to be executed, in our case write the value in the $i position
}
Powershell script
More about for statement by typing Get-Help about_for:
For loop Powershell
The foreach statement:
Used to execute a piece of code for items that are part of an array. The syntax of foreach statement looks like this:
foreach (item in array)   – for each item that is part of the array
{
code                               – execute the code
}
 
An example of foreach statement:
$array=@(3,5,7,8,10)              – array declaration
foreach($i in $array)                – for each item part of array
{
$i=$i+10                                 – increment item with value 10
Write-Host $i                          – write value
}
Foreach Powershell
More about the foreach statement can you find by typing Get-Help about_foreach:
Foreach statement Powershell
Using the brake and continue statements when working with loops.
Brake is used when you want to interrupt a code that is running and to execute the next code that follows. When break is used the loop ends. For example you want to execute a code but when you get to a certain value you want the code to be interrupted. I will show you what I mean in the following example:
$array=@(3,5,7,8,10)
$n=$array.length;
foreach($i in $array)
{
$i=$i+10
   if($i -gt 15)
     { break}
Write-Host $i
}
This example is like our foreach exercise except that when $i value gets greater then 15 the code ends and powershell will jump to the next line and will write the value of $i:
Foreach statement Powershell
Continue is used almost like break statement except that powershell doesn’t end the whole loop it just terminates executing the code at that particular moment. In our next example I will show you how continue can be used:
$array=@(3,5,7,8,10)
$n=$array.length;
foreach($i in $array)
{
$i=$i+10
   if($i -eq 15)
     { continue }
Write-Host $i
}
In the code above, powershell executes the code until $i gets at the value 15. At that point PS terminates executing that particular iteration and jumps directly to the next one. The result of our example is shown in the image below:
Powershell script
OK that is all about working with loops, we have covered the basics of this section. I hope this was an interesting post, if you have any question please don’t hesitate to comment. Have a nice day and stay tuned for more tutorials.

Powershell basics part 5 – Conditional statements and operators

Hello there and welcome to our powershell training materials. Today we will continue discovering other PS features. In this post I will focus on explaining the use of if and switch statements. As we discovered in a past article, these two are part of the so called reserved powershell words.
Now let’s start by explaining the if statement. If is used when you want to test a condition and if the condition is met then execute a piece of code, else execute another piece of code. I will write down the basic statement of if:

“if (condition1) {code 1}
elseif (condition2) {code 2}
elseif (condition3) {code 3}
elseif (condition4) {code 4}
.
.
else {code n}”
As you can see in this example, the condition1 is tested in the first line, if the test result is true then the code 1 is executed. If the test result is negative then the elseif condition2 is tested. Again if the result is true then code 2 is executed, if not then condition3 is tested and so on. At the end it’s only an else statement. That corresponds with the first if, condition1. The elseif statement is not necessary to exist, it depends on what problem we need to solve. A simple test condition can look as:

“if (condition1) {code 1}
else {code 2}”
The above code states that if the condition is meet execute code 1, if not execute code 2.\
The operators can be used in if statements starting with comparison or logical operators etc. I will give you a -eq example:

[int]$a = 14;
[long]$b=23;
if ($a -eq $b) {write-host true}
else {write-host False}
Save this example in a .ps1 file then execute it. You will see that it will display the message false. This happens because the value of $a is tested to see if it’s the same value as $b and because the values are different “false” is written.

The switch statement is used to test a condition over multiple values. The way switch works is just like the statement:

“if (condition1) {code 1}
elseif (condition2) {code 2}
elseif (condition3) {code 3}
elseif (condition4) {code 4}
.
.
else {code n}”

Switch looks something like this:

switch (expression)
{
value1 {code1}
value2 {code2}
value3 {code3}
.
.
default {coden}
}

This statement can be translated something like: test expression for value 1, if the condition is met execute code1, test the condition for value2 if the condition is met execute code 2 and so on. If no condition is met then the default coden is executed.

The operators are very close with the if and switch statements because usually in such statement you use a operator. Let;s type the following:

Operators Powershell
I have written under some of the most used operators in if and switch statements. You can find more on www.google.com by typing powershell operators or by checking the Get-Help command in powershell
Operator         Description
-eq – Equal to (case insensitive)
-ieq –  Equal to (case insensitive)
-ceq –  Equal to (case sensitive)
-ne –  Not equal to (case insensitive)
-ine –  Not equal to (case insensitive)
-cne –  Not equal to (case sensitive)
-gt –  Greater than (case insensitive)
-igt –  Greater than (case insensitive)
-cgt –  Greater than (case sensitive)
-ge –  Greater than or equal to (case insensitive)
-ige –  Greater than or equal to (case insensitive)
-cge –  Greater than or equal to (case sensitive)
-lt –  Less than (case insensitive)
-ilt –  Less than (case insensitive)
-clt –  Less than (case sensitive)
-le –  Less than or equal to (case insensitive)
-ile –  Less than or equal to (case insensitive)
-cle –  Less than or equal to (case sensitive)

–not – Not logical
! – Not logical
–and –  And logical
–or  – Or logical

This is all about the if and switch statements. In the next post I will talk more about loop statements. Thank you for reading this.
Have a nice day.

Powershell basics part 4 – Variables,reserved words,special characters

Hello, thank you for reading my posts, if you read all my powershell basics parts, now you should already have some skills working with powershell. In this post we will continue the training, I will talk more about variables, strings, arrays and other useful powershell things.
Powershell has some reserved words.These are:
No 
break
elseif
if
until
continue
filter
in
where
do
foreach
return
while
else
function
switch
We can find out more about reserved words by typing Get-Help about_Reserved_Words. Here is the output of the command:

Get-Help about_Reserved_Words

These words were build with a special purpose so you cannot use them as an array, variable, function name etc. For example while was predefined to be used when you want a code to run as long as a condition is met. It is also called a loop; If was build to test a condition.

Now, let’s talk a little bit about so called escape characters. First let’s type the following in powershell Get-Help about_escape_character:

Get-Help about_escape_character
In this output we can see the list of special characters and also a short description of the purpose of special characters. To learn more about each of them we can type the following: Get_Help about_special_characters.The output of this command is:
Get_Help about_special_characters
I’m not going to describe each of the special characters because they are pretty good explained in this command.
Variables start with $ in powershell and they can be declared in several ways:

a single numeric variable : example $x=123

a collection of strings : example $x=” Hello there”  (A string is a collection of characters)\
a variable that contains specific data : example [Type of variable]$x=Value
[Type of variable] can be the following:
[int] – a 32 bit interger
[long] – a 64 bit integer
[bool] – a boolean value, it can be only true or false
[decimal] – a 128 bit decimal value
[array] – array of values
[xml] – xml object
[DateTime] – date and time
[single] / [double] – single-precision (32-bit), double-precision(64-bit)
[string] – a list o characters
[char] – 16 bit character
[byte] – 8 bit character
[hashtable] - hashtable object
some examples of these variable declaration would be : [int]$a=123;
for declaration of a boolean variable I made the following example:
Boolean variable Powershell
If you want a variable to have special characters in it’s name you have to put {}, for example ${hello!@}=”hello”

Another way to create a variable is :

New-Item variable:\x -value 12
New-Variable x -value 12
 
More about these two can be found by typing Get-Help New-Variable / Get-Help New-Item:
Get-Help New-Variable
Automatic variables are variables that store information about powershell. Type the following: Get-Help about_automatic_variables. Here is the output of the command:
Automatic variables Powershell
With variables you can do a lot of things starting from arithmetic operations, assignment comparison, logical etc. We talked about operators in a past post.
An Array is a list of values. In a array each position corresponding to an index value. An array is declared by a @ in a variable declaration. I will give you an example of array declaration:
I want to create an array that includes only numbers as follows: 1 2 3 4 5. The declaration of the array would look like this:
Powershell array
The same array can also be declared like this:
Powershell array declaration
And if you want to print just a value from the array you would type the command like this:
write-host $array3] – 3 represents the index value of the array in our example the index corresponds with the value as follows:
index value    : 0 1 2 3 4
number value : 1 2 3 4 5
So if we want to change the first value we type the following :
Powershell array declaration
More about arrays you can find out by typing Get-Help about_arrays :
Get-help about_arrays
From here we can see that you can manipulate arrays in many ways:
$array.SetValue(22,3) – this example changes the third element of the array with 22
$ary = $array[0,1,2,3 + 5..($a.length – 1)] – this example creates an array called ary that has the same elements of array exact index value of 4.
$t= 3,6,2
$s= 4,5,1
$z=$t+$s
And the value of $z is:
Powershell sumation script
Furthermore let’s type the following: $w=$z.length. This function gives variable w the number of items that z has. If we type now Write-host w$, powershell will return value 6. $w=$z.count does the same thing.
To see the available methods for a variable type the following:
Powershell sumation script
OK, that’s it for this post. In the next post we will discuss about other cool powershell features.
I hope you’ve enjoyed this, thanks a lot for reading,
Have a nice day.

Powershell basics part 3 – Piping,Alias,Cmdlets

In this post we will continue discovering Microsoft’s powershell features. We talked in a past post that Microsoft created so called alias names for commands in powershell. This thing helped a lot because sometimes it is hard to remember the whole name of a command especially if it’s a command that you do not use very often. One example is the command Get-ChildItem, the command has inbuild aliases, ls and dir. Another command is Clear-Host which has cls alias . We can do the same thing with any command in powershell by using the command Set-Alias. I will show you an example of this command. If we want the Get-Command to have an alias named getcom we would type the following Set-Alias getcom Get-Command. Now if we simply type getcom, the Get-Command will be executed by powershell. Here is the output of the command:

Get-Command powershell
OK, now let’s talk a little about piping or as you will get used to ” | ” . Piping is used to redirect the output of a command to another command for further processing. More about piping you can find out by typing Get-Help About_pipeline. Here is the output of the command:
Get-Help About_pipeline
It is hard to know all the cmdlets that exist in powershell. There are over 100 of them and to know the name of every one or what they do is very hard. I will try to write most of them and a short description of every cmdlet. Probably I will return again to read this beocause it will be very useful :). OK, now let’s type the following: Get-Command. Hmm… the output doesn’t look very good because it contains cmdlets,functions, aliases etc. If we type Get-Command  Format-list * we will get the output of the same command but also things like Modules,Parameters,Command Type etc. The output of the command looks like this:
Format-List Powershell command
Now let’s try to export the output of the Get-Command in a file but also with explanation of every command. Normally to get information about a command we would type Get-Help “command name”. For example Get-Help Get-ChildItem. If we want to get information about every command we would type Get-Command | Get-Help. This means that first powershell will execute Get-Command and the output will be send to Get-Help command. Now to export to a file type something like Get-Command | Get-Help | Out-File “path”. In my example I typed: Get-Command | Get-Help | Out-File c:\Powershell\information.txt
Now if I go to that path I should find the file named information.txt:
Out-File Powershell command
Now if you open that file you will see that every command is explained in detail:
Notepad file
If I type now Get-Help Get-Command I can see that in the output of this command is a Option called -commandType, we need only to display the cmdlets so the command that we need to type is Get-Command -commandType Cmdlet. The output is this:
Get-Command Powershell
OK, now we have the full list of the cmdlets commands but we still don’t know exactly what every command is doing. For a command, if you want to know what its purpose you just type for example Get-Help Get-Command. In our case we only want to display the name of the cmdlet and the description. This is where Format-Table cmdlet get’s in action. Let’s type Get-Help Format-Table. If you don’t remember the command you can always search for it’s alias name simply by typing Get-Alias. If you want to find more about that command type Get-Help Get-Alias. The output of Get-Alias looks like this:
Get-Alias command
For a simple way of getting to the aliases let’s export the alias names in a txt file : get-alias | Out-File c:\powershell\alias.txt
Here are the existent alias names:
 
Get-Alias Powershell
Get-Alias Cmdlet
                                  

 

The output of the Get-Help Format-Table command looks like this:

 

Format-Table Powershell
As you can see from this image that the Format-Table command is used to alter the output of a command. So in our exercise we want to extract from the output of the Get-Help command only the name and the description of the cmdlets. So now we type Get-command -commandType Cmdlet | Get-Help | Format-Table Name,Description| Out-File C:\powershell\allcmdlets.txt
This command will export in a file called allcmdlets.txt, all the cmdlets with their name and the description:
Format-Table Powershell
As you can see the file has everything we need except that powershell has truncated the description.
This happens because powershell detected that the description of the cmdlets has exceeded the maximum characters allowed by powershell. A simple solution is to put the -wrap parameter in the Format-Table. You can find more about -wrap parameter by typing Get-Help Format-Table -detailed:
Get-Help Format-Table Powershell
The parameter -wrap does the following : “Displays text that exceeds the column width on the next line. By default, text that exceeds the column width is truncated.”
Now if we return to our exercise, the whole command is the following:
Get-Command -commandType Cmdlet | Get-Help | Format-Table -wrap Name,Description| Out-File C:\powershell\allcmdlets.txt . This command is showing the whole description of each cmdlet. I think that in our case better is to have the Synopsis rather than the whole Description.
So let’s type again Get-command -commandType Cmdlet | Get-Help | Format-Table -wrap Name,Synopsis| Out-File C:\powershell\allcmdlets.txt. And finally here si the output:
Get-Help Format-Table Powershell

 

Get-Help Format-Table Powershell

 

Get-Help Format-Table Powershell

 

Powershell cmdlets

 

Powershell cmdlets list
Powershell cmdlets list

 

Powershell cmdlets list
Powershell cmdlets list
Powershell cmdlets list
Powershell commands
OK, that’s it for this post. Stay tuned because in a future post we will get deeper intro the powershell scripting. I hope this was a nice post please comment if you liked it.

Powershell basics part 2 – Customizing powershell, operators

In this post I will talk about customizing powershell enviroment and some other cool features.
First of all I will start by creating a windows powershell desktop icon:

Run as administrator
After the icon is created right click it and then click properties. In the properties window in the start in field enter the path where you want to start powershell in. I’ve created previously a folder named Powershell in drive C, so I’ve enter the path C:\Powershell. Press Apply and the OK. Now if I start powershell it will start in the path added:
Windows Powershell
Now I’ll go on top of the window, right click it and then I’ll press properties:
Powershell
In this windows you can customize powershell features like Cursor Size (Small, Medium, Large), Command History(Size, Buffers) etc. Now let’s press the font tab:
Customize Powershell
Here you can change the font options. I usually use 8×12 and Raster Fonts. Now press Layout:
Customize Powershell
In the Layout tab you can customize window size and position. Let’s go to the final tab Colors:
Customize Powershell
Here we can change the colors of different items like screen text, screen backgroud, popup text etc. After you finish press ok and the start powershell.
A nice cmmdlet is Get-History; type this and then press enter. Powershell will save the commands that you have previously used in a buffer so the commands that you’ve typed will appear here. The number that powershell memorizes is the “Buffer Size” option that you have entered in the window properties. Here is the output of the command:
Get-History command
Command Get-PSProvider is another useful cmmdlet that displays information about the specified Windows Powershell provider. Here is the output of the Get-Help Get-PSProvider:
Get-PsProvider
Now type Get-PSDrive. This command gets the windows powershell drive in the current session:
Get-PSDrive Powershell
OK now we will use the command Set-Location (you cand use also cd-change directory alias) and we will switch to the second partition. I will enter Set-Location D:
Set-Location command
Now enter Set-Location Env: and after that enter Get-ChildItem:
Set-Location Env Powershell
This is a environment that displays the variables need by the OS (operating system).
As you have probably seen in the output of Get-PSDrive command, there where also the registry containers in the output (hklm and hkcu – for the local machine and current uset). Just as if you typed regedit and entered the Registry Editor window, in powershell you can also change the registry settings. I entered Set-Location hkcu: command and then Get-ChildItem. In parallel I opened a regedit window. Here is the output:
Get-ChildItem Powershell
As you can see the output is relatively the same. OK, now if we want to start a clear powershell session we can enter the command Clear-Host ( you cand use also the alias cls).
When scripting you’ll have to know some syntax used. A script written in powershell has a .ps1 extension.
# is used to write a description or something that powershell will not read.
Write-Host, will send a message to the screen.
Read-Host, reads a line of input from the console.
Variables are written as $ followed by the variable name. You can find out more about variables by typing Get-Help about_variables.
Now let’s start a simple script. Let’s make a summation between two variables, a and b. The result we will enter in variable d. OK, let’s type the following:
Clear-Host
$a = 15
$b = 20
$d = $a + $b
write-host $d
Powershell operation
I will write now different operators that you need to know in order to work with powershell. I’ve written them from the Get-Help about_operators command:
 Arithmetic Operators
     Use arithmetic operators (+, -, *, /, %) to calculate values in a command or expression.

 

 Assignment Operators
     Use assignment operators (=, +=, -=, *=, /=, %=) to assign one or more values to variables, to change the values in a variable, and to append values to variables.
 Comparison Operators
     Use comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare values and test conditions.
Logical Operators
    Use logical operators (-and, -or, -xor, -not, !) to connect conditional statements into a single complex conditional.

 

Redirection Operators
    Use redirection operators (>, >>, 2>, 2>, and 2>&1) to send the output of a command or expression to a text file.
Split and Join Operators
    The -split and -join operators divide and combine substrings
 Type Operators
     Use the type operators (-is, -isnot, -as) to find or change the .NET Framework type of an object.

 

Unary Operators
    Use unary (++ / ) operators to increment or decrement variables or object properties and to set integers to positive or negative numbers.
Special Operators
    Use special operators to perform tasks that cannot be performed by the other types of operators. “
I will talk about special operators in a future post.

Powershell basics part 1 – Getting started with powershell

In this post I will write about basic things that you need to know in order to work with windows powershell. I’ll start by writing some simple commands and the basics in order to interact with PS. We will do more complex stuff in a later post.
When you start powershell it will start in the default directory and it will be something like “PS C:\users\your-username\”. From here you you type Get-Childitem you will see the contents of the directory. Same thing appends if you write ls or dir. Microsoft build powershell in a way that both Microsoft and Linux users can operate with it because some commands from Linux were added to powershell.Below are the three commands:

Get-ChildItem command
From these three commands you have to understand that Get-Childitem is the cmdlet and ls and dir are the alias names of the cmdlet. It is easier to remember a shor name like dir than the whole cmdlet. Microsoft has build in powershell over 100 cmdlets and the majority of them have at least one alias.
If you type Get-Command, powershell will return a list with cmdlets, functions and aliases. For example if you can’t remember exactly a function’s name you can write Get-Command to look for that particular function.The commands are not key sensitive. Another useful thing is the “TAB” key. If you only remembered a portion of a cmdlet you can type that portion and by pressing “TAB” key powershell will try to auto-complete your cmdlet name. For example if you type Get-C and then press the tab key powershell will write Get-ChildItem. Pressing again tab key powershell will display the next cmdlet in alphabetical order (in this case Get-Cluster).
Now type Get-Command *.msc. Powershell will display all the applications that have the .msc extension
Get-command Powershell
If you type Get-Command *.exe it will display applications that have de .exe extension:
Get-command Powershell
Ok now let’s start with some other commands. If you have for example a problem with some processes that run on you computer or you need to find some information about one process, in powershell you can use the function Get-Process. Ok now let’s type this function in powershell:
Get-Process Powershell
In this output you can see a part of the processes that run on my computer.
Another useful cmdlet is Get-Help. You can use this cmdlet to display other cmdlets information. Now if I type Get-Help Get-Process powershell will display the following:
Get-help command
Now I see that outlook runs on my computer so I just want to select this process so I will type Get-Process -ProcessName outlook:
Get-Process Powershell
The same thing happens when you type Get-Process outlook because the -ProcessName is the first parameter in Get-Process function. The Get-Process o* will display all the processes that start with o:
Get-process command
If I write Get-Process *o powershell will return processes that end with o and if I enter Get-Process *o* it will return processes that contain the letter o inside.
Get-process command
In the next powershell tutorial I will continue with some basic things and later I will try to do some scripting.