All posts by Thiyagu

How to get the array as input using Powershell

To read an array into Read-Host (get the array as input), you would need to put it in a loop because anything entered into Read-Host will be interpreted as a string. To make output in new line we can use $OFS, which is a special variable in PowerShell . OFS stands for Output field separator . You would use this to separate object/Array.

The .split() method is self explanatory, the .trim() method will simply remove leading and trailing spaces and leading and trailing line breaks

Example #1 : Getting Value as an Array by Looping

$arrayInput = @()
do {
$input = (Read-Host "Please enter the Array Value")
if ($input -ne '') {$arrayInput += $input}
}
#Loop will stop when user enter 'END' as input
until ($input -eq 'end')

$arrayInput

OUTPUT:

Example 2# : Alternative approach for handling the multiple inputs without loop.

#Set New line using OFS special Powershell variable
$OFS = "`n"
#Externally set input value as string
[string[]] $_ServerList= @()
#Get the input from the user
$_ServerList = READ-HOST "Enter List of Servers"
#splitting the list of input as array by Comma & Empty Space
$_ServerList = $_ServerList.Split(',').Split(' ')
$OFS + $_ServerList

Output:

How to move files from one location to another location using PowerShell

In this article, Let me show you how to move files from one location to another location using PowerShell script. The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider.

Move-Item : Cannot create a file when that file already exists.

Example:1 Moving single files/folders

In the PowerShell window, type the command below and press ENTER. After the –path parameter, type the path of the file on your local PC that you want to copy, and after the –destination parameter, type the path of the destination folder. In the example below, I’m moving a file called URL_List.txt from the Source File Path folder to the Destination File Path folder.

$_SourcePath = "D:\BLOG\Power Shell\Examples\Source File Path\URL_List.txt"
$_DestinationPath = "D:\BLOG\Power Shell\Examples\Destination File Path"

Move-item –path $_SourcePath –destination $_DestinationPath

OR we can directly mention the path of files location without -path Keyword

Move-item $_SourcePath $_DestinationPath

Example:2 Moving all the item which created today.

From below code, we getting all files and folder which created today and move from “Source File Path” folder to “Destination File Path” folder.

get-childitem -Path "D:\BLOG\Power Shell\Examples\Source File Path" -Recurse |
Where-Object {$_.CreationTime -gt (Get-date).Date} |
move-item -destination "D:\BLOG\Power Shell\Examples\Destination File Path"

Also, by default, Get-ChildItem does not move hidden files. To move hidden files, use the Force parameter with Get-ChildItem.

Example:3 Moving the files based on File Type (extension)

I had created $_FileType array which contains the list of file types that need to move. After execution, all .html and .txt files will move from source to destination folder. Please refer to the snapshots to under stand the before and after the script execution

#location of starting directory
$_sourcePath ="C:\Users\dotnet-helpers\Desktop\SourcePath"
#location where files will be copied to 
$_destinationPath = "C:\Users\dotnet-helpers\Desktop\DestinationPath";
#Array of extension that need to move from source path
$_FileType= @("*html*", "*.*txt")

Get-ChildItem -recurse ($_sourcePath) -include ($_FileType) | move-Item -Destination ($_destinationPath)

OUTPUT:

Before Execution: Source Folder/Destination Folder

After Execution: Source Folder/Destination Folder

 

What do you think?

I hope you have an idea of how to move the files from one location to another location using the Powershell script. I would like to have feedback from the readers of my posts. Your valuable feedback, question, or comments about this article are always welcome.

 

KnockoutJS – Visible Binding

As the name specifies this binding makes the related DOM element to be visible or hidden based on the value passed in the binding.

Syntax

visible: <binding-condition>

Parameters

When the parameter transforms into false (like false/0/null/undefined), then the binding sets display:none for the element to making it as hidden.

When the parameter transforms into true (true/non-null/array ), the binding removes the element’s display value and makes it visible.

Example

<html>
<head>
<title>KnockoutJS Computed Observables</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.4.2.js"></script>

</head>
<body>
<a href="#" data-bind="click: toggleVisibility">Show/Hide Text</a>
<br/><br />
<div data-bind="visible: shouldShowMessage">
Welcome To Dotnet-helpers.com Learning Curve
</div>

<script type="text/javascript">
var viewModel = function () {
this.shouldShowMessage = ko.observable(true);
this.toggleVisibility = function () {

this.shouldShowMessage(!this.shouldShowMessage());
alert('shouldShowMessage status ' + this.shouldShowMessage());
};

};
ko.applyBindings(new viewModel());
</script>

