top of page

Powershell and VMs

  • Writer: mohdmyyusuf
    mohdmyyusuf
  • Dec 27, 2021
  • 7 min read

Updated: Dec 28, 2021

The Powershell is used for system administration so it is a command line shell or scripting language. For different operating systems, different scripting languages have been designed eg bash scripting in Linux. Windows Powershell is build on .Net framework and it is used to automate the windows operations.


* A shell is a user interface that gives you access to the operating system.

* An Alias is another name for a command that points to the real command that PowerShell recognizes.


Help System:

It is a secret to become a powershell expert. cmdlets are unique to powershell, cmdlets take the form of verb-noun means its a combination of a verb and a noun like export-csv. Here we can see "export" is a verb and "csv" is a noun. So the combination of a verb and noun forms a cmdlet. To examine the help center we can go with the options like- examples, detailed, full and online. These are the options which are used to see how a particular cmdlet is used. For example suppose we want to see the details of cmdlet "Get-command", and we type the following command:

PS C:\Users\MY> Get-Help Get-Command -Online

It will open up the details of the command in the default browser if system is connected to internet. Similarly other options also work and display the details of the cmdlet.


We can see the details of any command using the regular expressions. Type the command "PS C:\Users\MY> Get-Help *process*", it will list out all the commands containing the "process" in their name. Same way we can implement the regular expressions in different formats like "Get-help *a", it will list out all the cmdlets with the name starting with letter 'a'. There are different other ways to see the details of the cmdlets. If the user wants to open the detail of any command in a new window, type the following command:

PS C:\Users\MO20264186> Get-Help Get-Service -ShowWindow

The command will open a new window with all details of the command or cmdlet. We can customize the view in the window by removing the selection of different options, the window will show the content for which the checkboxes are checked.


There is a specific syntaxt which is used to write the instructions for windows and these instructions are called cmdlets. Powershell provides the complete environment to write the code including functions and other programming constructs.


Powershell can be run in two modes, Normal mode and Administrator mode. In normal mode, you don't have rights to run all commands and in Administrator mode user is having access to all commands.


Intelligent Scripting Environment: When we search the Windows Powershell in the searchbar, there are two flavours available one is Windows Powershell and another is Windows Powershell ISE. ISE contains the Modulewise commands, editors and CLI.


Common Commands

  1. ipconfig: This is the command to check the Windows IP Configuration

  2. dir: to enlist all directories.

  3. $PSVersionTable

dir | get-members

cls


To create a new folder at any location we use the following command:

New-Item -Path 'D:\PS\Test Folder' -ItemType Directory

Explanation: The command is New-Item and the attribute -Path is to give the path where to create a new folder. The value of the attribite -ItemType should be "Directory".


New-Item cmdlet is used to create another type of files in the folder like txt file or of another extension. The command is as follows:

New-Item -Path 'D:\PS\Test Folder\Test File.txt' -ItemType File

This command will create a new file "Test File.txt", the value of the attribite -ItemType should be "File".


Copy-Item: This is a cmdlet which is used to copy an item from a source to destination. The command is as follows:

Copy-Item 'D:\PS\Test Folder' -Destination 'D:\Test Folder

The Tes Folder will be created in D:


Type the following command in PowerShell ISE Console


To create a variable in powershell add $ with the name like $a = 10. We have assigned the value 10 to variable 'a' here. If you want to print the variable just type the

variable name with $ in the command and it will be printed on console. See different operations below:

PS C:\Users\MY> 1+2                                                                                             3
PS C:\Users\MY> $a = 1+2 //here we have assigned the value 3 to variable a.
PS C:\Users\MY> $a //printed the variable.
3
PS C:\Users\MY> $a = "My name is khan and I am not a terrorist" //value is changed to a string value.
PS C:\Users\MY> $a //printed the variable
My name is khan and I am not a terrorist
PS C:\Users\MY> $a.Length //calling the string function to find its length.
40
PS C:\Users\MY> $b ='inf: $a'
PS C:\Users\MY> $b
inf: $a
PS C:\Users\MY> $b ="inf: $a"
PS C:\Users\MY> $b
inf: My name is khan and I am not a terrorist

