Friday, July 10, 2020

Powershell Walkthrough



Courtesy  to Wayne Sheffield for  posting  blogs " A MONTH OF POWERSHELL"  with drafting an inspiration line " what better way is there to learn a subject than to write about it?” .
Saying that i thought to shadow the same blog to learn powershell encouraging everyone to do the same. 
I'm drafting these topics in a self way to understand in the FAQ format. 
What is PowerShell ?
Powershell is an Microsoft's command/scripting tool to automate  the process and adminster the server. It's designed  as a .net object based scripting environment . Everything in powershell is an object even the output. 

How do you launch PowerShell ?
Powershell can be launched by Start Menu/Programs/Accessories/Windows powershell or Windows Powershell ISE.

What is the command to see all the process running in your machine ?
Get-Process

If its need to filter with sqlserver then the below command can be used.
Get-Process | Where-object Processname -Eq 'sqlservr'

The pipe sends the output (remember that output is an object) from the cmdlet running on  the left side to the cmdlet running on the right side .
The above cmdlet also introduces Comparison operator (-).


Command to get the list of available drives ?
Get-PSDrive 
This returns the list of all the physical drives,HKCU & HKLM registry hives, a drive to the windows environment variables and others.

Explain about Variables in PowerShell ?
The syntax of the variable is the name of the variable proceeded by a dollar sign($) . Values are assigned to variables with equal sign (=). When the variable is assigned and values are passed to it , an appropriate .net data type is created.
For eg . $Myvariable=123 , here myvariable is the variable name and 123 is the values with system.int32 data type.

String variables are assigned by using quotation marks. Powershell accepts both single or double quotation marks . However there is a difference in how they operate. Single quotation marks use the literal values inside the quotation marks as the string. Double quotation marks will perform string substitution of other variables in the string.
Eg. $i=123
$s='hello'
S2="$i $s"
$s2
executing this will produce the below result.  
123 hello

You can use the long concatenation build string.
$q="select top 100"
$q=$q + ", Firstname "
$q=$q +", Lastname"
$q=$q +" from MyTable;"

 Or it can be used with here-string
$q=@"
select Firstname,Lastname from Mytable;
"@
$q
where using the here-string ,the string starts with @ and ends with @ which must be with a line itself. What's really neat with using a here-string is that PowerShell respects that all the line breaks,quotation marks (single or double) or white space withing the string that maintains that in the variable.

Special variables :
Powershell has a few variables that are automatically created.

Get-help about_automatic_variables --> Variables that store PowerShell state information.
Get-Help about_preference_variables --> Variables that customise PowerShell behaviour.
Get-Help about_environment_variables--> working with windows environment variables within powershell.

Explain Arrays
Arrays are data structures designed to store a collection of items, which can be of same data type or of different data types. Items to arrays can be assigned in a few different manners.

$A= 5 4 3 2 1      #specific items

$B=6..10  #range,Integars only
$c=@("String1","String2","String3") #Specific Seperate String Items
$D=@()
[array] $E="a;e;i;o;u;y" -split ";" #Specific Seperate String Items

Explain Hash tables ?
A hash table is a simply a Name-value pair.  The following example shows creating and adding to the hash table.
$z=@{"Colarado", ="Denver"; "Virginia"= "RichMond";
#z.Add{"Alaska","Fairbanks"}

Explain about security feature in powershell ?
Powershell  by default is in restricted mode. If any scripts to be executed with .ps1 file must have the right execution policy set. 
Below are the different execution policies in powershell.

Restricted --> Doesn't load configuration files or run scripts. This is the default execution policy.
AllSigned--> Requires that all scripts and configuration files must be signed by a trusted publisher,including scripts that you write on the local computer.
RemoteSigned--> Requires that all scripts and configuration files downloaded from the internet be signed by a trusted publisher.
Unrestricted--> Loads as scripts and configuration files. If you run an unsigned script from an internet then you are prompted for permission to run.
ByPass--> Nothing is blocked and there are no warnings or promps.
Undefined--> Removes the current assigned exeuction policy from the current scope. This parameter will not remove an exeuction policy that is set in a group policy settings.

To set a execution policy.
Set-ExecutionPolicy RemoteSigned


param(
  [string]$MyVariable
)


Command line Arguments
You can provide your script with command-line arguments by including a PARAM script block as the very first executable code in your script. A param script block would look like:

param(
  [string]$MyVariable
)

Script Block :
A script block represents  a precompiled block of script that can be used as a single unit. In powershell, the boundaries of script block is designated with curly -Brace characters. They can be nested and used anywhere.

Functions :
Functions are a pre defined script block that is assigned a name. When u call a assigned name, all of the script blocks are executed. A function includes the 'function' keyword,an optional scope,a name(that you select),optional parameters,and a script block that consists of one or more powershell commands. An example of a function is the following, which returns the username.
Function Get-CurrentUser
{
[System.Security.Principal.WindowsIdentity]::Get-Current().Name
}
Get-CurrentUser
Function names should follow the naming  rules that powershell uses especially the verb-noun syntax.
There are 4 types of parameters : named,positional,switch and dynamic. Parameters can be read from the command line or from the pipeline. Get-Help About-functions can used to see more information.


Modules :
Modules are a group of related functions. You create the module by 
1.Placing the related functions  into one script file.
2.Save the script file with .psm1 extension.
3. Move the file into the $ENV:PSModulePath directory.
4. Load the module with Import_module cmdlet.
5. Unload the module with Remove-Module cmdlet.
6. You can list the functions in the module with the Export-ModuleMember cmdlet.

Error Handling .
There are two methods of error handling 1) Trap function 2 ) Try-Catch-Function.
Try is a script block that is attempted to run.Catch is a 0-N script blocks to run if there is a error in the try script block. Finally is 0-1 script blocks to run after the completion of either the try or catch blocks above it. 
$handling any error that Occurs.
Trap 
{
#Hanndling the error
$err=$_.Exception
write-host ,@err.Message
While ($err.Innerexception)
{$err=$err.Innerexception
{
Write output $err.message
}#end of the scipt.
Break