Tuesday, March 19, 2019

Progress bar in Power-Shell


Progress bar function is very important function in power shell. It’s always good to use show progress bar when you are running some process in your script. GUI effect makes you script much interactive and informative .Here  I am discussing  some of the power shell progress bar .We my be help full to someone.




#################################################################################

for($I = 1; $I -lt 101; $I++ )
{
    Write-Progress -Activity Updating -Status 'Progress->' -PercentComplete $I -CurrentOperation OuterLoop
    for($j = 1; $j -lt 101; $j++ )
    {
        Write-Progress -Id 1 -Activity Updating -Status 'Coping the file' -PercentComplete $j -CurrentOperation InnerLoop
    }
}

#################################################################################




################################# Function on progress bar ###########################

function Progress-Bar($iSeconds,$sInUnString)
{
    $Host.UI.RawUI.BackgroundColor = ($bckgrnd ='Black')                                                               # Changing the progress bar color and background text color
   # $Host.PrivateData.ProgressForegroundColor ='Green'
   # $Host.PrivateData.ProgressBackgroundColor='Black'

    $DoneDT = (Get-Date).AddSeconds($iSeconds)
    while($DoneDT -gt (Get-Date))
{
        $iSecondsLeft = $DoneDT.Subtract((Get-Date)).TotalSeconds
        $iPercent = ($iSeconds - $iSecondsLeft) / $iSeconds * 100
        Write-Progress -Activity "$sInUnString Apple.." -Status " " -PercentComplete $iPercent
        [System.Threading.Thread]::Sleep(500)
    }
 }

 Progress-Bar "20" "Best Company to work"

#################################################################################



############################### Time you can give here ##############################

$totalTimes = 10

  $i = 0

  for ($i=0;$i -lt $totalTimes; $i++) {

  $percentComplete = ($i / $totalTimes) * 100

  Write-Progress -Activity 'Work in Progress' -Status "Did thing $i  times" -PercentComplete $percentComplete

  sleep 1

}

#################################################################################




################################# Pause Program for 15 min #########################

###===========================
### Pause Program for 15 min
### - Matt Brown, 2008
###===========================
$x = 15*60
$length = $x / 100
while($x -gt 0) {
  $min = [int](([string]($x/60)).split('.')[0])
  $text = " " + $min + " minutes " + ($x % 60) + " seconds left"
  Write-Progress "Pausing Script" -status $text -perc ($x/$length)
  start-sleep -s 1
  $x--
}

#################################################################################




################################## Three progress bar################################

for ($i = 1; $i -le 2; $i++)
{
    Write-Progress -ID 1 -Activity "Outer loop" -Status "Tick $i" -percentComplete ($i / 2*100)
    for ($j = 1; $j -le 3; $j++)

    {
               Write-Progress -ID 2 -Activity "Mid loop" -Status "Tick $j" -percentComplete ($j / 3*100)
               for ($k = 1; $k -le 3; $k++)

           {

            Write-Progress -ID 3 -Activity "Inner loop" -Status "Tick $k" -percentComplete ($k / 3*100)
            Sleep(1)
           }
    }

}

#################################################################################

Monday, March 18, 2019

Create and remove new directory,file and folder using Power-Shell.


Creation and removal of directory\folder\file  in power shell is very easy .you just have pass simple command in script. Here we will see some of the example how we can create new Directory\Folder\File




Creating new Directory

New-Item -Path "c:\" -Name "Dir1" -ItemType "directory"

Creating multiple Dir using power shell

New-Item -ItemType "directory" -Path "c:\Dir1\Dir2"

New-Item -ItemType "directory" -Path "c:\Dir1\Dir2" -ErrorAction SilentlyContinue  

New-Item -ItemType Directory -Force -Path C:\Dir\You\Can\Create\Any\Time\Here


Check path exist or not condition here..

$path = "c:\Dir1\Dir2"

If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}

Creating new test file and enter new test values.

New-Item -Path C:\Temp\ -Name "testfile1.txt" -ItemType "file" -Value "This is a text string."

Create multiple files

New-Item -ItemType "file" -Path "c:\ps-test\test.txt", "c:\ps-test\Logs\test.log"




Removing files and folder from power shell

Remove-Item –path c:\Dir1\Dir2 –recurse

Remove-Item -Path "c:\Dir1\Dir2" -Force -Recurse

Remove-Item "c:\Dir1\Dir2" -Force  -Recurse -ErrorAction SilentlyContinue


The –recurse parameter will allow Power Shell to remove any child items without asking for permission

More Complex Delete Operations

Remove-Item –path c:\test\ remove-item * -include *.mp3 –recurse

More Complex Delete Operations

Remove-Item –path c:\folder\* -include *.txt


Delete the 'demo' registry key and all of its subkeys and values:

Remove-item hklm:\software\SS64\demo -Recurse


Note:- Please test script in your test environment before running in production directly.

Friday, March 8, 2019

Change font color in Power-Shell and display in PS console

