PowerShell Logon Script Example

The following script – LogonScript.ps1 is an example of a possible usage of PowerShell for login scripts.

# Filename:	LogonScriptExample.ps1
# Date:              April 30, 2012
# Author:     Alex Dujakovic
# Description: Logon script for domain AlexTest.Local
# ************************************************************
$ErrorActionPreference = "SilentlyContinue"
$strName = $env:username
$strComputerName = $env:ComputerName
$strADgroupHelpDesk = "Help Desk"
$strADgroupDeployManager = "Deployment Managers"
$strADgroupAccounting = "Accounting"
$strAccountingDrive = "W:"
$strHelpDeskDrive = "X:"
$strDeployDrive = "Y:"
$strDeployMgrDrive = "Z:"
$strHomeDrive = "Q:"
$strPathToHelpDeskShare = "\\test-dc-01\HelpDesk$"
$strPathToUsersHomeShare = "\\test-dc-01\Users$"
$strPathAccountingShare = "\\test-dc-01\Common\Accounting"
$strPathDeployMgrShare = "\\test-dc-01\Common\Deployment"
$strPathDeploymentShare = "\\test-sccm-01\DeploymentShare$"
$strTime = Get-Date -Format "t"
$strDate = Get-Date -format "yyyy-MM-dd"
$strFile = Get-Date -format "yyyy-MM"
$strFileName = "\\test-dc-01\LoginAndOutFiles$\"
# ***********************************************************************************
function ListADGroup-Member {
BEGIN{}
PROCESS{
$strFilter = "(&(objectCategory=User)(samAccountName=$_))"
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = $strFilter
$objPath = $objSearcher.FindOne()
$objUser = $objPath.GetDirectoryEntry()
$strUserHomeDrive = $objUser.sAMAccountName
$DN = $objUser.distinguishedName
$ADVal = [ADSI]"LDAP://$DN"
if (!($ADVal.memberOf.Value -eq $Null)){
$GroupName = $ADVal.memberOf.Value
foreach($gp in $GroupName)
  {
  if($gp | Select-String -pattern $strADgroupAccounting)
  # {$(New-Object -ComObject WScript.Network).MapNetworkDrive($strCommonDrive, $strPathCommonShare)}
  # Map a drive calling .MapNetworkDrive from a Wscript.Network COM object, this method will make a persistent drive map
  # ********************************************************************************************************************
  {if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strAccountingDrive'") )
      {net use /persistent:yes $strAccountingDrive $strPathAccountingShare | Out-Null}
  }
  if($gp | Select-String -pattern $strADgroupHelpDesk)
     {if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strHelpDeskDrive'") )
         {net use /persistent:yes $strHelpDeskDrive $strPathToHelpDeskShare | Out-Null}
  }
  if($gp | Select-String -pattern $strADgroupDeployManager)
     {if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strDeployDrive'") )
         {net use /persistent:yes $strDeployDrive $strPathDeploymentShare | Out-Null}
  }
  if($gp | Select-String -pattern $strADgroupDeployManager)
     {if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strDeployMgrDrive'") )
         {net use /persistent:yes $strDeployMgrDrive $strPathDeployMgrShare | Out-Null}
  }
}
}
}
END{
# Map a user's home drive
if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strHomeDrive'") )
   {$strPathToUsersHomeShare = $strPathToUsersHomeShare + "\" + $strUserHomeDrive
   net use /persistent:yes $strHomeDrive $strPathToUsersHomeShare | Out-Null}
}
}
# End of function ListADGroup-Member
$strName | ListADGroup-Member
$strFileName += [string]$strFile + ".txt"
$strDate + "," + $strTime + "," + $strName + "," + $strComputerName + "," + "Logon" | Out-File $strFileName -append -Encoding ASCII

Out-File with encoding parameter:

I’ve consulted Windows PowerShell Help file and found this parameter -Encoding.
It specifies the type of character encoding used in the file. Valid values are “Unicode”, “UTF7”, “UTF8”, “UTF32”, “ASCII”, “BigEndianUnicode”, “Default”, and “OEM”. “Unicode” is the default. “Default” uses the encoding of the system’s current ANSI code page. “OEM” uses the current original equipment manufacturer code page identifier for the operating system.
This parameter is not required and its position is 2.  The text file is encoded in ASCII format so that it can be read by search programs like Findstr and Grep. In one of my future blogs I will show you how this file could be used by VBScritp in my HTA application.

Mapping drives based on user´s group membership:

To map a network drive I could use the PowerShell cmdlet New-Object and Wscript.Network COM object in the script above. By calling .MapNetworkDrive method this script will make a persistent drive map.  But I want to be absolutely sure that a mapped drive stays there when I either close PowerShell or use Explorer or click a “Browse” button from an application. That is the reason why I use Net Use command, it is simple and works great.

Please note that you can use the Windows PowerShell drives that you create to access   data in the associated data store, just like you would do with any mapped   drive. However, the Windows PowerShell drives are known only to Windows   PowerShell. You cannot access them by using Windows Explorer, Windows   Management Instrumentation (WMI), Component Object Model (COM), or the   Microsoft .NET Framework, or by using tools such as Net Use.  Windows PowerShell drives exist only in the   current Windows PowerShell session. To make the drive persistent, you can   export the session to which you have added the drive, or you can save a   New-PSDrive command in your Windows PowerShell profile.

To check if mapped drive exist, in the script I use WMI just before mapping (if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter “DeviceID=’$drive'”).

Mapping user´s home drive:

To map a user´s home drive I used the End{} block of the function ListADGroup-Member, just to show you that the same code/logic could be applied for mapping a home drive.

Mapping one drive to different shared folders based on group membership:

For example: John works for the Accounting, Stephen works in the other department and he is a member of Sales, Kate is a member of Warehouse. So when John logs in, the drive I: should point to “\\Test-DC-01\Common\Accounting”, Stephen logs in, and his drive I: points to “\\Test-DC-01\Common\Sales” and for Kate the drive I: points to “\\Test-DC-01\Common\Warehouse”.

The second example:

# Filename:	LogonScriptMappingOneDrive.ps1
# Date:              April 30, 2012
# Author:     Alex Dujakovic
# Description:  Logon script for domain AlexTest.Local
# Mapping one drive to different folders based on group membership
# ************************************************************
$ErrorActionPreference = "SilentlyContinue"
$strName = $env:username
$strComputerName = $env:ComputerName
# ************************************************************
$strOneDrive = "I:"
$strADgroupAccounting = "CN=Accounting,OU=Groups,OU=FirstLocation,DC=ALEXTEST,DC=LOCAL"
$strADgroupSales = "CN=Sales,OU=Groups,OU=FirstLocation,DC=ALEXTEST,DC=LOCAL"
$strADgroupWarehouse = "CN=Warehouse,OU=Groups,OU=FirstLocation,DC=ALEXTEST,DC=LOCAL"
$strPathToAccounting = "\\test-dc-01\Common\Accounting"
$strPathToSlales = "\\test-dc-01\Common\Sales"
$strPathWarehouse = "\\test-dc-01\Common\Warehouse"
$mappingOneDrive = @{
$strADgroupAccounting = $strPathToAccounting;
$strADgroupSales = $strPathToSlales;
$strADgroupWarehouse = $strPathWarehouse
}
# ************************************************************
$strADgroupHelpDesk = "Help Desk"
$strADgroupDeployManager = "Deployment Managers"
$strHelpDeskDrive = "X:"
$strDeployDrive = "Y:"
$strDeployMgrDrive = "Z:"
$strHomeDrive = "Q:"
$strPathToHelpDeskShare = "\\test-dc-01\HelpDesk$"
$strPathToUsersHomeShare = "\\test-dc-01\Users$"
$strPathDeployMgrShare = "\\test-dc-01\Common\Deployment"
$strPathDeploymentShare = "\\test-sccm-01\DeploymentShare$"
$strTime = Get-Date -Format "t"
$strDate = Get-Date -format "yyyy-MM-dd"
$strFile = Get-Date -format "yyyy-MM"
$strFileName = "\\test-dc-01\LoginAndOutFiles$\"
# ************************************************************
function ListADGroup-Member {
BEGIN{}
PROCESS{
$strFilter = "(&(objectCategory=User)(samAccountName=$_))"
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = $strFilter
$objPath = $objSearcher.FindOne()
$objUser = $objPath.GetDirectoryEntry()
$strUserHomeDrive = $objUser.sAMAccountName
$DN = $objUser.distinguishedName
$ADVal = [ADSI]"LDAP://$DN"
if (!($ADVal.memberOf.Value -eq $Null)){
$GroupName = $ADVal.memberOf.Value
foreach($gp in $GroupName)
  {
    if($mappingOneDrive.ContainsKey($gp))
    {
       if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strOneDrive'") )
          {net use /persistent:yes $strOneDrive $($mappingOneDrive.$gp) | Out-Null}
    }
   if($gp | Select-String -pattern $strADgroupHelpDesk)
      {if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strHelpDeskDrive'") )
          {net use /persistent:yes $strHelpDeskDrive $strPathToHelpDeskShare | Out-Null}
    }
    if($gp | Select-String -pattern $strADgroupDeployManager)
      {if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strDeployDrive'") )
          {net use /persistent:yes $strDeployDrive $strPathDeploymentShare | Out-Null}
    }
    if($gp | Select-String -pattern $strADgroupDeployManager)
      {if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strDeployMgrDrive'") )
          {net use /persistent:yes $strDeployMgrDrive $strPathDeployMgrShare | Out-Null}
    }
}
}
}
END{
# Map a user's home drive
    if ( !(Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$strHomeDrive'") )
       {$strPathToUsersHomeShare = $strPathToUsersHomeShare + "\" + $strUserHomeDrive
       net use /persistent:yes $strHomeDrive $strPathToUsersHomeShare | Out-Null}
    }
}
# End of function ListADGroup-Member
$strName | ListADGroup-Member
$strFileName += [string]$strFile + ".txt"
$strDate + "," + $strTime + "," + $strName + "," + $strComputerName + "," + "Logon" | Out-File $strFileName -append -Encoding ASCII

It is not difficult to set up PowerShell logon script. I hope that these example scripts can help you to implement PowerShell scripts in your organization. In addition, you can read my post with title: PowerShell ADAssist Tool, where I present an application I use to harness stats data produced by logon/logoff scripts created with PowerShell.


 

One thought on “PowerShell Logon Script Example

Leave a Reply

Your email address will not be published. Required fields are marked *