How to update app.config file using PowerShell?

Below code will help to update app.config file with given data-

#It helps to connect db and get the data.

$HostName = $env:computername
$connectionstring = 'Server=XX.XX.XX.XX;Database=TestDataBase;User Id=VM;Password=VMTest;MultipleActiveResultSets=True'
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = "SELECT [Params].value('(/root//Version/node())[1]', 'nvarchar(max)') as FirstName from Request where [Params].value('(/root//Name/node())[1]', 'nvarchar(max)') = '"+$HostName+"'"
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object “System.Data.DataTable”
$table.Load($result)
$Unified = $table | %{ $_.FirstName }

#It helps to update app.config file with given data.

$appConfigFile = 'C:\Project\ProjectPath\Project.dll.config'
$doc = (Get-Content $appConfigFile) -as [Xml]
$node = $doc.configuration.appSettings.add | where {$_.Key -eq 'Version'}
$node.value = $Unified
$doc.Save($appConfigFile)

How to convert PowerShell Object to a String?

Alike any other languages, PowerShell script also supports conversion of an object to a string for many kinds of manipulations. In my course of actions, I have come across two ways which help to convert Object to a string very easily.

Out-String

$string = Get-CimInstance Win32_OperatingSystem | Select-Object {$_.Version} | Out-String

%{$_.Version}

$string = Get-CimInstance Win32_OperatingSystem | %{$_.Version}

Note: you can replace your parameter with ‘Version’

 

How to create Windows 10 VM Template in SCVMM

A VM template is a master copy which we use to deploy multiple VM with our defined  base setup. Usually, creating VM template using System Center Virtual Machine Manager is pretty staraight forword however once it comes for Windows 10 then there is different scene- “SysPrep Failed” error. It comes everytime whenever I tried to create template in usual way.

VM.png

So I chose other way to create Windows 10 VM Template.

Steps:

  • Create a VM with Windows 10 OS.
  • Login into the VM once it gets created.
  • Ctrl+R and type ‘SysPrep’ and click on OK button.

VM1

Vm2

  • Execute sysprep.exe and select options as below screenshot.

Vm3

Vm4

  • Copy your VM vhdx file and paste in share folder of SCVMM. In my case its in ‘Win10-Default’.
  • Now Click on Library > Click on ‘Create VM template’.
  • Select first radio option and same VHDX file from copied location.
  • Click on Next button.

VM5.png

  • Provide VM Template name and click on Next button.

VM6.png

  • Now check the details in ‘Configure Hardware’ section. Its same as while creating VM we have given.

VM7

VM8

VM9

  • Make sure Differencing Disk checkbox is checked.

Vm10

VM11

  • Provide the details in Configure Operating System as given below screenshots

12.png

13

  • Provide Product Key

14.png

  • Provide Domain and Workgroup details.

15.png

That’s it. In last screen, click on Create button to complete your process.

PowerShell Get-ChildItem -Include, -Exclude, and -Recurse parameters

‘Get-ChildItem’ cmdlet gets you the contents of any given path and then you can perform your next desired actions on them.

In my case, I have to get into the particular folder and need to find out all exe and msi files to install in the system. Usually when we get into any folder there could be again child folders and folders, in this case we can use ‘-Recurse’ parameter with Get-ChildItem which basically helps to get into all child folder and gets you your desired output. ‘-Include’ and ‘-Exclude’ parameters name suggests what’s the use of these.

OK let’s see below script to get all msi and exe file from particular path and install the same on system-

$path = "D:\Softwares\MyPackage\ISOImage\Prerequisites\"
$IncludeExe = @("*.exe", "*.msi")
$ExcludeExe = @("SQL*", "SS*")
$foldercontents = Get-ChildItem -Path $path -File -include $IncludeExe -exclude $ExcludeExe -Recurse
if($foldercontents.Count -eq 0){exit}else{foreach ($exefile in $foldercontents){Start-Process $exefile /q -wait}}

How to integrate System Center Service Manager with Orchestrator

The Service Manager is used to give organizations a single, integrated platform to deliver IT as a Service (ITaaS). There are around six major components under System Center Service Manager and we are using Service Manager Console to integrate System Orchestrator to Service Manager.
To integrate System Center orchestrator to service manager, there are five major steps-

  1. Create Connector for SC Orchestrator
  2. Create Runbook Automation Activity Template
  3. Create Service Request Template
  4. Create Request Offering
  5. Create Service Offering

Create Connector in SC Orchestrator

  1. Open SC Service Manager as Administrator (It installed automatically with a Service Manager Management server)
  2. Click on Administrator > Connector.
  3. Click on Create connector > Orchestrator Connector