Every want color full life and color full job. Some time watching a black and white console makes thing very boring bring some color in your power shell console. Change font color using the power shell script. Its always looks good when you code have some significant color in console .As a script-er you have to show some nice color in power shell scripts.



In order to change the colors, I’ll familiarize myself with where that info is stored.This info is stored in the variable $host

you want to be cool and use Power-Shell to list the enum values.

1.
[System.Enum]::GetValues('ConsoleColor') | ForEach-Object { Write-Host $_ -ForegroundColor $_ }


2.  Change the font color of the console

      $host.UI.RawUI.ForegroundColor = "DarkGreen"

3.  Changing the main console foreground and background is slightly different. That data is stored in       a separate location.

      $host.UI.RawUI.ForegroundColor = "DarkGreen"
      $host.UI.RawUI.BackgroundColor = "Black"

4. Write with different text and background colors

     Write-Host "Whole text is in red" -ForegroundColor Red
     Write-Host "Red on white text." -ForegroundColor green -BackgroundColor black

5. Write to the console without adding a new line

     Write-Host "no newline test " -NoNewline
     Write-Host "second string"

6. Suppress output from Write-Host

    Write-Host "I won't print" -InformationAction Ignore

7. Color full console 

   Write-Host "Green " -ForegroundColor Green -NoNewline; 
   Write-Host "Red " -ForegroundColor Red -NoNewline; 
   Write-Host "Yellow " -ForegroundColor Yellow -NoNewline;





Note:- Please test script in your test environment before running in production directly.

Tuesday, March 5, 2019

How we can get the script file system location of from Power-Shell script ?


Here is the some cases we have to get power shell script system directory path .There is many way to achieve that .Power shell have some inbuilt function to get system directory and script path and root n-1 directory.
I am showing some example here. This examples may be help you to get your target Dir.




1. Best way to get Script directory path is

         $PSScriptRoot

Just save below code in .PS1 format and run it and you will get Dir path

         $ScriptName = $PSScriptRoot
         Write-host $ScriptName

Note:- For using $PSScriptRoot method your power shell version has 3.0 or above.If you have below 3.0 power shell function so please use below methods.