</body>
</html>

OUTPUT

 

What do you think?

I hope you have idea of how to use KnockoutJS visible or hidden based on the value passed in the binding. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

KnockoutJS – Controlling text and appearance

The “text” binding

The text binding causes the associated DOM element to display the text value of our parameter. This is used in text-level DOM elements such as div,span. The text binding accepts any data type and parses it into String before rendering it.

Syntax:

text: <binding-value>

Parameters

  • Knockout sets the element’s content to a text node with your parameter value. And if there is any previous content then it will be overwritten.
  • If this parameter is an observable value, then the binding value will update the element’s text whenever the value changes.  If the parameter isn’t observable then it will only set the element’s text once and will not update again.

Example

<html>
<head>
<title>KnockoutJS Computed Observables</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
</head>
<body>
<span data-bind="text: myMessage1"></span><br /><br />
<span data-bind="text: myMessage"></span>

<script type="text/javascript">
var MyModel = {
myMessage: ko.observable("myMessage: IntialMessage"),
myMessage1: ko.observable("IntialMessage - Welcome to dotnet-helpers.com")
};

MyModel.myMessage("myMessage1 : Welcome to KO Learning curve session");
ko.applyBindings(MyModel);
</script>
</body>

OUTPUT

 

What do you think?

I hope you have idea of Controlling text and appearance. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

 

How to check response code from a website using PowerShell

In this post we will discuss about how to check the response code from a website. In this article, we’re going to cover how to build a PowerShell function that will query a specific URL and attempt to find out if that URL is working fine or not. To get started, let’s construct a function for this task called CheckSiteURLStatus with a single parameter called URL.

Net.WebReques makes a request to a Uniform Resource Identifier (URI). This is an abstract class.

Using Net.WebRequest class (which is under the System.Net namespace), we get a response from a web server. Unlike the Net.WebClient class, you will not be able to download the site page. However, using Net.WebRequest class, you can get a response code and also see what type of web server is being used to host the site. The WebRequest class has a static method called Create in which we can pass a URL to invoke a HTTP,  We’ll add the code to create the request into our function as shown below.

[string] $_URL = 'https://dotnet-helpers.com'
function CheckSiteURLStatus($_URL) {
try {
$request= [System.Net.WebRequest]::Create($_URL)
$response = $request.getResponse()
if ($response.StatusCode -eq "200") {
write-host "`nSite - $_URL is up (Return code: $($response.StatusCode) - 
$([int] $response.StatusCode)) `n" -ForegroundColor green 
}
else {
write-host "`n Site - $_URL is down `n" ` -ForegroundColor red
}
} catch {
write-host "`n Site is not accessable, May DNS issue. Try again.`n" ` -ForegroundColor red
}
}

CheckSiteURLStatus $_URL

Based on the response code, the condition will execute and write on the console.Finally, we’ll need to dispose of the response after we’re done to clear it from memory which would finish it off to make it look like this:

OUTPUT

What do you think?

I hope you have idea of how to check the Website status using Powershell script. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

 

Difference between write-host and write-output in powershell

One of the great benefits of PowerShell is its pipeline mechanics that enable the output of one command to be passed to the next command in the pipeline. That output is not sent as basic text but rather the actual objects generated from a command are sent in the native object format to the next command and this is enabled for all commands.

Example: 1

If you open a PowerShell window and type the following commands the result is the same for both, Let us test this by the below cmdlet.

PS C:\> Write-Host ("Hello " + $env:USERNAME)
Hello Aadharsh

PS C:\> Write-Output ("Hello " + $env:USERNAME)
Hello Aadharsh

If we look at the above script, it like they are the same but in reality, they are working in very different ways. Let us discuss more to understand this more.

Example: 2

From Example 1, we think that it seemed to achieve the same result for both Write-Output and Write-Host but we have differences between these two cmdlets. This can be demonstrated in more detail in this example. Write-Output sends the output to the pipeline. From there it can be piped to another cmdlet or assigned to a variable. Write-Host sends it directly to the console

$a = 'Testing Write-OutPut' | Write-Output
$b = 'Testing Write-Host' | Write-Host

Get-Variable a,b

From the above example, we can able see the Write-Output cmdlet has passed the value to the next process but Write-Host just directly writes to the host and nothing has to send forward to the next cmdlet. 

In simpler, if you possibly want to write data to the screen, but also want the data to be passed down the pipeline to further commands, then use Write-Output.  Write-Host does not output data to PowerShell Object flow Engine but rather, as the name implies, writes directly to the host and sends nothing to the PowerShell engine to be forwarded to commands later in the pipeline.

 

How to Append Data to a Text File Using PowerShell

 Here’s we can discuss on how to add text to the end of a text file using the Add-Content cmdlet using PowerShell.  In our example let’s add “This is the last line” to the end of a file using add-content cmdlet to append data to a text file.

Add-Content "C:\dotnet-helpers\DummyfiletoDelete.txt" "This is the last line"

The above example above adds the text to the last line of the text, it doesn’t actually create a new line. We can use an escape character to tell PowerShell to add a carriage return, new line… while appending the text in existing file.

Escape characters:

‘n — New line
‘t — Horizontal tab
‘’ — Single quote
‘” — Double quote
‘0 — Null
‘a — Alert
‘b — Backspace
‘r — Carriage return

Append Text using Escape characters:

Add-Content -Path "C:\dotnet-helpers\DummyfiletoDelete.txt" -Value "`r`nThis is the last line".

The above example append the “This is the last line” as a new line at end of the text file with help of ‘n and’ r

Add-Content -Path "C:\dotnet-helpers\DummyfiletoDelete.txt" -Value "This is the last line added from $env:computername system"

 

 OUTPUT:

 

How to Delete a Folder or File using PowerShell

Use PowerShell to Delete a Single File or Folder

Before start executing the Delete powershell command we need to make sure you are logged in to the server or PC with an account that has full access to the objects you want to delete.

# Using PowerShell commnads to delete a file
Remove-Item -Path "C:\dotnet-helpers\DummyfiletoDelete.txt"

The above command will excute and delete the “DummyfiletoDelete.txt” file which present inside the “C:\dotnet-helpers” location.

Use PowerShell to Delete all File and Folders inside the folder

We can also use wildcard ‘*’ characters to remove multiple items. For example, this command removes all the files in “C:\dotnet-helpers\*.*”

# Using PowerShell commnads to delete all file
Remove-Item -Path "C:\dotnet-helpers\*.*"

# Using PowerShell commnads to delete all file and folders
Remove-Item -Path "C:\dotnet-helpers\*.*" -recurse

Recurse drills down and finds lots more files. The –recurse parameter will allow PowerShell to remove any child items without asking for permission. Additionally, the –force parameter can be added to delete hidden or read-only files.

Using -Force command to delete files force fully

# Using PowerShell commnads to delete all file force fully
Remove-Item -Path "C:\dotnet-helpers\*.*" -Force

The above command will delete all hidden or read-only files from the location “C:\dotnet-helpers\”

ASP.NET Core: My First New Project

In this tutorial section, we will discuss how to create a new project in Visual Studio using ASP.NET CORE. Once you have installed the Visual Studio 2015 tooling, you can start building a new ASP.NET Core Application .

STEP: 1

Once you have installed the Visual Studio 2015 tooling, you can start building a new ASP.NET Core Application using File → New Project menu option.

STEP: 2

On the New Project dialog box, you can able to see the three different templates for Web projects as shown below. After selecting ASP.NET Core Web Application (.NET Core),specify the location and name for your ASP.NET Core project click OK

ASP.NET Web Application − The simple ASP.NET application templates .

ASP.NET Core Web Application (.NET Core) − This will start you with a crossplatform compatible project that runs on the .NET Core framework.

ASP.NET Core Web Application (.NET Framework) − This starts a new project that runs on the standard .NET Framework on Windows.

STEP: 3

In the below dialog box, you can select a specific template for the ASP.NET application from the available ASP.NET Core Templates. Here, we select and start with an empty template. This would help us build it from scratch. Let us select the Empty template, turn off the Host in the cloud and click OK.

Now the Visual Studio will launch your new project. In the Solution Explorer window, you will see all the files that are in this project.

STEP: 4

Now you can run your application by pressing Ctrl+F5 or by going to the Debug menu. After going to the Debug menu, select Start Without Debugging.

STEP: 5

We can see it display only Hello World! This runs on http://localhost:44432. In your window system tray, you can also see that IIS Express is running as shown below.

What do you think?

I hope you have idea about creating first ASP.NET CORE application. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.