SM1

4. Provide connector name.

SM2

5. Provide Orchestrator Web Service URL.

SM3

6. Select the Orchestrator folder for sync.

SM4

7. Click on Create button.

SM5

Create Runbook Automation Activity Template

  1. Click on Library > Runbooks link in left pane (Before creating Runbook activity template please make sure connected Runbook is synced with Service Manager).

SM1

2. Click on Create Runbook Automation Activity Template link from right pane.

3. Provide template Name and Description.

SM2

4. Click on OK button.

5. Select “Is Ready For Automation” checkbox under General tab.

SM3

6. Go to Runbook tab and select desired runbook and verify the runbook parameters map with template.

SM4

7. Click on Apply button.

8. Click on OK button.

Create Service Request Template

  1. Click on Library > Templates link from left pane.
  2. Provide Template Name.
  3. Select Management pack.

SM1

4. Click on OK button.

5. Click on Activities tab.

SM2

SM3

6. Click on + green button.

7. Select Runbook Automation Activity template.

8. Click on OK button.

9. Click on Apply button.

Create Request Offering

  1. Click on Library.
  2. Select Service Catalog.
  3. Select Request Offering.
  4. Click on ‘Create Request Offering’ link from right pane.

SM1

5. Provide Request Offering Title.

6. Select Service Request Template Name.

SM2

7. Click on Next button.

8. Provide User Prompts, Response Type, and Prompt Type.

SM3

9. Click on Next button.

SM4

10. Click on Next button.

SM5

11. In Map Prompts tab, Select Runbook Automation Activity option and map the prompts.

12. Click on Next button.

SM6

13. In Publish tab, select ‘Published’ option in ‘Offering status’ select field.

14. Click on Next button.

Create Service Offering

  1. Click on Library tab from left pane.
  2. Select Service Offering label from left pane.
  3. Click on Create Service Offering link from right pane.

SM1

4. Provide service title and click on Next button.

5. Go to Request Offering tab.

SM2

6. Click on Add button.

7. Select created Request Offering.

SM3

8. Click on Add button.

9. Click on OK button and come out.

SM4

10. From Publish tab, Select Published option in Offering status select field.

11. Click on Next button.

SM5

12. Now click on Create button to publish the offering.

Alright we are set now. Now open Service Catalog URL and submit your request to automatically remove VM checkpoints.

SM1

SM2

How to create VM checkpoints using Orchestrator Runbook

Well, if anyone googled “How to create VM checkpoints using Orchestrator Runbook” that gives feeling person who searched this term is new with Orchestrator Runbook concept however he/she is aware about Virtualization, Checkpoints, and PowerShell and now he/she wanted to move a step forward to do the same with System Center.

Alright, before going into the details that how we can do the same with System Center Orchestrator, let me brief about System Center, Orchestrator, Runbooks, and VM Checkpoint. Certainly, after this we will walk through step-by-step to understand Runbooks automation.

System Center:  Microsoft System Center is a bundled suite of systems management products that offers tools to monitor and automate virtualized environments, including private clouds based on Microsoft Hyper-V.

Orchestrator: Orchestrator is a workflow management solution for the data center

Runbooks: Runbooks contain the instructions for an automated task or process.

Checkpoints: Checkpoint saves the state of each virtual hard disk that is attached to a virtual machine and all of the hard disk’s contents, including application data files.

There are other ways also to create VM checkpoints like-

Creating Checkpoint Using Hyper-V Manager

CP1.png

Creating Checkpoint Using PowerShell script

Get-SCVirtualMachine | where {$_.Status -eq "PowerOff" -and $_.Name -eq "VM_Name"} | New-SCVMCheckpoint -Name Checkpoint_Name

Creating Checkpoint Using Orchestartor Runbook

To create checkpoint System Center should be installed in your server and Runbook Designer should be open as Administrator.

Step 1:

Create a runbook.

  1. Right click on Runbook > New > Runbook.
  2. Rename it.
  3. Click on Check In icon link.

CP7

CP4

CP5

CP6

Step 2:

Drag and Drop activities in Runbook Designer design workplace from Activities pane.

Scenario: To create checkpoint for any VM following points are required-

  • Script required user inputs for VM name and checkpoint name.
  • Script should get the status of VM, if VM is in Running status then it should be shutdown before taking the checkpoint.
  • Script should take the screenshot.
  • After taking the screenshot script should leave VM in original state.

