Powershell - functions


Define and call Powershell function - untyped parameter

 
## define function 
Function PrintName{param($Nom) 
              Write-Output "Bonjour : $nom ! "
}
 
## call function
PrintName -Nom Martin

Define and call Powershell function - using typed parameter

## define function 
Function PrintName{param([String]$Nom) 
              Write-Output "Bonjour : $nom ! "
}
 
## call function
PrintName -Nom Martin

Function: Deleting Files older than 60 days

 
## deleteOldFiles: Delete files older than 60 days
## programme deleteOldFiles.ps1
## erase files over 60 days found in C:\tests or its subdirectories
## except for files containing string *LOADDATA*
## write work done to deleteOldFiles.log
 
Function deleteOldFiles {param([String]$Directory)
              
    $Logs = "C:\Logs\deleteOldFiles.log"
    $Jours= -60
    $Entête1 = "Date deleted:  $((Get-Date).ToString()), Repertoire:  $Directory1"
    $Entête2 = "Last Modified          Size      Directory/Name"
    $Entête3 = "-------------------------------------------------------------------------------------------------------------"
                
    ## Wite to log file
    $Entête1 | Out-File $Logs -Append
    $Entête2 | Out-File $Logs -Append
    $Entête3 | Out-File $Logs -Append
    Get-ChildItem $Directory -Recurse -ea 0 | 
    ? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays($Jours)} |
    ForEach-Object {
        if ($_ -notlike "*LOTDAS*") {
            ## $_ | del -Force
            ('{0,-23}' -f $_.LastWriteTime) + ('{0,-10}' -f $_.Length) + ('{0,-120}' -f $_.FullName)  | Out-File $Logs -Append
        }
    }
}
 
$Directory1 = "C:\tests"
## call function deleteOldFiles
deleteOldFiles -Directory $Directory1