2. Get power shell script path

         $Script:sScriptFolder = (Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
         Write-Host $sScriptFolder

3. Get power shell script path

         $MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
         Write-Host $MyDir

4. Get power shell script file name.This is very good function

         $MyDir1 = $MyInvocation.MyCommand.Name
         Write-Host $MyDir1

5. Get complete power shell script path.

         $script_path = $myinvocation.mycommand.path
         Write-Host "Current ScriptPath $script_path"

6. Get the current directory of the cmdlet being executed

         (Get-Item -Path ".\").FullName

7. Get Script parent folder N-1 and N-2 folder path.This script will help you.

         $scriptPath = (Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
         $parentPath = Split-Path -parent $scriptPath
         Write-host $parentPath
         $rootPath = Split-Path -parent $parentPath
         Write-host $rootPath



Note:- Please test script in your test environment before running in production directly.


Thursday, February 21, 2019

How to check windows machine are x64-bit and x86 (32-bit ) architecture


Logic to detect system architecture for windows machine are 32-bit or x64-bit from power-shell. This is very small function but admin and script-er use a lot in day to day task .I am sharing one function which will deduct bitness of windows machine.We can check OS architecture from remote machine also. 



#################################################################################

Function GetArchOS($sArchOS)

{
    $sArchOS = (Get-WmiObject Win32_OperatingSystem).OSArchitecture
    If($sArchOS -eq '64-bit' )
    {
        $Script:sArchOS = "x64"
        Write-Host $sArchOS
    }
    Elseif($sArchOS -eq '32-bit')
    {
        $Script:sArchOS = "x86"
        Write-Host $sArchOS
    }
    
}

GetArchOS


#################################################################################

################################## Remote Machine ################################

$sComputerName='CRP-APPTESTW64'

$sOSArch = (Get-WmiObject Win32_OperatingSystem -computername $sComputerName).OSArchitecture

Write-host $sOSArch

#################################################################################


################################  Win-32_Processor #################################


$sComputerName='CRP-APPTESTW64'

$sOSArch = Get-WmiObject -Class Win32_Processor -ComputerName $sComputerName| Select-Object AddressWidth

Write-host $sOSArch


#################################################################################

Note:- Please test script in your test environment before running in production directly.

Wednesday, February 20, 2019

Check process is running or not on windows machine from Power-Shell


Some of the scripter wanted to check process  is running or not in particular windows machine and if process is running so admin can perform required task on system for example kill process, execute any installation file. I tried to create the Power-Shell function to get those process is running on the machine. This function could help somewhere. I have added the array logic so you can pass multiple process as a argument in the function.




################################ Check in local machine #############################

Function CheckProcess($sEnterProccessNameHere)

{

    # Calling Aarray
    @($sEnterProccessNameHere) | `    
    Foreach-Object `
    {
        If (Get-Process $_ -ErrorAction SilentlyContinue)
        { 
        Write-Output "$_ is running" 
        }
        else 
        { 
        Write-Output "$_ is not running" 
        }
    }

}

$sEnterProccessNameHere = @("Services","Outlook","Word","SMSS")  # Pass the process agreement here

CheckProcess $sEnterProccessNameHere      # Calling function 


#################################################################################

Note:- Not able to pass multiple value in below code but single parameter its working fine.Still searching solution for multiple parameter value

########################### Check process on remote machine ##########################

Function CheckProcess([String[]]$sEnterComputerNameHere,[String[]]$sEnterProccessNameHere)
{
    #Write-host " $sEnterComputerNameHere hello"

        @($sEnterComputerNameHere) | ` 
    Foreach-Object `
    {
        # Calling Aarray
        @($sEnterProccessNameHere) | ` 
        Foreach-Object `
        {
             
            If (get-process -computername $sEnterComputerNameHere | where {$_.ProcessName -eq $sEnterProccessNameHere})
            {
            Write-Output "$_ is running"
            }
            else
            {
            Write-Output "$_ is not running"
            }
        }
    }
}

$Script:sEnterProccessNameHere = @("VPNUI")  # Pass the process agreement here
$Script:sEnterComputerNameHere = @("CRP-APPTESTW64")  # Pass the process agreement here

CheckProcess $sEnterComputerNameHere $sEnterProccessNameHere     # Calling function


#################################################################################

############################### Calling multiple process on multiple machine ############

Function CheckProcess([String[]]$sEnterComputerNameHere,[String[]]$sEnterProccessNameHere) 
{ #Write-host " $sEnterComputerNameHere"

    @($sEnterComputerNameHere) | Foreach-Object {
        $computer = $_
        Write-Host $computer        
        @($sEnterProccessNameHere) | Foreach-Object {
            $process = $_
            Write-Host $process
            try{
                $x = get-process -computername $computer #Save all processes in a variable
                If ($x.ProcessName -contains $process) #use contains instead of equals
                {
                    Write-Output "$process is running"
                }
                else
                {
                    Write-Output "$process is not running"
                }
            }
            catch
            {
                Write-Host "Computer $computer not found" -ForegroundColor Yellow
            }
        }
    }
}

$script:sEnterProccessNameHere = @("VPNUI","Notepad++","SMSS") 
$script:sEnterComputerNameHere = @("remotecomputer1","remotecomputer2") 

CheckProcess -sEnterComputerNameHere $sEnterComputerNameHere -sEnterProccessNameHere $sEnterProccessNameHere

#################################################################################


Note:- Please test script in your test environment before running in production directly.

Monday, February 18, 2019

Popup Message Box From Power-Shell..


Every Admin, Developer, Scripter need good customized pop box message box to their user PC screen and creating a message box in power shell is pretty simple command ([System.Windows.MessageBox]::Show('Hello')) we have but sometime you want to show customize box where you can pass message box Title and some pretty good color and that message box appear on user windows for some limited time and close automatic and popup message closing time you can pass as an arguments. You can customize window size as well. I found the very good function which help to popup pretty neat popup message box. May be this can help you.


1. [System.Windows.MessageBox]::Show('Hello')

2. [System.Windows.MessageBox]::Show('Do you want to do coding?','My Test Box','YesNoCancel','Error')

3. Customize popup message box power shell code.

################################### Pop-Up Message ###############################

Function PopupWindow([string]$message,[int]$seconds,[string]$title)
{
     Function ClearAndClose()
     {
        $Timer.Stop();
        $Form.close();
        $Form.Dispose();
        $Timer.Dispose();
        $Label.Dispose();
        $Script:CountDown=$seconds
     }

     Function Button_Click()
     {
        ClearAndClose
     }

     Function Timer_Tick()
     {

        $Label.Text = "$message $Script:CountDown seconds.$title"
             --$Script:CountDown
             if ($Script:CountDown -lt 0)
             {
                ClearAndClose
             }
     }

     Add-Type -AssemblyName System.Windows.Forms
     Add-Type -AssemblyName System.Drawing
     $Form = New-Object system.Windows.Forms.Form
     $Form.Text = "customized Box..."                                         #Display title here
     $Form.Size = New-Object System.Drawing.Size(550,100)   #change the popbox Size
     $Form.StartPosition = "CenterScreen"
     $Form.MinimizeBox = $False
     $Form.MaximizeBox = $False
     $Form.Topmost = $True
     $Form.BackColor = "black"

     $Label = New-Object System.Windows.Forms.Label
     $Label.AutoSize = $true
     $Label.Location = New-Object System.Drawing.Size(30,30)
     # $Label.Font = 'Segoe UI, 8.75pt, style=normal, Italic'
     $label.ForeColor = "Yellow"              # Change the message text color

     $Timer = New-Object System.Windows.Forms.Timer
     $Timer.Interval = 1000

     $Form.Controls.Add($Label)

     $Script:CountDown = 6
     $Timer.Add_Tick({ Timer_Tick})

     $Timer.Start()
     $Form.ShowDialog()


}

PopupWindow("Hello",10,"My customized Box")   #Calling Function here....



################################################################################

Note:- Please test script in your test environment before running in production directly.