Alright so our scenario is ready, now its time to add different activities in design workspace.

  1. Select Runbook Control activities.
  2. Drag and drop Initialize Data activity in design workspace.
  3. Double click on Initialize Data activity.
  4. Add two parameters by clicking on Add button.
  5. Change the parameters name as per your wish by clicking on parameters name. CP8
  6. Click on Finish button.
  7. Select SC 2016 Virtual Machine Manager activity.
  8. Drag and drop Get VM activity in Design Workspace.
  9. To create a link from the Initialize Data activity to the Get VM activity, click and drag the right arrow of the Initialize Data activity to the Get VM activity.
  10. Double click on Get VM activity.
  11. Click the ellipse () button to the right of the Name box, and then select specified server name.
  12. Click on Add button.
  13. Make sure Name field is displaying VM Name value.
  14. Right click on Value field > Subscribe > Published Data.
  15. Select VM Name (a parameter which we have set in Initialize Data activity)
  16. Click on OK button.
  17. Click on OK button.
  18. Click on Finish button.
  19. Drag and Drop Shut Down VM activity from SC 2016 Virtual Machine Manager.
  20. To create a link from the Get VM activity to the Shut Down VM activity, click and drag the right arrow of the Get VM activity to the Shut Down VM activity.
  21. Double click on connecting arrow of Get VM to Shut Down VM.
  22. Click on Add button to add new condition.
  23. Click on newly added Get VM link.
  24. Select Status and click on OK button.
  25. Click on value link and changed to ‘Running’.
  26. Click on OK button.
  27. Now condition should look like this “Status from Get VM equals Running”
  28. Click on Finish button.
  29. Double click on Shut Down VM activity.
  30. Click the ellipse () button to the right of the Name box, and then select specified server name.
  31. Right click on next to VM ID > > Subscribe > Published Data.
  32. Select VM ID and click on OK button.
  33. Click on Finish button.
  34. Select Monitoring from activities.
  35. Drag and drop Get Computer/IP Status activity.
  36. To create a link from the Get VM activity to the Get Computer/IP Status activity, click and drag the right arrow of the Get VM activity to the Get Computer/IP Status activity.
  37. To create a link from the Shut Down VM activity to the Get Computer/IP Status activity, click and drag the right arrow of the Shut Down VM activity to the Get Computer/IP Status activity.
  38. Double click on Get Computer/IP Status activity.
  39. Right click Computer text field > > Subscribe > Published Data.
  40. Select VM ID and click on OK button.
  41. Click on Finish button.
  42. Right click on Get Computer/IP Status activity and select looping…
  43. Select Enable checkbox.
  44. Enter 30 Delay between attempts.
  45. Click on Finish button.
  46. Select SC 2016 Virtual Machine Manager activity.
  47. Drag and drop Create Checkpoint activity in Design Workspace.
  48. To create a link from the Get Computer/IP Status activity to the Create Checkpoint activity, click and drag the right arrow of the Get Computer/IP Status activity to the Create Checkpoint activity.
  49. Double click on arrow between Get Computer/IP Status and Create Checkpoint activity.
  50. Click on Success link and select failed checkbox.
  51. Click on Finish button.
  52. Double click on Create Checkpoint activity.
  53. Click the ellipse () button to the right of the Name box, and then select specified server name.
  54. Right click on next to VM ID > > Subscribe > Published Data.
  55. Select Get VM activity from Activity select field.
  56. Select VM ID and click OK button.
  57. Click on Optional Properties button.
  58. Select Name and click on >> button.
  59. Click on OK button.
  60. Right click on next to Name > > Subscribe > Published Data.
  61. Select Initialize Data activity from Activity select field.
  62. Select second parameter for checkpoint which we have set during Initialize Data activity. In my case, I have given CP Name.
  63. Click on OK button.
  64. Click on Finish button.
  65. Drag and drop Start VM activity from SC 2016 Virtual Machine Manager.
  66. To create a link from the Create Checkpoint activity to the Start VM activity, click and drag the right arrow of the Create Checkpoint activity to the Start VM activity.
  67. Double click on Start VM activity and Click the ellipse () button to the right of the Name box, and then select specified server name.
  68. Right click on next to VM ID > > Subscribe > Published Data.
  69. Select Get VM activity from Activity select field.
  70. Select VM ID and click OK button.
  71. Click on Finish button.
  72. Click on Check In icon link to save the runbook.

OK, after all these steps your runbook should look like this-

CP9

  • Now click on Runbook Tester link.
  • Click on Step Through link.

CP10

Once you pass VMName and CPName, it will start creating checkpoint by given name.

It may look lengthy process but once you get the flow of activities then it is very easy to automate complex task in few minutes. Remember, in the background engine is PowerShell script only.

