Showing posts with label powershell script. Show all posts
Showing posts with label powershell script. Show all posts

Monday, 9 January 2023

Get-ChildItem - Powershell command to find items in a specified location

The 'Get-ChildItem' cmdlet gets the items in one or more specified locations.

 It can be used to list the files and directories in a particular directory, or to list the registry keys and values in a registry hive.


How to use 'Get-ChildItem' to list the files in the current directory:
                    
Get-ChildItem


We can also specify a different directory to list the files and directories in that directory by using the -Path parameter: 

Get-ChildItem -Path D:\TestDir


To get the list of files with a particular extension, suppose .txt files, using Get-ChildItem Command, it can be used as:

 Get-ChildItem -Filter *.txt


We can find more about Get-ChildItem command and its usage by using:

                    Get-Help Get-ChildItem 

 Get-ChildItem [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device | Directory | Encrypted | Hidden | IntegrityStream | Normal | NoScrubData | NotContentIndexed |Offline | ReadOnly | ReparsePoint | SparseFile | System | Temporary}] [-Depth <System.UInt32>] [-Directory] [-Exclude <System.String[]>] [-File] [-Force] [-Hidden] [-Include     <System.String[]>] -LiteralPath <System.String[]> [-Name] [-ReadOnly] [-Recurse] [-System] [-UseTransaction] [<CommonParameters>]


    Get-ChildItem [[-Path] <System.String[]>] [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device | Directory | Encrypted | Hidden | IntegrityStream | Normal | NoScrubData | NotContentIndexed | Offline | ReadOnly | ReparsePoint | SparseFile | System | Temporary}] [-Depth <System.UInt32>] [-Directory] [-Exclude <System.String[]>] [-File] [-Force] [-Hidden] [-Include <System.String[]>] [-Name] [-ReadOnly] [-Recurse] [-System] [-UseTransaction] [<CommonParameters>]


Monday, 5 July 2021

PowerShell: Calculate the power using math function

 Here is a Powershell script 

  • which gets two numbers from the command line 
  • if there is no parameters, read them from the keyboard
  • Calculate the power (first param on the power of the second )
  • Display the output
  • E.g. .\calcPower.ps1 2 3 => 8

 

PowerShell Script:


                    

#assign argument values
$num1 = $args[0]
$num2 = $args[1]

#check if the value entered is null
if ($num1 -like "$null"){
    #if null, ask for user input
    $num1 = read-host "Please enter the 1st number"
}

if ($num2 -like "$null"){
    $num2 = read-host "Please enter the 2nd number"
}

#calculate power using 'pow' function
$power = [Math]::Pow($num1,$num2)

#display output
Write-Output "$num1 to the power $Num2 is $power"

 

 


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:




 


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'"


Thursday, 5 November 2020

PowerShell: Remove Local User

 Read local user names from a file and remove them.

The file userFile.txt contains local user names to be removed from the computer.


$userData = Get-Content .\userFile.txt

foreach ($usr in $userData){
#remove users
Remove-LocalUser -Name "$usr"
}


Read:    How to add local user

Saturday, 31 October 2020

PowerShell: Write a Script to Add a local user

Create a group of users using a PowerShell script.

There is a file consisting of a group of 3 new user name’s and passwords in each line.

userFile.txt
Jack,123jack
Tim,123tim
Shawn,123shawn


 Write a script that does the following

i.      Retrieve the names and assign them to an array

ii.      Write a loop that prints out each of the user names. 

iii.      Create an account and Add each of these users to the local group  'Users'


PowerShell Script


#Use get-content to retrieve the names and assign them to an array
    $userData = Get-Content .\userFile.txt

#Write a loop that prints out each of the user names. 
    Write-Output "Below is the list of users:"
    foreach ($data in $userData){
        $user = ($data.split(","))[0]
        $user
    }

#create an account using localuser for each of the users, Add each of these users to the local group Users
    foreach ($data in $userData){
       $user = ($data.split(","))[0]
        $psswd = ($data.split(","))[1]
    
#convert password to  secure string
        $securPass=convertTo-SecureString -string $psswd -asPlainText -Force
#create new local user
        New-LocalUser -Name "$user"  -Password $securPass
#add user to local group Users
        Add-LocalGroupMember -Group "Users" -Member "$user"
}



You can verify the script by using the below cmdlet in PowerShell prompt:

        Get-LocalGroupMember -Name 'Users





Wednesday, 28 October 2020

Simple parsing in PowerShell & Sorting

Take a variable and break it up into 2 parts, store it in a simple array, and display values using PowerShell. Also, sort the array in descending order.


Input: "Hello-World"
variable one would be from 1st character of the input and up to the "-"
variable two would be from the character "-" to the end of the input variable


so
Output 1 would be "Hello"
Output 2 would be "World"


Program:

$string = Read-Host "Enter a String" 
$varArray = $string.split("-")

#variable 1
$varArray[0]

#variable 2
$varArray[1]

#sorting the array
Write-Host "`nSorted Array in Descending Order:"
$varArray | Sort-Object -Descending