Function declaration

Decorating a script block with the function keyword and a name is, at first, the only thing that makes a function. Adding your functions to a module will enable you to package them, version them, and ship them as a single unit.

While you can certainly create functions in your code dynamically, it is not recommended. There is no good reason to not create a proper function declaration:

# Using the function PSDrive, create a new function in your code
New-Item -Path function:MyFunction -Value {param($Id) Get-Process -Id $Id}
MyFunction -id $pid
& (Get-Item Function:MyFunction) -id $pid

Consider the following code. You should be able to immediately spot why using a function might be the best option here:

# The legacy code
$prinfo = Get-CimInstance -Query 'SELECT * FROM CIM_Processor'

if (-not (Test-Path -Path D:Logs))
{
New-Item -Path D:Logs -ItemType Directory
}

"$((Get-Date).ToString('yyyy-MM-dd hh:mm:ss')):`tFound $($prinfo.NumberOfCores) cores with $($prinfo.NumberOfLogicalProcessors) logical processors" | Out-File -FilePath D:Logs$((Get-Date).ToString('yyyyMMdd'))_SysInfo.log -Encoding UTF8 -Append

Get-Service | foreach {
"$((Get-Date).ToString('yyyy-MM-dd hh:mm:ss')):`tService$($_.Name) has status $($_.Status)" | Out-File -FilePath D:Logs$((Get-Date).ToString('yyyyMMdd'))_SysInfo.log -Encoding UTF8 -Append
}

"$((Get-Date).ToString('yyyy-MM-dd hh:mm:ss')):`tScript finished" | Out-File -FilePath D:Logs$((Get-Date).ToString('yyyyMMdd'))_SysInfo.log -Encoding UTF8 -Append

Extracting the reusable code, we get two functions: Enable-Logging and Write-Log. The code is much leaner, and any changes to the date format in the log messages only need to take place at one point. In this short example, adding the functions has, of course, increased the total lines of code. However, this quickly pans out in larger scripts and modules as seen in the next code sample:

# The improved code with two functions
function Enable-Logging
{
[CmdletBinding()]
[OutputType('System.IO.FileInfo')]
param
(
[Parameter(Mandatory)]
[String]
[ValidateScript({
Test-Path -Path $_ -PathType Leaf
})]
$Path
)

$logFolder = Split-Path -Path $Path -Parent

if (-not (Test-Path -Path $logFolder))
{
[void] (New-Item -Path $logFolder -ItemType Directory)
}

if (Test-Path $Path)
{
return (Get-Item $Path)
}

New-Item -ItemType File -Path $Path
}

function Write-Log
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string]
$Message,

[Parameter(Mandatory)]
$Path
)

$logMessage = "{0}:`t{1}" -f (Get-Date).ToString('yyyy-MM-dd hh:mm:ss'),$Message
Add-Content -Path $Path -Value $logMessage -Encoding UTF8
}

$processorInfo = Get-CimInstance -Query 'SELECT * FROM CIM_Processor'

$log = Enable-Logging -Path "D:Logs$((Get-Date).ToString('yyyyMMdd'))_SysInfo.log"

Write-Log -Message "Found $($processorInfo.NumberOfCores) cores with $($processorInfo.NumberOfLogicalProcessors) logical processors" -Path $log.FullName

foreach ($service in (Get-Service))
{
Write-Log -Message "Service $($service.Name) has status $($service.Status)" -Path $log.FullName
}

Write-Log -Message "Script finished" -Path $log.FullName
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.125.219