Hope all the details are making sense. In the next blog I would discuss how to inject PowerShell script in the runbook and how to integrate Runbook to System Center Service Manager.

Disable and Enable Features Using Dism

Dism- Deployment Image Servicing and Management used to service a windows image (.wim) or a virtual hard disk. It can be also used to enable and disable features in windows.

Start the cmd as administrator and supply below commands-

#It gives the list of all features

C:Windows\system32>Dism /online /Get-Features

#It enable the feature

C:Windows\system32>Dism /online /Enable-Feature /FeatureName:<FeatureName> /All

cmd

#It disable the feature

C:Windows\system32>Dism /online /Disable-Feature /FeatureName:<FeatureName>

cmd1

Reading and Writing Text File using PowerShell

Here I am listing some of the common cmdlets which help to operate with text file-

How to create text file using PowerShell?
New-Item <File Path>
How to open text file or any folder sturcture using PowerShell?
Invoke-Item <File Path>
How to add or append contents in text file using PowerShell?
Add-Content <File Path> Text with single quote
How to clear contents in text file using PowerShell?
Clear-Content <File Path>
How to clear contents and add new contents in text file using PowerShell?
Set-Content <File Path> Text with single quote
How to read file contents using PowerShell?
Get-Content <File Path>
How to save cmdlets outputs directly to text file?
Cmdlets | Out-File <File Path>. Example: Get-Process | Out-File D:\PowerShell
How to remove text file using PowerShell?
Remove-Item <File Path>

How to create generation 2 virtual machine using PowerShell?

Below script would help to create virtual machine in Hyper-V using PowerShell-

  1. Open PowerShell window as admin.
  2. Paste below script and hit enter.
  3. VM would be created.
  4. Open Hyper-V Manager and verify it.

# Set VM Name, Switch Name, and Installation Media Path.
$VMName = ‘TestVM’
# Switch is nothing but network adapter
$Switch = ‘My New Virtual Switch’
#OS Iso file should be assigned to InstallMedia
$InstallMedia = ‘D:\Softwares\en_windows_10_enterprise_version_1607_updated_jul_2016_x64_dvd_9054264.iso’

# Create New Virtual Machine
# MemoryStartupBytes contents the RAM size of VM.
# NewVHDSizeBytes contents the size of HD.
New-VM -Name $VMName -MemoryStartupBytes 1073741824 -Generation 2 -NewVHDPath “C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\$VMName.vhdx” -NewVHDSizeBytes 53687091200 -Path “C:\ProgramData\Microsoft\Windows\Hyper-V\$VMName” -SwitchName $Switch

# Add DVD Drive to Virtual Machine
Add-VMScsiController -VMName $VMName
Add-VMDvdDrive -VMName $VMName -Path $InstallMedia

# Mount Installation Media
$DVDDrive = Get-VMDvdDrive -VMName $VMName

# Configure Virtual Machine to Boot from DVD
Set-VMFirmware -VMName $VMName -FirstBootDevice $DVDDrive

Extension Method in Selenium, what, why, and how???

An Extension Method enable us to add methods to existing   types without creating a new derived type, recompile, or modify the original types.

Alright, confusing???

Picture1

Now consider you don’t have access for Car class and if I ask you to add a method for Car class, how would you do that?

In this kind of circumstances you can use Extension method concept to add a method for existing type without creating new class.

Still???

If I ask you write a program which should give today date, probably you would write below lines of code-

Picture2

Now if I ask you to give 1 month back date, probably you would write below method to get 1 month back date-

Picture3

Certainly you would write this method in a class and to call this method you would create object.

Picture4

How it would be if you get same method like this-

Picture5

You can achieve above line of code using Extension Method concept.

Picture6

Now you will see your extension method in below manner-

Picture7

OK, there are some rules also-

  • It should be static method.
  • It must be located in a static class.
  • It should use the “this” keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
  • An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
  • You can give any name for the class that has an extension method but the class should be static.
  • If you want to add new methods to a type and you don’t have the source code for it, then the solution is to use and implement extension methods of that type.

Picture8

Now you will see your selenium extension method in below manner-

Picture9

Alright, now we will see a real time example-

While automating an application sometimes we all observed that click action performs the operation but button does not get clicked.

In that scenario, mostly we write different line of codes or methods to achieve our goal.

So instead of writing code each time for specific click, we can write different extension methods to handle all possible click actions and if one click is not working out we can call another IWebElement click methods (Extension Method).

It’s a right approach in any Automation framework to keep extension methods to perform the similar kind of actions using different ways.