• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

TECHDIIP

  • Tech
  • Windows
  • Powershell
  • Scripts
  • News
  • Games

PowerShell Functions

Powershell functions are the most lightweight form of Powershell command, it’s a grouping of code runs against each object defined (within that code) in the script block and performs the specified action. Powershell functions help the administrator to create reusable code which acts as Powershell cmdlets.

Syntax

A function is defined as follows:

function <name>

{<statement list>}

function myfunction
{
 'Hello world'
 }

Passing arguments to function

function myfunction1
{ 
 "Hello there $args, how are you?" 
}

output

PS C:\Windows\System32> myfunction1 raj

Hello there raj, how are you?

function Adition {

Param ([int]$var,[int]$var2)

$result = $var + $var2

Write-Output $result

}

Output:

PS C:\Adition -var 10 -var2 15

25

PowerShell Advanced functions:

The PowerShell advanced functions specified with parameter attribute [cmdletbinding()], this cmdletBinding attribute is similar to the Cmdlet attribute that is used in compiled cmdlet classes to identify the class as a cmdlet.

Example

function Hello-world
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string] $Name
    )

    Process
    {
        Write-Host ("Hello " + $Name + "!")
    }
}

Output:

PS C:\Windows\System32> Hello-world -Name raj

Hello raj!

Thank you for reading this article, if you have any questions please let us know.

Thank you for visiting my site, for any scripts in these articles you are testing please make sure you have tested this script in our lower environment before you run in production.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Recent Posts

  • How do Zoom Application Testing | Working or Not
  • Powershell script to test website status up or down on a local or remote computers
  • Solved: Server execution failed windows 10 Server 2016 and 2019
  • How to Fix windows 10 version 1903 error 0xc1900223
  • Free Music Making Software List One Can Try Out
  • About Us
  • CONTACT US
  • Disclaimer
  • Privacy Policy

Copyright © 2023 techdiip.com