Implementing logging (to log file) in Powershell Scripts

Many of the times one requires to setup logging for a script that is very huge in code and/or critical in it’s activities.  Here is a quick PS function code that I authored which simply logs all the log statements to a given file (for this example, I used C:tempTest.log file). Code: $LogFile    = ‘C:tempTest.log’ function MyLog {     param ([string]$msg, [int]$flag)     $date = get-date -format MM:dd:yyyy-HH:mm:ss     Write-Output "msg received is [ $msg ] flag received is: [ $flag ]" | Out-File $LogFile -append     if ($flag -eq 0) {         Write-Output "$date INFO: $msg" | Out-File $LogFile […]

Read more

PS: Windows GUI Automation

Very often in automation you require to bring a running process Window to the front and setting it as the active Window for the user. For this you need to run a script like below where you ensure that specified process is running, once you detect that process is running, you select the process Window and then set it as the active Window with maximized position. Code: while (! $IsWindowRunning) {     $IsWindowRunning = select-window -ProcessName excel } select-window -ProcessName excel | set-windowactive | Set-WindowPosition -maximize   In case, you just need to one of have the Window maximized, then […]

Read more

PowerShell Return Codes

You can access/verify/check the success/failure return code of a Powershell commands via $? variable.  The $? variable is of type Boolean. It will only give you a True or False states depending whether the last command ran successfully or failed respectively. Checking PS commands return code: Sample code: $ret = Invoke-Item "C:Program DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft Office Excel 2007.lnk" # Note the space in the path which is incorrect Write-Host "$?" $date = get-date -format MM:dd:yyyy-HH:mm:ss Write-Host "$?" Output: Invoke-Item : Cannot find path ‘C:Program DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft Office Excel 2007.lnk’ because it does not e xist. At C:temptest-ps-return-codes.ps1:2 char:19 + […]

Read more