DNK Gif

Dot Net Knowledge

Labels

Tuesday, 1 November 2016

Deployment Automation using WixSharp (Wix#)

How to Automate Deployment Process?

Normally We developer, for deployment of a WebApplication, we prepare a deployment manual of 10-11 pages, put down steps and hand over the document to Deployment Team with the Source Codes in TFS or any Version Controlled System. Then they will follow one by one step to do the deployment. 
  • Imagine if any single step is missed, then ??
  • If the person doing deployment not familiar with your technology then it's a guarantee, there would be some discrepancy.
  • What if more than one application needs to be integrated for a single application, how many pages of deployment manual it would be? And what is the probability of a successful deployment?

So we have to automate these processes to make the deployment process error free. And in order to achieve that building MSI (Microsoft Installer) is a good option. So the developer will hand over the MSI file to the Server Admin then just clicking on the MSI file will complete the job and of-course it will be error free because there would be no chance of missing any step.

So here is how to build MSI and automate the Deployment process


Sunday, 11 September 2016

Enable/Install IIS in your System or Server by just running the batch file

IIS installation using batch file



Ease your IIS installation in any system or server just by running the batch file as Administrator. Here goes the series of commands to enable all the features in IIS by just a single click. You can remove any line of command if that feature is not needed for you.

%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-WebServerRole
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-WebServer
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-CommonHttpFeatures
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HttpErrors
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HttpRedirect
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ApplicationDevelopment
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-NetFxExtensibility
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HealthAndDiagnostics
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HttpLogging
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-LoggingLibraries
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-RequestMonitor
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HttpTracing
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-Security
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-URLAuthorization
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-RequestFiltering
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-IPSecurity
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-Performance
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HttpCompressionDynamic
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-WebServerManagementTools
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ManagementScriptingTools
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-IIS6ManagementCompatibility
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-Metabase
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HostableWebCore
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-StaticContent
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-DefaultDocument
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-DirectoryBrowsing
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-WebDAV
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ISAPIExtensions
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ISAPIFilter
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ASPNET
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ASP
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-CGI
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ServerSideIncludes
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-CustomLogging
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-BasicAuthentication
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-HttpCompressionStatic
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ManagementConsole
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ManagementService
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-WMICompatibility
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-LegacyScripts
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-LegacySnapIn
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-FTPServer
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-FTPSvc
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-FTPExtensibility
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-WindowsAuthentication
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-DigestAuthentication
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ClientCertificateMappingAuthentication
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-IISCertificateMappingAuthentication
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:IIS-ODBCLogging
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:NetFx3
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:WCF-HTTP-Activation
%windir%\system32\dism.exe /online /quiet /enable-feature /featurename:WCF-NonHTTP-Activation
%windir%\system32\shutdown.exe /r /t 30 /c "System Restart is required for IIS installation to take effect."


Copy all these command and paste in a notepad file and save it as .bat file and your batch file is ready or you can download the batch file from here.

Friday, 22 April 2016

Develop and Install a Windows Service using C#

Download the Sample Project here

What a Windows Service is

  • Enables you to create long-running executable applications that run in their own windows session.
  • Can be automatically started when the computer boots, can be paused and restarted without any user interaction.
  • Easily installable by running the command line utility InstallUtil.exe and passing the path to the service's executable file.
Why a Windows Service?

One of the most common requirements of some businesses is long-running scheduled jobs based on some time interval. For example: sending a newsletter everyday afternoon or send an email alert to the customer for every one hour.

So building a Windows Service could be one of the reliable solutions to do the goal that can do the required job in the behind the scenes without interfering others users on the same computer.

Introduction
This article explains a step-by-step process of developing and installing a Windows Service to do a scheduled job based on a time interval.

Open Visual Studio and from the menus select "File" -> "New" -> "Project...".

A New Project window will open. Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the right hand side and name the project "TestWindowsService" as shown in the following screenshot.




After you click "OK", the project will be created and you will see the design view of the service as shown in the following screen. Right-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or any other name that you want to give it. Then click “click here to switch to code view”.




In the code view, you can see two methods called OnStart() and OnStop(). The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.


Right-click the TestWindowService project, add a new class and name it "Library.cs". This class will be useful to create the methods that we require in the project. If your TestWindowService is a big project, you can create a ClassLibrary project and reference it to your TestWindowService.

Library.cs
Make the class public and declare it as a Static class.

Create a log method (WriteErrorLog) to log the exceptions.


Create one more log method (WriteErrorLog) to log the custom messages.


Scheduler.cs
Now return to our Scheduler.cs file and declare a Timer.



Write the following code in the OnStart() method and timer1_Tick():


Write the following code in the OnStop() method:

Scheduler.cs [Design]
Now return to the Scheduler.cs [Design] and right-click on the editor window then click "Add Installer".


Then you can see that there will be a new file called "ProjectInstaller.cs" as shown in the following.





Right-click on the "serviceInstaller1" and click "Properties".


Change the ServiceName to "Test Windows Service" (or your own name) and StartType to "Manual" (or you can choose "Automatic" if you need this service to be automatic).

Right-click the serviceProcessInstaller1, go to the properties window and change "Account" to "LocalSystem".




Build the project to see the .exe file at the location where you created the solution.


That's all. Your Windows Service is all ready to install in your machine.

Installing the Windows Service
Go to "Start" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" then click "Developer Command Prompt for VS2012".

Type the following command:

cd <physical location of your TestWindowService.exe file>

in my case it is :

cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug


Next type the following command:

InstallUtil.exe “TestWindowService.exe”

and press Enter.


Here you go, the TestWindowService is installed successfully.


How to start the Windows Service
Since we chose StartType = Manual, we must start the Windows Service manually by visiting the "Services and Applications" window in the computer.



Select the Test Windows Service and click "Start" to start the service. Go to the "TestWindowService.exe" location to see the logs.

LogFile.txt
Since we are tracking our Windows Service by writing some logs to a .txt file called LogFile.txt, we can test the working condition of our Windows Service by looking at this log file.



As you can see in the preceding screen, you can find the LogFile.txt file at the physical location that your TestWindowService solution exists.

Click the LogFile.txt to see the logs, whether our service is doing the job that we set it to do for every 30 seconds.

If you look at the preceding log file, we can prove that our Windows Service is running and doing the job that we wanted on a 30 seconds interval.

Stop the Windows Service
To stop the Windows Service, just click "Stop" link in the Services window by selecting our TestWindowService.

Logfile after stopping our service:

Type the following two commands in the "Developer Command Prompt for VS2012" to uninstall the TestWindowService.exe.

  1. cd <physical location of your TestWindowService.exe file>
    and press Enter. In my case it is:
    cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug
  2. InstallUtil.exe /u “TestWindowService.exe”
    And press enter.
    After executing the preceding commands, the TestWindowService will be uninstalled from your computer.
Summary
In this article, I explained how to develop a Windows Service and install it using InstallUtil.exe from a command prompt.

Call .NET object or methods from PowerShell scripts

 

*********************Call System Assembly Class Object/Static Class *****************

PS C:\Users\837853> Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show("Hello World");
OK

***********************Call Customized .NET DLL Class Object**********************

PS C:\Users\837853> [System.Reflection.Assembly]::LoadFile("C:\Users\837853\Umesh\Development\Test\PowerShellExecution\W
indowsFormPowerShellExecution\WindowsFormPowerShellExecution\bin\Debug\WindowsFormPowerShellExecution.dll"); $classname=
New-Object MyClass; $classname.ShowMessage()

Exception calling "LoadFile" with "1" argument(s): "This assembly is built by a runtime newer than the currently loaded
 runtime and cannot be loaded. (Exception from HRESULT: 0x8013101B)"
At line:1 char:39
+ [System.Reflection.Assembly]::LoadFile <<<< ("C:\Users\837853\Umesh\Development\Test\PowerShellExecution\WindowsFormP
owerShellExecution\WindowsFormPowerShellExecution\bin\Debug\WindowsFormPowerShellExecution.dll"); $classname=New-Object
 MyClass; $classname.ShowMessage()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
New-Object : Cannot find type [MyClass]: make sure the assembly containing this type is loaded.
At line:1 char:231
+ [System.Reflection.Assembly]::LoadFile("C:\Users\837853\Umesh\Development\Test\PowerShellExecution\WindowsFormPowerSh
ellExecution\WindowsFormPowerShellExecution\bin\Debug\WindowsFormPowerShellExecution.dll"); $classname=New-Object <<<<
 MyClass; $classname.ShowMessage()
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At line:1 char:263
+ [System.Reflection.Assembly]::LoadFile("C:\Users\837853\Umesh\Development\Test\PowerShellExecution\WindowsFormPowerSh
ellExecution\WindowsFormPowerShellExecution\bin\Debug\WindowsFormPowerShellExecution.dll"); $classname=New-Object MyCla
ss; $classname.ShowMessage <<<< ()
    + CategoryInfo          : InvalidOperation: (ShowMessage:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

******************After Changing the .NET DLL Framework to V2.0*******************

PS C:\Users\837853> [System.Reflection.Assembly]::LoadFile("C:\Users\837853\Umesh\Development\Test\PowerShellExecution\W
indowsFormPowerShellExecution\WindowsFormPowerShellExecution\bin\Debug\WindowsFormPowerShellExecution.dll");  $classname
=New-Object WindowsFormPowerShellExecution.MyClass; $classname.ShowMessage()
GAC    Version        Location
---    -------        --------
False  v2.0.50727     C:\Users\837853\Umesh\Development\Test\PowerShellExecution\WindowsFormPowerShellExecution\Wind...

PS C:\Users\837853> [System.Reflection.Assembly]::LoadFile("C:\Users\837853\Umesh\Development\Test\PowerShellExecution\W
indowsFormPowerShellExecution\WindowsFormPowerShellExecution\bin\Debug\WindowsFormPowerShellExecution.dll");  $classname
=New-Object WindowsFormPowerShellExecution.MyClass; $classname.Welcome("Avik",456988);
GAC    Version        Location
---    -------        --------
False  v2.0.50727     C:\Users\837853\Umesh\Development\Test\PowerShellExecution\WindowsFormPowerShellExecution\Wind...
Returned value: Hello Avik Id: 456988

***********************Check Powershell Vresion in System***************************

PS C:\Users\837853> $PsVersionTable
Name                           Value
----                           -----
CLRVersion                     2.0.50727.5485
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

PS C:\Users\837853> Get-WmiObject -Class Win32_OperatingSystem | Format-Table Caption, ServicePackMajorVersion -AutoSize

Caption                         ServicePackMajorVersion
-------                         -----------------------
Microsoft Windows 7 Enterprise                        1


Check .NET Frame work V4.5 installed or not which is a pre-requisite for PowerShell Version-4 or  Windows Management Framework 4.0


PS C:\Users\837853> (Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -ErrorAction Sile
ntlyContinue).Version -like '4.5*'
True


******************To Update Powershell V2.0 to Powershell V4.0 ********************


******************************Check for Powershell Version *************************

PS C:\Users\837853> $PsVersionTable
Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.18408
BuildVersion                   6.3.9600.16406
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

Common PowerShell Commands(Execution Policy, Enable Remote Managemnt of a System, Get Command Help related to Windows Service)

Download Sample PowerShell Script to Start or Stop a Windows Service

Execution Policy

PS C:\Users\837853> get-executionpolicy
Unrestricted

Set-ExecutionPolicy [-executionPolicy] Policy
        { Unrestricted | RemoteSigned | AllSigned | Restricted | Default | Bypass | Undefined}
            [[-Scope] ExecutionPolicyScope ] [-Force]
               [-whatIf] [-confirm]
Ref- http://ss64.com/ps/set-executionpolicy.html

Enable Remote Managemnt of a System


PS C:\Users\837853> winrm quickconfig
WinRM is not set up to receive requests on this machine.
The following changes must be made:
Set the WinRM service type to delayed auto start.
Start the WinRM service.
Make these changes [y/n]? y
WinRM has been updated to receive requests.
WinRM service type changed successfully.
WinRM service started.
WinRM is not set up to allow remote access to this machine for management.
The following changes must be made:
Create a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this machine.
Enable the WinRM firewall exception.
Make these changes [y/n]? y
WinRM has been updated for remote management.
Created a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this machine.
WinRM firewall exception enabled.

PS C:\Users\837853> winrm quickconfig
WinRM already is set up to receive requests on this machine.
WinRM already is set up for remote management on this machine.

Get Command Help related to Windows Service


PS C:\Users\837853> get-command -noun service
CommandType     Name                                                Definition
-----------     ----                                                ----------
Cmdlet          Get-Service                                         Get-Service [[-Name] <String[]>] [-ComputerName ...
Cmdlet          New-Service                                         New-Service [-Name] <String> [-BinaryPathName] <...
Cmdlet          Restart-Service                                     Restart-Service [-Name] <String[]> [-Force] [-Pa...
Cmdlet          Resume-Service                                      Resume-Service [-Name] <String[]> [-PassThru] [-...
Cmdlet          Set-Service                                         Set-Service [-Name] <String> [-ComputerName <Str...
Cmdlet          Start-Service                                       Start-Service [-Name] <String[]> [-PassThru] [-I...
Cmdlet          Stop-Service                                        Stop-Service [-Name] <String[]> [-Force] [-PassT...
Cmdlet          Suspend-Service                                     Suspend-Service [-Name] <String[]> [-PassThru] [...

Get Status of a Particular Windows Service


PS C:\Users\837853> get-service TestWindowsservice
Status   Name               DisplayName
------   ----               -----------
Stopped  TestWindowsService TestWindowsservice
PS C:\Users\837853> get-service -ComputerName "01hw808400" -Name "TestWindowsservice"
Status   Name               DisplayName
------   ----               -----------
Stopped  TestWindowsService TestWindowsservice

Start of a Particular Windows Service


PS C:\Users\837853> Start-service "TestWindowsService" -Passthru
Status   Name               DisplayName
------   ----               -----------
Running  TestWindowsService TestWindowsService
PS C:\Users\837853> start-service TestWindowsService


Stop a Particular Windows Service


PS C:\Users\837853> stop-service TestWindowsService -Passthru
Status   Name               DisplayName
------   ----               -----------
Stopped  TestWindowsService TestWindowsService

PS C:\Users\837853> stop-service TestWindowsService

Get Date


PS C:\Users\837853> get-date
Tuesday, April 19, 2016 5:26:19 PM

Get Processes in a System


PS C:\Users\837853> get-process
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    544      18     5244       3508   115     0.59   2440 ac.activclient.gui.scagent
    490      15     6160       6628    97     5.62   2264 acevents
     69       4     1892       1072    35     0.08   1728 armsvc
   1127      28    19636      32828   160    27.71   8392 ccmexec
    534      27    28032      24448   237     6.29   9424 CDViewer
    259      15    40276      64916   224    13.31    224 chrome
    199      11    28668      36224   290     2.40   2492 chrome
    258      14    40492      59976   300     7.44   2944 chrome
    206      12    43072      59140   217     9.38   3688 chrome
    102       5     1248       1060    47     0.11   3832 chrome
    153       9    30016       1360   160     1.53   8196 chrome
   1432      36    90852      89320   353   176.86   9396 chrome
    253      13    37912      50720   315     5.16   9872 chrome
    263      14    35356      57028   312     5.82  12136 chrome
    198      12    41236      54396   224     4.87  13004 chrome
     30       4     2080        260    34     0.02   2224 cmd
     26       2     1864        260    21     0.02   4908 cmd
    163      75    26368       3728    79     0.19  13496 CmRcService
    362      14    11932       3472   168     0.36   6412 concentr
     48       5     1248        524    49     0.00    928 conhost
     33       2      612        320    24     0.02   1452 conhost
     31       2      588        400    24     0.02   2156 conhost
     30       4      832        264    21     0.00   5924 conhost
     32       2      616        388    24     0.00   6176 conhost
     51       5     1312        556    50     0.06   7196 conhost
     54       5     2060       1516    50     0.62  10076 conhost
     33       4     1020       3188    34     0.02  14012 conhost
    157       6     2120      11332    60     0.14   6156 cscript
   1462       9     2572       2060    42     4.85    532 csrss
   1080      11     2340       4280    41    49.47    608 csrss
   1149      56   171724     142092   601   157.78   6372 devenv
    269       9     8332       4608    66     2.78   1700 dllhost
    190       9     4104       1648    38     0.62   5824 dllhost
     70       6     2468       1520    71     0.12   7468 Dserui
    455      55    46056      13308   131   104.77  12424 dsSamProxy
    178      10     4576       4688    81     3.32   4280 dsSamUI
     90       5     1712       1756    51     0.03   7696 dwm
    262      77     4092       2056    67     0.48   1808 DWRCS
    107       7     1824       1104    58     0.08   7460 DWRCST
    650      19   110580      18016   288    60.84   3936 EndPointClassifier
     99       6     2236       4572    75     0.14   3284 ErgoCare
   1075      42    75924      41020   295    85.25   7760 explorer
    160       7    16268       1328    43     0.02   5916 fdhost
     76       6     2156       1152    35     0.08   5716 fdlauncher
    416      15    25724      13120   123    25.77   1996 FireSvc
    450      84    12320       2280   117    30.05   1308 FrameworkService
    235      10    19196       4340   136     0.47    164 GoGreenService
    156      10    19176       5764   154     0.75   5144 GoGreenTool
    133       6     1788        532    51     0.41   7960 GoogleUpdate
    239       9     5464       6012    67     9.30    552 HipMgmt
      0       0        0         24     0               0 Idle
    426      24    28216      23876   145     2.67   8556 iexplore
    955      40    43544      40540   275     3.46  11780 iexplore
    293      16     5776       2960    97     0.64   3304 JuniperSetupClient
     74       6     2372        312    55     0.03   6336 jusched
     30       3     1396        932    32     0.00    752 kvoop
     40       4     1604       2740    39     0.19   1424 kvoop
     30       3     1236        296    32     0.02   1460 kvoop
     34       3     1788       2928    37     0.06   2228 kvoop
     36       4     1632       2952    40     0.05   2256 kvoop
     30       3     1160        268    32     0.00   2260 kvoop
   1508      45    10612      10524    51   182.07    664 lsass
    252       5     2332       1932    25    22.37    672 lsm
    595      15    97012      56276   216 8,203.92   3440 mcshield
    326      16     7208       2508   109     0.56   6460 McTray
    241      10     4496       1612    63     0.23   2140 mfeann
    135       7     2136       1432    38     0.95   3528 mfefire
    193       6     4824       4676    52   121.98   1896 mfevtps
    215       9    22404      27572   152     0.42   1236 MSBuild
    149       9     3604       1080    42     0.11   6112 msdtc
    145       9     5064       2564    65     7.24   2416 naPrdMgr
    526      20    57836      35324   270    15.82   9484 nlnotes
     61       5     1404       5368    60     0.05   7868 notepad
   1397     127   229696     127924   854   108.72   7192 notes2
     70       4    11908       1084    66     0.03    688 nsd
    270      13    28188       7016   186    11.67   9180 ntaskldr
     71       4     1740       1240    47     5.21   2680 ntmulti
    223       9    12532       2252   134     0.39   2760 PFERemediation
    281      12    32184       7828   171     1.37   6256 powershell
    398      19    69616      33196   282   100.62   6692 powershell_ise
    174       9    13868      13444   154     0.11  13500 PowerShellExecution.vshost
    148       6    13300       2092   116     0.17   8112 PresentationFontCache
    299      18     8140       6324   142   100.62   5160 Receiver
     85       5     1744        552    50     0.70   6440 redirector
     22       2      836        248    16     0.02   3752 reg
    637      29    99516      32796   651     3.51   2812 ReportingServicesService
     32       4      916       2720    40     0.06  13492 scalc
    231      46    27532      30864   208     0.41   3508 SCNotification
    113       4     3076       6160    39     0.16  12788 SearchFilterHost
   1110      35    49676      30500   161   271.36   5900 SearchIndexer
    287       6     3072       3536    46     3.78  12540 SearchProtocolHost
    263      14    14104       4412   180     0.45   6632 SelfServicePlugin
    377      16     7944       5452    48    95.97    648 services
     32       1      316        176     3     0.05    344 smss
     61       7     1884       4792    64     0.09   7140 soffice
    387      32    68912     117332   348    29.20   5384 soffice.bin
    406      16     9896       8008    88     9.45   1512 spoolsv
     94       6     2064        904    25     0.05   2932 sqlbrowser
    522      90    81772      12944   337   648.75   2360 sqlservr
    641      97   220912      82664   488    40.84   2576 sqlservr
     86       5     2492       1012    31     0.11   2996 sqlwriter
    145      11     4296       1828    76     0.16   6512 StikyNot
    109       5     2480       1008    62     0.08   1192 SUService
    406       8     4708       3240    62    10.55    828 svchost
    478      43     5700       4340    52    10.36    908 svchost
    537      27    17076       8824    72   123.43   1000 svchost
    410      12   115808     106972   208   176.76   1040 svchost
    770      24    11508       9800   105    25.55   1064 svchost
   2929      49    66356      56656   623   457.27   1096 svchost
    604      20    12572       6512    82    22.48   1356 svchost
    411      16     6072       5376    47     8.88   1544 svchost
    344      26    10948       4444    63     4.24   1584 svchost
     98       6     4288       1432    34     0.11   1768 svchost
    154       8     4464       1512    36     0.06   2036 svchost
    160       7     9528       8428    42     0.59   3324 svchost
    312       9     3500       1556    50     0.22   3888 svchost
    215       8     5836       4360    57     3.76   5744 svchost
    106      15     2508        936    27     0.16   6068 svchost
   5750       0       48       1396     4               4 System
    101       4     1260       1600    24     0.12   7652 taskeng
    268      17    12584       3780    98     1.33   7452 taskhost
    181       6     6616       8848   112     0.09   9400 TestWindowsService
    993      30    50772      25980   310    11.70   3200 TFSJobAgent
    129       9     2952       2504    75     2.64   6284 UdaterUI
    344      14    10212       2520    90     2.50   1628 vstskmgr
    308      14    14984       5140   111   143.93   3348 wepsvc
    366      17     7924       6488   119     1.12   1160 wfcrun32
    714      32    62684      44288   245    37.38  13640 wfica32
     83      12      956        344    33     0.12    596 wininit
    112       4     2244        404    40     0.37    756 winlogon
    138       7     6248       9664    39     0.61   1412 WmiPrvSE
    335      11    17508      13076   117    40.12   6276 WmiPrvSE
    315       8     8084      10228    54     7.85   7928 WmiPrvSE
    125       5     2204       2704    27     0.06   7932 WmiPrvSE
    138       6     6680       6144    42     3.71  13276 WmiPrvSE
    227      11     3512       2860    86    10.16   5516 wscript
    193       4     1288       1684    27     0.33    784 WUDFHost



 

Thursday, 21 April 2016

Execute a Powershell script file in the local Computer or in a remote Computer/Server using C#

Condition:- The Powershell Script file should be available in the machine where it needs to be executed. For example if you want to execute a Powershell script file in System A, then the script file should be there in the local disk of System A.

If you want to execute a Powershell script file in a Remote system, then it must be there in the local disk of the Remote System. If the script file is not there in the Remote System, then you have to copy the script file from the System A(from which you are executing the script in the Remote Sytem using C# code) to the Remote System as done in the following code, but for that the Application account needs to have Admin Right in the Remote System for the Remote Connection.

Download the Sample project here

I have added a class PowerShellExec which contains two public method, one for Remote execution and another for execution in the local system.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.IO;

namespace PowerShellExecution
{
    public class PowerShellExec
    {
        public bool RunPowerShellScript(string scriptFullpath, out string output, out string errors)
        {
            errors = string.Empty;
            try
            {               
                var runspace = RunspaceFactory.CreateRunspace();
                return RunPowerShellScriptInternal(scriptFullpath, out output, out errors, runspace);
            }
            catch (Exception e)
            {               
                errors += "Error occurred while Creating Runspace: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
                output = string.Empty;               
                return false;
                throw e;
            }
        }

        public bool RunPowerShellScriptRemote(string scriptFullpath, string computer, string username, string password, out string output, out string errors)
        {
            errors = string.Empty;
            try
            {               
                var filename=Path.GetFileName(scriptFullpath);
                var credentials = new PSCredential(username, convertToSecureString(password));
                //port – Thanks to the blog post at
http://blogs.msdn.com/b/wmi/archive/2009/07/22/new-default-ports-for-ws-management-and-powershell-remoting.aspx
                //we know what port numbers PowerShell remoting uses. 5985 if you are not using SSL, and 5986 if you are using SSL
                var connectionInfo = new WSManConnectionInfo(false, computer, 5985, "/wsman", "
http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credentials);
                var runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                var remoteScriptFullpath = "
\\\\01hw894947\\D$\\Temp\\" + this.GetType().Module.Name + "\\" + Guid.NewGuid() + "\\";
                remoteScriptFullpath = Path.GetFullPath(remoteScriptFullpath);
                if(!Directory.Exists(remoteScriptFullpath))
                {
                    Directory.CreateDirectory(remoteScriptFullpath);
                }               
                remoteScriptFullpath += filename;
                File.Copy(scriptFullpath, remoteScriptFullpath,true);
                return RunPowerShellScriptInternal(remoteScriptFullpath, out output, out errors, runspace);
            }
            catch (Exception e)
            {
                errors += "Error occurred while Remote System Connection: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
                output = string.Empty;               
                return false;
                throw e;
            }

        }
        private System.Security.SecureString convertToSecureString(string password)
        {
            System.Security.SecureString secure = new System.Security.SecureString();
            try
            {
                if (!string.IsNullOrEmpty(password))
                {
                    foreach (char c in password)
                    {
                        secure.AppendChar(c);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + ex.InnerException);
                throw ex;
            }
            return secure;
        }

        private bool RunPowerShellScriptInternal(string scriptFullpath, out string output, out string errors, Runspace runspace)
        {
            bool isExecutionSuccessful = true;
            output = string.Empty;
            errors = string.Empty;
            Collection<PSObject> results = new Collection<PSObject>();
            Pipeline pipeline = null;
            StringBuilder stringBuilder = new StringBuilder();
            try
            {
                runspace.Open();
                pipeline = runspace.CreatePipeline();
                var cmd = new Command(scriptFullpath);
                pipeline.Commands.Add(cmd);
                pipeline.Commands.Add("Out-String");
                results = pipeline.Invoke();

                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }

                if (pipeline.Error.Count > 0)
                {
                    errors += String.Join(Environment.NewLine, pipeline.Error.ReadToEnd().Select(e => e.ToString()));
                    isExecutionSuccessful = false;
                }
            }
            catch (Exception e)
            {

                errors += "Error occurred in PowerShell script: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
                isExecutionSuccessful = false;
                throw e;
            }
            finally
            {
                output = stringBuilder.ToString();
                pipeline.Dispose();
                runspace.Dispose();
            }
            return isExecutionSuccessful;
        }
    }
}



Then I added the following code to my Program.cs file in main method to call the methods of above class.

For Execution of PowerShell script file in the local System

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.IO;

namespace PowerShellExecution
{
    class Program
    {
        static void Main(string[] args)
        {
            PowerShellExec ps = new PowerShellExec();
            var scriptFullpath
=@"C:\Users\837853\Desktop\Powershell POC\Script.ps1";           
            string errors=string.Empty;
            string output=string.Empty;
            var success = ps.RunPowerShellScript(scriptFullpath, out output, out errors)
            if (success)
            {
                Console.WriteLine("Local Execution Successful.");
                Console.WriteLine(output);                               
            }
            else
            {
                Console.WriteLine(errors);
            }
            Console.ReadKey();
        }
    }

}

For Execution of PowerShell script file in a Remote System

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.IO;

namespace PowerShellExecution
{
    class Program
    {
        static void Main(string[] args)
        {
            PowerShellExec ps = new PowerShellExec();
            var scriptFullpath
=@"C:\Users\837853\Desktop\Powershell POC\Script.ps1";
            var computer = "01hw894947";
            var username = @"INDIA\740471";
            var password = "
Apr@2016";
            string errors=string.Empty;
            string output=string.Empty;
            var success = ps.RunPowerShellScriptRemote(scriptFullpath, computer, username, password, out output, out errors);


            if (success)
            {
                Console.WriteLine("Remote Execution Successful.");
                Console.WriteLine(output);                               
            }
            else
            {
                Console.WriteLine(errors);
            }
            Console.ReadKey();
        }
    }

}
 

References