Comparison operators:


To compare the variables in powershell we use the comparison operators as follows:
PS C:\Users\MY> $x = 5
PS C:\Users\MY> $y = 6
PS C:\Users\MY> $x -gt$y //checks if x is greater than y
False
PS C:\Users\MY> $x -lt$y //checks if x is less than y
True
PS C:\Users\MY> $x -eq$y  //checks if x is equal to y
False
PS C:\Users\MY> $x -ne$y  //checks if x is not equal to y
True
PS C:\Users\MY> 'a'-eq 'A'
True
PS C:\Users\MY> 'a'-ceq 'A'
False
PS C:\Users\MY> 'a'-ceq 'a'
True
PS C:\Users\MY> 'a'-ceq "a"
True
PS C:\Users\MY> "Mango" -like"M"
False
PS C:\Users\MY> "Mango" -like"M*"
True
PS C:\Users\MY> "Mango is the king of fruits" -like"M*"
True
PS C:\Users\MY> "Mango is the king of fruits" -match"king"
True
PS C:\Users\MY>

To see the details of any command just type <help commandName> it will display all related informations. Let's take an example, we will create an alias and then will print the

details of it.

PS C:\Users\MY> write-host "hello world" hello world

PS C:\Users\MY> get-alias dir // we are checking the information of dir ie what it does and which command it called by it.

CommandType Name Version Source

----------- ---- ------- ------

Alias dir -> Get-ChildItem


PS C:\Users\MY> get-alias ls

CommandType Name Version Source

----------- ---- ------- ------

Alias ls -> Get-ChildItem



We can set the alias for a given command, here we will set "my" as alias for command "Get-ChildItem". See the process below:

PS C:\Users\MY> set-alias

cmdlet Set-Alias at command pipeline position 1

Supply values for the following parameters:

Name: my

Value: Get-ChildItem

PS C:\Users\MY> my //now let's check if alias is working as expected.


Directory: C:\Users\MY

Mode LastWriteTime Length Name

---- ------------- ------ ----

d-r--- 29-10-2021 15:54 3D Objects

d-r--- 29-10-2021 15:54 Contacts

d-r--- 10-11-2021 12:27 Desktop

d-r--- 29-10-2021 15:54 Documents

d-r--- 10-11-2021 11:15 Downloads

d-r--- 29-10-2021 15:54 Favorites

d-r--- 29-10-2021 15:54 Links

d----- 29-10-2021 15:54 mcafee dlp quarantined files

d-r--- 29-10-2021 15:54 Music

d-r--- 29-10-2021 16:05 OneDrive

d-r--- 29-10-2021 16:05 Pictures

d-r--- 29-10-2021 15:54 Saved Games

d-r--- 29-10-2021 16:01 Searches

d-r--- 01-11-2021 10:20 Videos


The same way we can set the alias in one line command and it will get executed at the same time. See the command below:

PS C:\Users\MY> set-alias blah get-process // we have set "blah" as the alias for the get-process command and it is executed in the same line. PS C:\Users\MY> blah

Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName

------- ------ ----- ----- ------ -- -- -----------

188 11 2864 2904 2684 0 AppHelperCap

271 18 6428 20952 1.03 15256 2 ApplicationFrameHost

148 9 2108 1032 5320 0 armsvc

269 14 15172 21760 3.16 18868 0 audiodg

471 27 6544 5684 36.16 16624 2 AuthManSvr


If we want to see the detailed info of any alias created, use command help <aliasName>. See the example below where we are trying to see the detailed info of alias "my"(created previously):

PS C:\Users\MY> help my

NAME

Get-ChildItem


SYNTAX

Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes {ReadOnly

| Hidden | System | Directory | Archive | Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}]

[-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]


Get-ChildItem [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes

{ReadOnly | Hidden | System | Directory | Archive | Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream |

NoScrubData}] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]


ALIASES

gci

ls

dir

my


REMARKS

Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.

-- To download and install Help files for the module that includes this cmdlet, use Update-Help.

-- To view the Help topic for this cmdlet online, type: "Get-Help Get-ChildItem -Online" or

