Access Network Location – PowerShell

In order to access a network location in PowerShell, we need to temporary map it to a drive locally, which we can then use as a reference for our further operation.

For ex, here, I want to copy a SharePoint package from a shared network location to my local machine.

If (!(Test-Path Z:))
{
 write-host "Attempting to map network drive, Z:" -foregroundcolor Magenta
 
 $map = new-object -ComObject WScript.Network
 $map.MapNetworkDrive("Z:", "\\lpdl-piyushk\sharedFolder", $true, "lpdl-piyushk\username", "Password")
}
else
{
 write-host "Z: mapping already exist" -foregroundcolor Green
}

# Copy the package from network location to local drive
write-host "copying wsp file" -ForegroundColor Magenta

Copy-Item Z:\SharePointWebPart.wsp P:\Piyush\SharePointWebPart.wsp -force

I have mapped the network location to Z: which is then used as a source location.

TypeScript New Project Error

I was trying to create a new TypeScript project in Visual Studio 2015. As soon as I hit the OK button, Visual Studio would crash. I then checked it with a Console Application template and everything seemed perfectly fine then. Again when I tried to create a new TypeScript project, Visual Studio crashed yet again!

Faulty TypeScript Version

The issue, as it turned out was, that I was using an older version of the TypeScript, 1.6.3.0, and I needed to update it. Since I had not used TypeScript before, I never bothered to check it’s version history. Nevertheless, I then decided to update it from the Visual Studios Extension and Updates UI to version, 1.7.4.0 and, the issue got resolved.

New TypeScript Version

TypeScript Update Setup

 

Schedule a PowerShell Script to run on Windows Startup

By default, ps1 files open with the default text-editor. So mere putting it in the startup folder will only open the file at the startup instead of them actually getting executed. In order to execute the same, we need to trigger a startup job which will fire the PowerShell in the non-interactive mode with the file path as argument. Following are the steps:* Open the Windows PowerShell in admin mode.

* Create a new job trigger. Here, I am introducing a delay of 10 mins.

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:10:00

* Schedule the job

Register-ScheduledJob -Trigger $trigger -FilePath C:\Some-Path\StartStopServices.ps1 -Name StartStopServices

View the scheduled job

* Open Task Scheduler and navigate to Microsoft => Windows => PowerShell. You can find here, the newly scheduled job.

* Open its properties. Since, the script will check the state of some Windows Services on startup. I’ll select the ‘Run with highest privileges‘ option.

* Go to the Action tab and select Edit Action. Here, you can see that it’s the PowerShell, which will be fired at the startup, and it contains the script path as argument along with some other properties.

* Finally, at the time of saving, admin password box will be prompted. This is because, I have marked the job to run with the highest privileges.

Start, Stop & Re-Start Windows Service from PowerShell

Start

start-service FIMService

 

Stop

stop-service FIMService

 

Restart

restart-service FIMService

FIMService is the Forefront Identity Manager Service. You can replace this name with the name of the service upon which you’d like to perform any of the above action.

Here’s a zip file which contains the following ps1 script and a csv file.The script will loop through the associated csv file and as per the config, will start, stop and re-start the given service(s). It will also create a Logs folder in the directory from where the script will be executed. All the logs pertaining to the current operation will be stored in this Logs directory.

 



Function LogMessage($strMsg, $lgFlNm)
{
	$strMsg | out-file -Filepath $lgFlNm -append
}

$filePath = [System.IO.Path]::Combine($PSScriptRoot, “config.csv”)
$logFilePath = [System.IO.Path]::Combine($PSScriptRoot, “Logs”)

$logFileName = [System.IO.Path]::Combine($logFilePath, ("ServiceLog_" + [string](get-date -format "yyyyMMdd_hhmmtt") + ".txt"))
$configFile = Import-Csv $filePath

foreach ($servc in $configFile){
	$servc | ForEach-Object {

		try{
			if([String]::IsNullOrWhiteSpace($_.Start) -ne $true){
				LogMessage (“************************************************************”) $logFileName
				LogMessage (“Start:: “ + $_.Start) $logFileName
				LogMessage (start-service $_.Start -passthru *>&1) $logFileName
			}
		}
		catch{
			LogMessage (“Error:: “ + $_.Exception.Message) $logFileName
		}

		try{
			if([String]::IsNullOrWhiteSpace($_.Stop) -ne $true){
				LogMessage (“************************************************************”) $logFileName
				LogMessage (“Stop:: “ + $_.Stop) $logFileName
				LogMessage (stop-service $_.Stop -force -passthru *>&1) $logFileName
			}
		}
		catch{
			LogMessage (“Error:: “ + $_.Exception.Message) $logFileName
		}

		try{
			if([String]::IsNullOrWhiteSpace($_.Restart) -ne $true){
				LogMessage (“************************************************************”) $logFileName
				LogMessage (“Restart:: “ + $_.Restart) $logFileName
				LogMessage (restart-service $_.Restart -PassThru *>&1) $logFileName
			}
		}
		catch{
			LogMessage (“Error:: “ + $_.Exception.Message) $logFileName
		}
	}
}

Log Messages from a Command in PowerShell

Objective

When we run a cmdlet directly in PowerShell, any error, warning, or info regarding the same gets displayed in the console.

Here, I also want to capture the same messages but while running a ps1 script so as to log them down in a separate file. Since, I’ll schedule the script to always run on machine startup, cmdlets like, Start-Transcript & Stop-Transcript won’t be of any help as I’ll have to run the script in -NonInteractive mode of PowerShell.

