Windows Server: logging users logon and logoff via PowerShell

You are planning a migration and you want to track and monitor for a few weeks when your server is being used the most?

  1. Open Windows PowerShell ISE ( or notepad ;-) )
  2. Add this PowerShell line below and save the script as monitorlogon.ps1
  3. "logon {0} {1} {2:yyyy-MM-dd HH:mm:ss}" -f $env:username, $env:computername, (Get-Date) >> logon.log
  4. Create another script file, add the PowerShell line below and save it as monitorlogoff.ps1
  5.  "logff {0} {1} {2:yyyy-MM-dd HH:mm:ss}" -f $env:username, $env:computername, (Get-Date) >> logoff.log
  6. Start the Logal Group Policy Editor ([Windows]+[r] > gpedit.msc)
  7. Navigate to [User Configuration] > [Windows Settings] > [Scripts (Logon/Logoff)]
  8. Double click on the [Logon] name
  9. Navigate to the [PowerShell Scripts] tabpage
  10. Click the [Add] button and select your monitorlogon.ps1 script.
  11. Optionally you can select the execution order, default is set to “Not configured”.
  12. Repeat again from step 6. for the Logoff script.

You can change the >> filename.log part to >> \\MyShare\filename.log.

If you want to do this on a Windows Server 2003 where you can’t run your PowerShell you will need to save the file as an *.cmd:

  1. Create a new file and call it monitorlogon.cmd
  2. Enter the line below and save the script as monitorlogon.cmd:
  3. echo logon %username% %computername% %date% %time% >> C:\logon.log
  4. Repeat this for monitorlogoff.cmd and adjust the script line.
  5. Follow the steps from the PowerShell script.

Downloading files with PowerShell using the BitsTransfer module

@sstranger told me on Twitter that you can also use the BitsTransfer module, to download files via PowerShell (previous post).

He wrote a script to download several files from the microsoft website.

Here is a modified version of his script, using test files with size 50MB and 100MB:

# path to store the data
$global:path = "c:\TEMP\"

# loads the BitsTransfer Module
Import-Module BitsTransfer
Write-Host "BitsTransfer Module is loaded"

# test data from http://www.thinkbroadband.com/download.html
$fileLinks = @("http://download.thinkbroadband.com/50MB.zip",
 "http://download.thinkbroadband.com/100MB.zip");

# start the download
Foreach ($fileLink in $fileLinks)
{
 Start-BitsTransfer $fileLink $path
}
Write-Host "Files are downloaded to $path"

Save this script as PowerShellFileDownloader.ps1 and run it in the Windows PowerShell ISE (which is included by default in Windows 7).

If you can’t run the script due to security reasons, change your execution policy:
(read more about running PowerShell scripts here)

Set-ExecutionPolicy RemoteSigned

Warning: changing the ExecutionPolicy might cause a security risk.

Some screenshots of the script running with the BitsTranfser module:

Have fun! ;)