go to https://go.microsoft.com/fwlink/?LinkID=113308.


Objetcs: Everything in the powershell is an obejct. Even if we type the command 1+2 it returns 3 it is also an object. So everything is an object which is returned after

a command is executed in powershell. Say we execute the command "dir", it will return all the child directories in the present directory and it is an object. See the example

below:

PS C:\Users\MY> $file = dir //here the object is assigned to the variable "fille" PS C:\Users\MY> $file


Directory: C:\Users\MY> $file //variable "fille" is printed and it listed all the files in the directory.

Mode LastWriteTime Length Name

---- ------------- ------ ----

d-r--- 29-10-2021 15:54 3D Objects

d-r--- 29-10-2021 15:54 Contacts

d-r--- 10-11-2021 12:27 Desktop

d-r--- 29-10-2021 15:54 Documents

d-r--- 10-11-2021 15:39 Downloads

d-r--- 29-10-2021 15:54 Favorites

d-r--- 29-10-2021 15:54 Links

d----- 29-10-2021 15:54 mcafee dlp quarantined files

d-r--- 29-10-2021 15:54 Music

d-r--- 29-10-2021 16:05 OneDrive

d-r--- 29-10-2021 16:05 Pictures

d-r--- 29-10-2021 15:54 Saved Games

d-r--- 29-10-2021 16:01 Searches

d-r--- 01-11-2021 10:20 Videos


PS C:\Users\MY> $file[0]


Directory: C:\Users\MY

Mode LastWriteTime Length Name

---- ------------- ------ ----

d-r--- 29-10-2021 15:54 3D Objects


Currnt objects: If we want to refer to the current object, we can use $_. Suppose we want to access the name of the current object suppose the variable file we used in

the prevoius example


foreach loop: It is the loop which is used to run the same operations with each element in the list. See the example below:

foreach{$_*2} this says that all the elements of current object are going to be multiplied by 2.

PS C:\Users\MY> 1..10 |foreach{$_+2} 3

4

5

6

7

8

9

10

11

12

PS C:\Users\MY> 1.10 |foreach{$_+2} 3.1

PS C:\Users\MY> 1..10 |foreach{"*"*$_} *

**

***

****

*****

******

*******

********

*********

**********


Arrays:

To declare an array we use small bracket and put the comma separated values in there. The name of the array is like other variables

PS C:\Users\MY> $arr = @("mohd", "yusuf", "khan")

PS C:\Users\MY> $arr[0]

mohd

PS C:\Users\MY> $arr[3]

PS C:\Users\MY> $arr[2]

khan

PS C:\Users\MY>





functions in powershell:

To create a function in powershell, use the keyword "function" and give it a name. There is no need to add small brackets after the name of function like java.


//function declaration

function do-some{

1+3;

}

do-some //calling the function


If you want to parameterize the function, use the keyword "param" inside the curly braces(body of function) and write the parameters there. To pass the parameter at the

time of calling it, give the parameters separated with spaces. See the example below:

function do-somet{

param([int]$num1, [int]$num2)


$num1+ $num2;

}

do-somet 23 23

Another way of passing the parameter at runtime is to give the name of variables with hyphen then value and space and so on, see the code delow:

function do-somet{

param([int]$num1, [int]$num2)


$num1+ $num2;

}

do-somet -num1 23 -num2 100 //here the function has been called by giving the name of the parameters along with their values. We can change the order of the variables if

we specify the name also at the time of calling the function. The return keyword is used to return some values from the function. We can parameterize the functions like

we do in java and other programming languages by placing the small brackets after the name of the function.






 
 
 

Recent Posts

See All
Jenkins and its Set Up

CI/CD it is a practice which help in a ready to deploy code creation. Jenkins is an open source continuous integration server written in...

 
 
 
Test Performance with Jmeter

Execution order of jmeter elements: If multiple elements are added to a Test Plan in Jmeter, the execution order will be as follows:...

 
 
 

Comments


Subscribe Form

Thanks for submitting!

8810487385

  • Facebook
  • Twitter
  • LinkedIn

©2021 by testinggeeks. Proudly created with Wix.com

bottom of page