Why -passthru

Before getting into the solution part, I’d first like to talk about the Powershell parameter, -passthru. -passthru is for the cmdlets that do not return any data. Here, in the current example, I am using the the cmdlet, start-service to start a windows service. By default, it does not return anything and silently continues except, for errors. If I add -passthru parameter to this cmdlet then, a service object is returned containing all the details of the service upon which the cmdlet is executed. Now I can use this object to track the status of the service and consequently log them down.

Solution

So -passthru will return the object which in turn I can use for logging. However, I still need to redirect this output to a file. To do that, I’ll run the following cmdlet

start-service SPTimerV4 -passthru *>&1

This will return the stream which can be easily redirected to a file. Mission accomplished!

Explanation

*>&1 is a Windows PowerShell redirection operator which sends all output types (*) to the success output stream, So weather the command resulted in an error or it ran successfully, every thing is now getting captured and subsequently logged down.

There are other redirection operators as well. They are defined in the following technet article,
https://technet.microsoft.com/en-us/library/hh847746.aspx

Sencha Ext Js v/s Telerik Kendo UI

Very recently, I got a chance to get my hands on the trials of both, ExtJs 6 and Kendo UI. Before this, I had some working experience on ExtJs 3.4 (free version). So the basic model was somewhat clear to me. Must say, that it also helped me in quickly getting a grip on Kendo UI as well, as very much like ExtJs, it is also build on the MVVM model.

What I did was, that I build a simple drag & drop control using both the frameworks to get the working idea. It was a simple control comprising of two div/container where a user can drag/drop items back and forth from 1 container to another. Additionally, he can also re-arrange the order of items within the same container again with drag/drop only i.e., no buttons were involved.

At the end of the day, I won’t say whether a given framework emerged superior than the other, but while working upon them, some very clear and contrasting features caught my attention. Following is a comparison table highlighting the most contrasting features of the two, that were obvious to me.

Si No.

ExtJs 6

Kendo UI

Comments

1 IE Support Classic: IE8+ (Strict DOCTYPE)  
Modern: IE11+
Desktop: IE7+
Mobile: IE10+
Applications in ExtJS 6 can be developed either in Classic or Modern mode. Classic is desktop version which does not support features like touch and swipe. Modern supports touch functionality.

Kendo UI has only 1 mode which supports both desktop and mobile features, so no choice of types here. Some of its features like exporting to excel and pdf are supported from IE 8 onward.

Currently, there are users for IE7, IE8, IE9, etc. Personally I believe, that with the advent of Windows 10, Microsoft will be able to bring all its user base to the same browser platform, Edge. If that is achieved, we may not need a separate section for IE support anymore as Edge is as powerful as any other modern browser, maybe slightly more!

2 Rich Set of Controls Yes Yes ExtJS has probably more widgets than Kendo-UI.
3 FootPrint Large Small This is based on the current drag/drop control I used for this comparison. ExtJs adds a lot more HTML components for the same TreeView as compared to Kendo-UI. While Kendo-UI uses the HTML

    inside a parent table, ExtJS renders a number of Divs inside a parent table where each node is again bundled inside a separate table element, This arrangement may not have much impact on smaller applications but on a single web page with lots of UI widgets, Kendo-UI got to be faster.
4 Drag and Drop of multiple items Yes No Telerik has confirmed that there widget supports drag and drop of only 1 item at a time.
5 Code styling & maintenance Pure MVVM [Model View ViewModel] framework. It means once its concept is clear maintenance and development is uniform, enhancing the code quality. No HTML designing is required. Kendo-UI widgets are implemented by MVVM framework but functionalities have to be added via jQuery. You have to design your HTML as well. If not developed properly, maintenance can become an issue in the future. Basically, depends on the developers. If developed properly, jQuery and HTML is indeed the core of many small to large scale web developments and also offers a very strong and powerful web community.
6 jQuery support Yes, but need to chiefly work within the walls of ExtJs which is mostly enough. Largely depends upon jQuery. One of the features they have implemented to make it light weight No framework is 100% perfect. Having a proper jQuery support signifies that in future any 3rd party component can also be integrated which may or may not have been built on MVVM model.
7 Pivot-Grid Yes. Yes For ExtJs, Pivot-Grid is supported from its latest version only, which is, ExtJs6.
8 Customizing default themes Offers 6 different themes by default. Customizing these existing themes can be cumbersome. Offers 17 themes by default out of which 12 can be easily modified online. Again, not 100% design can be changed, but most of it is easily configurable using there online theme generator and applying our own custom css. http://demos.telerik.com/kendo-ui/themebuilder/ Sencha claims that themes can also be modified using there another paid product, Architect 3.
9 Responsive design Some level of responsiveness can be achieved. Claims to be completely responsive as it is built leveraging bootstrap css. Online demos are responsive. As of now, achieving complete responsiveness is not possible with ExtJs because of its architectural limitations. They still have two separate development models for mobile and desktop.
10 Learning Curve Steep. It will certainly take a while for a new developer to get accustomed to it. By far and large, for a web developer, not much of an extra effort is needed to learn it. Need clear understanding of MVVM though. Once the fundamentals are clear, developing in ExtJs shouldn’t be an issue.
11 Pricing A minimum of 5 license has to be bought. Single licensing model is available. Both of them seems to have different support and upgrade options.