Monday, 27 October 2014

How to build a form in PowerShell ?

Windows Forms (Win Forms)

https://gallery.technet.microsoft.com/How-to-build-a-form-in-7e343ba3

Windows Forms is a set of managed libraries in .NET Framework. Win-form is designed to develop client applications and it provides different kind of controls, such as text-boxes, buttons, and web pages along with options to create custom controls.
Here I am showing how to create a GUI using win-from. This is an older way of form creation, but the base of all GUI applications.

Loading Assemblies is the first step in creating a windows form. There are two main assemblies that are required in our form creation (It may work without loading assemblies in Powershell hosts like ISE, but it won't work if you are converting PS Scripts to .Exe and running desperately). The best practice is to load those class in the initial stage to avoid errors
       
001
002
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

Object Creation: We have to create a new object. This object type may differ based on our requirements. Once you create a form you have to call the form. Below is the basic example of a new object creation for a form

PART -1  Basics of form creation


001
$Form = New-Object system.Windows.Forms.Form

Get member cmdlet ( $Form | gm ) will provide the details of property and method of this object and  we can call the form to view the GUI using the below cmdlet


001
$Form.ShowDialog()

Now Combine all together and run it from PowerShell ISE or any other host and see the output.


001
002
003
004
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$Form = New-Object system.Windows.Forms.Form
$Form.ShowDialog()
















The above form is a blank one as we have not added any items on it, now we are going to add some controls on the form. Follow the below steps.

I am defining the size of the form using the below cmdlet, you can see I have used multiple ways for defining the form size, also there is an option to set the auto-size option.


001
002
003
004
005
006
007
$Form = New-Object system.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(400,200)
#You can use the below method as well
#$Form.Width = 400#$Form.Height = 200#
$Form.AutoSize = $True
$Form.AutoSizeMode = "GrowAndShrink"
$Form.Text = "My Application"

If you are using auto size with auto-size mode growandshrink, form size will automatically adjust as per the data\controls that you are adding to form..

Label Creation and customization.


001
002
003
004
005
$Label = New-Object System.Windows.Forms.Label
$Label.AutoSize = $true
$Font = New-Object System.Drawing.Font("Arial",15,[System.Drawing.FontStyle]::Bold)
$form.Font = $Font
$Label.Text = "This is My Test App"

Method of Adding $Label object into $From object


001
002
$Form.Controls.Add($Label)
$Form.ShowDialog()













What we learned in 1st Part ???

Loading assembly
Creating different object for forms
Customizing form ( By giving size and text )
Creating and customizing label and call the form for GUI
________________________________________________

PART - 2  Form Customization: 

Now we are going to create a form which includes >>>
Creation of form closing actions
Form button creation
Button creation

Base form creation


001
002
003
004
$Form = New-Object system.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(400,200)
$Form.Text = "My Application"

1 - Creation of form's closing actions

001
002
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter") {$Form.Close()}})
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape") {$Form.Close()}})

As per the above example, the form will be closed if you press Enter or Escape button. You can include letters as well to close the form (We should give only capital letters). As per the below example, the form will be closed if you press V letter on the keyboard.

001
$Form.Add_KeyDown({if ($_.KeyCode -eq "V") {$Form.Close()}})

2 - Form Button Creation

We have to create a .ICO image for our form button. Either you can generate from Photoshop or you can create from online icon creation websites.

Please note the below cmdlet which is pointing to a path of the icon file.

001
002
$formIcon = New-Object system.drawing.icon ("C:\vivek\red.ico")
$form.Icon = $formicon

3 - Button Creation

001
002
003
004
005
006
007
008
$Okbutton = New-Object System.Windows.Forms.Button
$Okbutton.Location = New-Object System.Drawing.Size(125,50)
$Okbutton.Size = New-Object System.Drawing.Size(100,50)
$Okbutton.Text = "OK"
$Okbutton.Add_Click({$Form.Close()})
$Form.Controls.Add($Okbutton)
$Form.ShowDialog()

Now our form is ready with Form icon and Button














Putting all the command together: PART - 1 And PART - 2

I have commented out the Form ICON lines... You can enable if you have a downloaded ICON pic by providing a proper name and icon's path


001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$Form = New-Object system.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(400,200)
$Form.AutoSizeMode = "GrowAndShrink"
$Form.Text = "My Application"


$Label = New-Object System.Windows.Forms.Label
$Label.AutoSize = $true
$Font = New-Object System.Drawing.Font("Arial",15,[System.Drawing.FontStyle]::Bold)
$form.Font = $Font
$Label.Text = "This is My Test App"
$Form.Controls.Add($Label)


$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter") {$Form.Close()}})
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape") {$Form.Close()}})


#$formIcon = New-Object system.drawing.icon ("C:\vivek\red.ico")
#$form.Icon = $formicon


$Okbutton = New-Object System.Windows.Forms.Button
$Okbutton.Location = New-Object System.Drawing.Size(125,50)
$Okbutton.Size = New-Object System.Drawing.Size(100,50)
$Okbutton.Text = "OK"

$Okbutton.Add_Click({$Form.Close()})
$Form.Controls.Add($Okbutton)


$Form.ShowDialog()

PART - 3  Creation of Button's Click Action: 

We have different options to connect the button to our script. In the previous part, I have used close() command in button click action to close the form. Now I am going to change the click action...


001
$Okbutton = New-Object System.Windows.Forms.Button

Method - 1

Use the cmdlet directly inside the script block

001
002
003
004
005
006
$Okbutton = New-Object System.Windows.Forms.Button
$Okbutton.Location = New-Object System.Drawing.Size(125,50)
$Okbutton.Size = New-Object System.Drawing.Size(200,50)
$Okbutton.Text = "Get-Service"
$Okbutton.Add_Click({Get-Service | Out-GridView})
$Form.Controls.Add($Okbutton)

Method - 2

Using function - We can define our script under a function and then we can call the function inside the click action. once you click on the button the function will be called and execute.

001
002
003
004
005
006
007
008
009
010
function Service
{
Get-Service | Out-GridView
}
$Okbutton = New-Object System.Windows.Forms.Button
$Okbutton.Location = New-Object System.Drawing.Size(125,50)
$Okbutton.Size = New-Object System.Drawing.Size(200,50)
$Okbutton.Text = "Get-Service"
$Okbutton.Add_Click({Service})
$Form.Controls.Add($Okbutton)

Method - 3

Calling script file (PS1) - Using this method we can call a PS1 file that is saved on your machine when you click on any controls (Buttons), in the back end the script you defined will be called and execute.

001
002
003
004
005
006
$Okbutton.Location = New-Object System.Drawing.Size(125,50)
$Okbutton.Size = New-Object System.Drawing.Size(200,50)
$Okbutton.Text = "Get-Service"
$Okbutton.Add_Click({
Invoke-Expression -Command "C:\Vivek\service.ps1"
})


Thanks for reading, I will be posting the Form creation using XAML and WPF soon.



Friday, 24 October 2014

GUI Creation Methods for PowerShell

There are many ways to create GUI for powershell... Below are the some of main option which I used to create powershell GUI.
  1. Windows Forms.
  2. Windows Presentation Foundation (WPF) by Integrating XAML into Powershell 
  3. Sapien powershell studio etc: Download 
Windows Forms (Win Forms)
Windows Forms is a set of managed libraries in .NET Framework. Win-form is designed to develop client applications and it provides different kind of  controls, such as text-boxes, buttons, and web pages along with options to create custom controls.

Windows Presentation Foundation (or WPF)
WPF is the latest technology for creating GUI and initially released as a part of .NET 3.0 which includes the features like 3D support, Interactive data visualization and content readability.


      .Net Framework Latest Stack:


Wikipedia Definitions:
Windows Forms (Win Forms) is the name given to the graphical application programming interface (API) included as a part of Microsoft .NET Framework, providing access to native Microsoft Windows interface elements by wrapping the extant Windows API in managed code. While it is seen as a replacement for the earlier and more complex C++ based Microsoft Foundation Class Library, it does not offer a paradigm comparable to Model–View–Controller. Some after-market and third party libraries have been created to provide this functionality. The most widely used of these is the user interface application block which is released by the Microsoft patterns & practices group as a free download that includes the source code for quick start examples.

Windows Presentation Foundation (or WPF) is a graphical subsystem for rendering user interfaces in Windows-based applications by Microsoft. WPF, previously known as "Avalon", was initially released as part of .NET Framework 3.0. Rather than relying on the older GDI subsystem, WPF uses DirectX. WPF attempts to provide a consistent programming model for building applications and separates the user interface from business logic. It resembles similar XML-oriented object models, such as those implemented in XUL and SVG.


Refer the below link to know how to build GUI using powershell
Building GUI Using Powershell

Monday, 29 September 2014

Import the Power shell module for Configuration Manager 2012

PowerShell module for managing System Center Configuration Manager 2012 is not available by default in PowerShell Console... If you want to Import module for SCCM 2012, run the below command

001
Import-Module (Join-Path $(Split-Path $env:SMS_ADMIN_UI_PATHConfigurationManager.psd1)

If you are using SCCM console from different PCs, you have to copy the module file (ConfigurationManager.psd) from SCCM server or Go to File Menu of SCCM and Open PowerShell


Saturday, 20 September 2014

Virtual Machine Creation In Azure Using PowerShell


  • Azure Registration : As you know we have to register in azure to use all the stuff. Below is the azure sing up \ Sign In link. One month free trial available.
          Azure Sin Up \ Sign In
  • Azure PowerShell module Installation : You can download and Install Azure Powershell from the below URL. After the installation, you will be able to find a new console named Microsoft Azure Powershell on you start.

    Download Azure PowerShell module
  • Azure Publish settings file download and configure : We have to download our azure publish file from our azure subscription. Follow the below steps to do that..
PS C:\>Get-AzurePublishSettingsFile
PS C:\>

This command will take you to azure log in page as showing below. You will have to provide your azure credential which you have registered prior.
















Once you logged, you will be prompted to download azure public setting file.Save the publish settings file on your drive. Refer the below picture.
File name will be like (Free Trial-9-19-2014-credentials.publishsettings)



















Now we have to import the saved publish setting file using the below command. Command should point to 

the saved location. So please note the location of public setting file while downloading.



PS C:\> Import-AzurePublishSettingsFile 'C:\vivek\Free Trial-9-19-2014-credentials.publishsettings'

This command will install the certificate into your certificate store and will configure your subscription settings.
You can verify the configured subscription by typing the below command. It will display the Subscription ID 


PS C:\> Get-AzureSubscription

# Execution Result

SubscriptionId             : b96c19a1-83c0-4614-91bf-402074vf4ae7
SubscriptionName          : Free Trial
Environment                  : AzureCloud
SupportedModes            : AzureServiceManagement
DefaultAccount              : BD555B5D40D53783C2BC366E2CD49A49EA459906
Accounts                       : {BD555B5D40D53883C2BC366F2CD49A49EA459906}
IsDefault                        : True
IsCurrent                        : True

CurrentStorageAccountName : 

Now we have to select the subscription



PS C:\> Select-AzureSubscription -SubscriptionName "Free Trial"

# You can use (Get-AzureSubscription).SubscriptionName to get the subscription name.Make sure that you are typing the correct subscription name as displayed.. 

Verify the subscription using the below command

PS C:\> get-AzureSubscription -Default

PS C:\>

Affinity Group Creation And Set the Storage Account to be used by new affinity group 


Affinity Groups are a way you can group your cloud services by proximity to each other in the Azure data center in order to achieve optimal performance. When you create an affinity group, it lets Azure know to keep all of the services that belong to your affinity group as physically close to each other as possible. For example, if you want to keep the services running your data and your code together, you would specify the same affinity group for those cloud services. They would then run on hardware that is located close together in the data center. This can reduce latency and increase performance, while potentially lowering costs.


PS C:\> New-AzureAffinityGroup -Name "VivAffGrp" -Location "Southeast Asia" -Label "VIVEKRRLAB" -Description "My Affinity Group" -Verbose

#Execution Result

VERBOSE: 11:46:25 AM - Begin Operation: New-AzureAffinityGroup
VERBOSE: 11:46:28 AM - Completed Operation: New-AzureAffinityGroup

OperationDescription                             OperationId                                                          OperationStatus                                

--------------------                                         -----------                                                              ---------------                                
New-AzureAffinityGroup                           2c6aa8ee-c6eb-1dd6-b67a-213e1c6d0f0d             Succeeded
PS C:\>

Storage Account Creation : 

"To store files and data in the Blob, Table, Queue, and File services in Azure, you must create a Storage account in the geographic region where you want to store the data"


So we need to create a storage account to create VMs ( To save VHDs ) . Follow the below steps to do that. Sharing the present status of my storage account.


















Before creating storage account, we have to know which location has to be selected. So find out the list of location available in azure and select accordingly.


# Get the Location Name first
PS C:\> (Get-AzureLocation).Name
#Execution Result
South Central US
Central US
East US 2
East US
West US
North Europe
West Europe
East Asia
Southeast Asia
Japan West

We got some location list as shown above, and we are going to select "Southeast Asia" as our location.

After the creation of storage account, we have to disable Geo replication option (Optional) if you are using the LAB locally.

* Storage Account Name will accept only small letters and numbers. Do Not Give Capital Letter 



PS C:\>New-AzureStorageAccount -AffinityGroup "VivAffGrp" -StorageAccountName "vivekrrstorage" -Label "VIVEKRRLAB" -Description "My Storage Account" -Verbose

PS C:\> Set-AzureStorageAccount -StorageAccountName vivekrrstorage -GeoReplicationEnabled $false -Verbose


#Execution Result

VERBOSE: 10:45:59 AM - Begin Operation: Set-AzureStorageAccount
VERBOSE: 10:46:04 AM - Completed Operation: Set-AzureStorageAccount
OperationDescription                             OperationId                                      OperationStatus                                
--------------------                             -----------                                      ---------------                                
Set-AzureStorageAccount                          5239ec4f-18f3-1925-9f1d-5fa4a34561e9             Succeeded 



Storage Account is ready in Azure : Note the below storage account name
















Once we created the storage account, set it as like the current storage account to be used for your default subscription. Follow the below steps and confirm that the current storage account name (vivekrrstorage) is displayed in your subscription.


PS C:\> Set-AzureSubscription -SubscriptionName "Free Trial" -CurrentStorageAccountName "vivekrrstorage"

#Confirm that the subscription has been set or not


PS C:\> Get-AzureSubscription
#Execution Result
SubscriptionId                         : b96c19a1-83c0-4614-91bf-402074cf4ae7
SubscriptionName                   : Free Trial
Environment                            : AzureCloud
SupportedModes                    : AzureServiceManagement
DefaultAccount                       : BD555B5D40D53783C2BC366F2CD49A49EA459906
Accounts                                : {BD555B5D40D53783C2BC366F2CD49A49EA459906}
IsDefault                                 : True
IsCurrent                                : True
CurrentStorageAccountName : vivekrrstorage

Now you will be able to see the current storage account name has updated with its value (vivekrrstorage).


Cloud Service Creation:


Cloud Service: By creating a cloud service, you can deploy a multi-tier web application in Azure, defining multiple roles to distribute processing and allow flexible scaling of your application. A cloud service consists of one or more web roles and/or worker roles, each with its own application files and configuration. Azure Websites and Virtual Machines also enable web applications on Azure. The main advantage of cloud services is the ability to support more complex multi-tier architectures. For a detailed comparison,


Please note that there is no cloud service created yet..















PS C:\> New-AzureService -ServiceName "CloudServiceViv" -AffinityGroup "VivAffGrp" -Label "VIVEKRRLAB" -Description "My Cloud Service" -Verbose

#Execution Result

VERBOSE: 1:16:10 PM - Begin Operation: New-AzureService
VERBOSE: 1:16:14 PM - Completed Operation: New-AzureService
OperationDescription                                         OperationId                                                       OperationStatus                                            
--------------------                                                   -----------                                                              ---------------                                            
New-AzureService                                             edbcd0e0-867a-18e5-a215-2fd2a2937bb3                         Succeeded                                                  



Cloud Service is ready now ... You can type Get-AzureService to check the status..












                       

Get Ready To Create VMs  :)

The first step is to decide that, which Image (or OS) you are going to deploy in Azure. There are many Images available in azure gallery.So we need to find out the Image name to deploy it. If you want you can log in and check Image availability in Azure. Below is the VM gallery snap from Azure Portal


























Now we are going to fetch the same details through powershell


Get-AzureVMImage is the Cmdlet to retrieve all the available VMs Images from Azure Portal.. As per the above snap shot Windows Server 2012 R2 Datacenter is the Imagefamily Name of an Image. So first you go ahead and type Get-AzureVMImage and see how the out put is !!!


Image Family : Image Family is a Property field of Azure VM Image (Display Name)


PS C:\> Get-AzureVMImage
PS C:\>(Get-AzureVMImage).ImageFamily

#Execution Result

Visual Studio Professional 14 CTP 2 on Windows Server 2012 R2
RightScale Linux v13
RightScale Linux v13
RightScale Linux v14
JDK 6 on Windows Server 2012
JDK 6 on Windows Server 2012
JDK 7 on Windows Server 2012
JDK 7 on Windows Server 2012
JDK 8 on Windows Server 2012 R2
JDK 8 on Windows Server 2012 R2
JDK 8 on Windows Server 2012 R2
Oracle Database 11g R2 Enterprise Edition on Windows Server 2008 R2
Oracle Database 11g R2 Enterprise Edition on Windows Server 2008 R2
.....................................................................................................
more

#Total Images Available in Azure Portal


PS C:\>((Get-AzureVMImage).ImageFamily).count


#Execution Result

253


Have a check on any Images and see all the property. Below I am checking a Linux Image.The same way you can check a Windows Image by giving the Image Family Name.

First property is the Name of Image (Vhd)



PS C:\> Get-AzureVMImage | ? {$_.ImageFamily -eq "RightScale Linux v13"} | select -First 2
#Execution Result
ImageName                 : 0b11de9248dd4d87b18621318e037d37__RightImage-CentOS-6.2-x64-v5.8.8.1
OS                               : Linux
MediaLink                    : 
LogicalSizeInGB          : 10
AffinityGroup               : 
Category                     : Public
Location                      : East Asia;Southeast Asia;North Europe;West Europe;Japan West;Central US;East US;East US 2;West US
Label                          : RightImage CentOS 6.2 x64 v5.8.8.1
Description                 : CentOS 6.3 with RightLink 5.8.
Eula                            : http://support.rightscale.com/12-Guides/RightLink/RightLink_End_User_License_Agreeement
ImageFamily               : RightScale Linux v13
PublishedDate             : 8/28/2012 5:30:00 AM
IsPremium                   : False
IconUri                        : 
SmallIconUri               : 
PrivacyUri                   : http://www.rightscale.com/privacy_policy.php
RecommendedVMSize : 
PublisherName           : RightScale with Linux
OperationDescription : Get-AzureVMImage
OperationId                : 053fe9cd-7e9f-1a4c-a6d4-601184234ba6
OperationStatus         : Succeeded

Creation of Virtual Machine and Provisioning Configuration :


We are going to create a Windows Server VM. So first we need to find out the exact name of the VM using the below command. Refer the above Image Gallery Screen Shot.



PS C:\> $SelectedVM = Get-AzureVMImage | ? {$_.ImageFamily -eq "Windows Server 2012 R2 Datacenter"} | select -last 1

Here I am selecting the last Image of "Windows Server 2012 R2 Datacenter". There are different images available in azure portal for the same OS. Most probably last Image will be the latest image released from Microsoft. You can check the published date as well to confirm the latest Image.

  • Creating Virtual Machine Configuration:

$Image = $SelectedVM.Imagename



PS C:\>$Configuration = New-AzureVMConfig -Name "VIVServer01" -InstanceSize "small" -ImageName $Image


















  • Adding Provisioning Configuration :

$UserName = "vivadmin"
$Password = "Image@123"

PS C:\>Add-AzureProvisioningConfig -Windows -AdminUsername $Username -Password $Password -VM $Configuration

Now the configuration field also filled















  • Networking Part
Right Now I am not creating Virtual Network through Powershell as there is no cmdlet to do that. So I have already created a VNet in my azure platform. Only we need to add those details to our VM Configuration.
Below is my VNet Configuration In Azure Portal.


















Adding IP Address and Sub-net Name to VM Configuration : 

$IpAddress = "10.0.0.5"

PS C:\>Set-AzureStaticVNetIP -IPAddress $IpAddress -VM $Configuration
PS C:\>Set-AzureSubnet -SubnetNames DC001 -VM $Configuration
#Just Verify the Configuration

PS C:\>$Configuration.ConfigurationSets

















The Final Steps : VM Creation : 

PS C:\>New-AzureVM -ServiceName "CloudServiceViv" -VMs $Configuration -VNetName "MyNET" -Verbose












Now our New VM ( VIVServer01 ) Is ready on Azure  !!!














Now you can start using the new VM by connecting from Azure portal or through Powershell (PS Session). 

I am just ceating a VM in azure portal... Please Visit below URL (DexterPosh) to know more about Powershell + Azure Deploy