Thursday, 18 March 2021

PowerShell Script: Copy Several files with same name to a folder without overriding with a differentiator

Powershell Script Description:

PowerShell script that will go through a directory called "C:\Deploy"

that has several subfolders with a file named "index.html in each of the subfolders and copy all the files named "index.html to a new folder called "C:\AllIndex" but not overwrite.

The files after copying would be named index001.html, index002.html, index003.html...



#source dir

$src = "C:\Deploy"

#destination dir 
$destn = "C:\AllIndex"

 

#Get the list of index.html
$index_html_list = (Get-ChildItem -Path "$src" -Name "index.html" -Recurse -Force)

 

# initialize counter
$counter = 1

 

#run in loop for all index.html 
foreach ($html in $index_html_list){
$counter = $counter.ToString('000')

#copy each index.html to new file in destination dir 
Copy-Item -Path "$src\$html" -Destination "$destn\index$counter.html"
#increment counter
$counter = [int]$counter + 1

}

 

Wednesday, 24 February 2021

PowerShell: Find the list of empty folders in a Directory

 

If you would like to find the empty folders in a directory you can use the below PowerShell script to find out.



Script:

$path = "D:\"   #change the value based on need

        #get the list of directories in the given path recursively  

         Get-ChildItem -Path $path -Directory -Recurse | ForEach-Object `

            #verify the count of files and folders in the directories are zero 

    if($_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0) 

        {

            "$($_.name)"            

        } 

Thursday, 18 February 2021

PowerShell: Check if the entered number is a valid Binary and print its decimal value

Powershell Script Description: 

Pass a number to a PowerShell script as an argument and validate whether it is a valid Binary. If the entered number is a valid binary, display its decimal value.


Script: isValidBinary.ps1

if (  $args[0] ){
    $num = $args[0]

    try {
        $value = [convert]::ToInt32(“$num”,2)
        Write-Host "'$num' is a valid Binary" -ForegroundColor Green
        Write-host "Decimal Value: $value"
        }

    catch{
        Write-Host  "'$num' is not a valid Binary" -ForegroundColor Red
    }
}
else{
    Write-Host "You must pass a number to the script"
}

Output:




 


Tuesday, 9 February 2021

Shell Script that accepts a positive integer and returns comma separated list of integers in descending order

Description: 
Write a  shell script that accepts exactly 1 argument which must be a positive integer. 
The script will print a comma-separated list of integers, all on the same line in descending order

Script: decreaseNum.sh

 

#!/bin/bash
#-----------------------------------------------
#user input
num=$1
temp=''
         
        #continue while input is greater than 0
 while [ $num -gt 0 ]
 do
                #append the numbers in decreasing order with comma-separated
  temp+="$num, "
  num=$(( $num - 1 ))
    done
 temp=$(echo $temp | sed 's/,$//')
 echo $temp


Output:








Saturday, 12 December 2020

PowerShell Script to calculate letter count in a string

 Count occurrence of a letter in a string using Powershell:

Instruction:

1. Create a Powershell script that accepts two arguments

2. argument 1: a string

3. argument 2: a letter


Script: letterCount.ps1

$word = $args[0]
$letter = $args[1]
$count = 0
if ( $word -like $null -or $letter -like $null){
Write-Host "Argument missing" -ForegroundColor Green
break
}
$len = $word.length
foreach ($i in 0..$len){
     $a = $word[$i]
     if ( $a -like "$letter"){
        $count = $count + 1
     }
}
Write-Output "'$word' has $count '$letter'"


Monday, 16 November 2020

Shell Script: Get the Average Grade of a Student

Write a shell script, which gives back the average grade of a student The student name we should give as a parameter! If you give a name that is not in the data file, please write out an error message and write out the list of the names (Just the names without the grades!!!) as a help!

input file: class.txt

Name/Math Informatics Literature English
Mohammed 3 4 5 4
Alan 2 1 3 2
Li 3 5 1 3
Jane 4 2 3 1

SCRIPT:

#!/bin/bash
# Variable Declaration
input_file="./class.txt"
name=$1
average=0
err_msg="\n\tPlease pass a student name to the script. \n\te.g.: ./average.sh Tom \n" 
name_list=`cat class.txt | awk '(NR != 1) {print $1}' | tr "\n" ","  | sed -e 's/,$//' -e 's/,/, /g' `
#---------------------------------------------------------------------------------------------
if [ -z "$name" ]
then
echo -e "$err_msg"
else
record=$(grep -w "$name" $input_file)
if [ -n "$record" ]
then
#sum=$(echo $a | awk '{sum=0; for (i=2; i<=NF; i++) { sum +=i} print sum }')
average=$(echo $record | awk '{sum=0; for (i=2; i<=NF; i++) { sum +=$i} print sum/(NF - 1) }')
echo -e "\t $name $average \n"
else
echo -e "No $name is in the list. There are: $name_list"
fi
fi


let's check the output:




Sunday, 8 November 2020

Shell Script: Write 000 to 999 (1000 lines in a file) using Brace Expansion

We need to write from 000 to 999 in a file. As these are consecutive numbers we will be using "Brace Expansion"

Let's Create a file by using the touch command.


Script:

 #create an empty file
touch output.txt 

#using brace expansion with foor loop
 for i in {000..999} #this is brace expansion
do
    #append data to output.txt 
    echo $i >> output.txt
done


Output: 

To see the output use bellow command

        cat output.txt | more