Microsoft Powershell Scripting

Powershell is one of the most useful languages out there, because of the vast amount of things you can do with it. 

You will find some useful scripts below which might help you out!

So to begin with, have a habit to log whatever your script is doing, it is the most efficient way to fix bugs and weird behaviour in larger projects, does not matter if it's into the eventlogs or if it's a log you have created yourself, aslong as you can follow up!

The Basics

In this example i'll show you how to make a nice little logging function which is very useful to have:

 


Function Log-Write
{
    <#
    .SYNOPSIS
    This function will let you log to file.
    .DESCRIPTION
    This function will let you create and add
    log entries to a log file.
    .EXAMPLE
    .\Log-Write -Value 'My custom log Entry' -Name 'My Custom Log Name' -Path 'H:\My_Custom_Log_Path\'
    In this example H:\My_Custom_Log_Path\ would get a new Log file named 'My Custom Log Name' with the content of Value timestamped.
    #>
    Param (
        [string]$Value="MyFirstLog",
        [string]$Name=$cfg['log_name'], 
        [string]$LogPath=$cfg['log_path'],
        [switch]$NoDate=$False
    )
    
    $Logfile = "$LogPath$(get-date -Format ('yyyy-MM-dd')) - $Name"

    
    if ($NoDate -eq $False)
    {
        $Value = $(get-date -Format ('yyyy-MM-dd HH:mm:ss')) + " - $Value"
    }
  
    if (!(Test-Path $Logfile))
    {
       $NULL = New-Item $Logfile -type file -Force
    }

    Add-content $Logfile -value $Value
    Write-Output $Value
}

 

And now you just call it whenever you need to within your script


Log-Write "Something Something" -Name "MyScriptLogIsAwesome log" -Path "C:\Scripts\Logs\";

 

You will notice that i have a some $cfg action going on at the top of the function.

I usually have a habit of creating a script config on top of my scripts like this

 


$cfg = @{
    log_path                 = 'C:\Scripts\Logs\initial\'
    script                   = "C:\Scripts\initializeserver.ps1"
    download_file_path       = 'c:\Scripts\Downloads\'
    script_task_name         = 'InitializeInstallation'
    restart_mode             = 'auto' #auto, manual
    max_concurrent_restarts  = '3'
}

 

It makes life alot easier if you can easily change the values at the top if you don't call your script directly (ie PS:>yourscript.ps1 -cmd blah blah -new blah blah -to blah blah ) meaning I can call my log function like this and im done: 


Log-Write "Something Something"

 

Use Try & Catch

It's easy and it will save you a lot of time in the long run, so start using it instantly!

Here is a little example how you can use try and catch but also the log-write function we talked about earlyer!

 


Function Create-LocalBackup
{
    Param(
        [Parameter (Mandatory=$True)][String]$ComputerName = "localhost",
        [String]$Destination = $cfg['dest_local_backup'],
        [String]$FileName=$cfg['config_name'],
        [String]$Source=$cfg['application_settings_path']
    )

    $error.clear()
    Try
    {
        if(!(Test-Path "\\$ComputerName\c$\$Destination\"))
        {
            New-Item "\\$ComputerName\c$\$Destination\" -ItemType Directory -Force | Out-Null
        }

        $Source = "\\$ComputerName\c$\$Source\$FileName"
        $Destination  = "\\$ComputerName\c$\$Destination"

        Copy-Item -Path $Source -Destination "$Destination\$FileName" -ErrorAction Stop;

        Backup-BGImage -ComputerName $ComputerName -Source $Source -Destination "$Destination\background.png"
    }
    Catch
    {
        Log-Write " *** ERROR - tried to make a local backup from $ComputerName but failed... :( Error notice: $error"
    }

    If (!$error) {
        Log-Write "successfully made a local backup from $ComputerName"
    }
}

 

 

You will find some useful script Here: