Tag Archive for powershell

Logon script to copy 2 folders into a user’s Roaming Profile

Script

The Task

Our users are logging into several Terminal Server Farms where they are running a TM1 application client which connects to the main TM1 Server. On opening the client it is meant to put 2 folders in their profile under the AppData folder. This is a folder called Applix which also contains another folder called TM1.

We have roaming profiles where we have a profile drive and a home drive and the AppData folder is redirected to the user’s Home Drive. It seems that this application does not cope well with creating the Applix folder on the redirected Home Folder location

However we have found it works fine when you have a straight roaming profile with no redirected folders!

So what do we need to happen?

  1. A user logs on to a Terminal Server Farm
  2. At logon a GPO containing a PowerShell script to do this task will run
  3. The script will test that the folder path exists first \\ServerXYZ\Home\Username\AppData\Roaming and if it does, it will do nothing
  4. If the path doesn’t exist, it will put a folder called Applix in the following path \\ServerXYZ\Home\Username\AppData\Roaming
  5. Note, we put the Applix folder on the Terminal Servers as C:\Applix and the script picks this up for copying from this location

The PowerShell Script

if (!(Test-path “\\ServerXYZ\Home\$env:USERNAME\AppData\Roaming\Applix”))
{
Copy-Item -path “C:\Applix” -Recurse -Destination “\\ServerXYZ\Home\$env:USERNAME\AppData\Roaming\Applix” -Container
}

 

Quest ActiveRoles Management Shell for Active Directory

untitled

Quest ActiveRoles Management Shell for Active Directory

The ActiveRoles Management Shell for Active Directory is a set of predefined commands for Windows PowerShell, the new command line and scripting language developed by Microsoft. These commands are designed to help administrators automate common, repetitive and bulk management tasks such as creating, removing or updating objects in Active Directory.
By using the ActiveRoles Management Shell for Active Directory to build your scripts, you can harness Quest ActiveRoles Server to leverage proven rules, roles, workflow and attestation features giving you a robust management option for Windows PowerShell and Active Directory.

The management operations are performed either via the Quest ActiveRoles Server proxy service or by directly accessing directory data on domain controllers. In both cases, the ActiveRoles Management Shell provides a flexible scripting platform that can reduce the complexity of current Microsoft Visual Basic scripts. Tasks that previously required many lines in Visual Basic scripts can now be done by using as little as one line of code in the ActiveRoles Management Shell.

Installing the ActiveRoles Management Shell

q1

q2

q3

q4

q5

Opening the ActiveRoles Management Shell

You can open the ActiveRoles Management Shell by using either of the
following procedures. Each procedure loads the ActiveRoles Management Shell
snap-in into Windows PowerShell. If you do not load the ActiveRoles
Management Shell snap-in before you run a command (cmdlet) provided by
that snap-in, you will receive an error.

To open the ActiveRoles Management Shell from the Programs menu

  • Select Start | All Programs | Quest Software | ActiveRoles Management Shell for Active Directory.

To add the ActiveRoles Management Shell snap-in from Windows
PowerShell

  • Select Start | All Programs | Windows PowerShell 1.0 | Windows PowerShell.
  • At the Windows PowerShell prompt, enter the following command:
  • Add-PSSnapin Quest.ActiveRoles.ADManagement

Using the ActiveRoles Management Shell

  • Select Start | All Programs | Quest Software | ActiveRoles Management Shell for Active Directory.

q0

Admin Guide

Quest ActiveRoles Management Shell Admin Guide

Example Command to check for inactive users in Active Directory

get-qaduser -SizeLimit 0 | Where-Object{$_.LastLogon -lt $limit -OR $lastLogon -ne $null} | Sort-Object LastLogon | Select-Object Name, SAMAccountName, LastLogon | Export-CSV C:\PATH\TO\file.csv

 

VBScript to get Active Directory User Logon Information, Disable and Move

vb

What does this VBScript script do?

  • Checks all accounts to determine what needs to be disabled.
  • If LastLogonTimeStamp is Null and object is older than specified date, it is disabled and moved.
  • If account has been used, but not within duration specified, it is disabled and moved.
  • If account is already disabled it is left where it is.

Please adjust the variables according to your AD and copy into a Notepad file with an extension of .vbs and run

  • ADVBScript_Script.vbs

‘===========================================================================
‘ Checks all accounts to determine what needs to be disabled.
‘ If LastLogonTimeStamp is Null and object is older than specified date, it is disabled and moved.
‘ If account has been used, but not within duration specified, it is disabled and moved.
‘ If account is already disabled it is left where it is.
‘ Created 23/7/09 by Grant Brunton
‘===========================================================================

‘===========================================================================
‘ BEGIN USER VARIABLES
‘===========================================================================

‘ * Change this to your domain *
‘DSEroot=”DC=domain,DC=local”

‘ Flag to enable the disabling and moving of unused accounts
‘ 1 – Will Disable and move accounts
‘ 0 – Will create ouput log only
bDisable=0

‘ Number of days before an account is deemed inactive
‘ Accounts that haven’t been logged in for this amount of days are selected
iLogonDays=30

‘ LDAP Location of OUs to search for accounts
‘ LDAP location format eg: “OU=Users,OU=Test”
strSearchOU=”OU=Users”

‘ Search depth to find users
‘ Use “OneLevel” for the specified OU only or “Subtree” to search all child OUs as well.
strSearchDepth=”OneLevel”

‘ Location of new OU to move disabled user accounts to
‘ eg: “OU=Disabled Users,OU=Test”
strNewOU=”OU=_Disabled”

‘ Log file path (include trailing \ )
‘ Use either full directory path or relational to script directory
strLogPath=”.\logs\”

‘ Error log file name prefix (tab delimited text file. Name will be appended with date and .err extension)
strErrorLog=”DisabledAccounts_”

‘ Output log file name prefix (tab delimited text file. Name will be appended with date and .log extension)
strOutputLog=”DisabledAccounts_”

‘===========================================================================
‘ END USER VARIABLES
‘===========================================================================

‘===========================================================================
‘ MAIN CODE BEGINS
‘===========================================================================
sDate = Year(Now()) & Right(“0” & Month(Now()), 2) & Right(“0” & Day(Now()), 2)
Set oFSO=CreateObject(“Scripting.FileSystemObject”)
If Not oFSO.FolderExists(strLogPath) Then CreateFolder(strLogPath)
Set output=oFSO.CreateTextFile(strLogPath & strOutputLog & sDate & “.log”)
Set errlog=oFSO.CreateTextFile(strLogPath & strErrorLog & sDate & “.err”)
output.WriteLine “Sam Account Name” &vbTab& “LDAP Path” &vbTab& “Last Logon Date” &vbTab& “Date Created” &vbTab& “Home Directory”
errlog.WriteLine “Sam Account Name” &vbTab& “LDAP Path” &vbTab& “Problem” &vbTab& “Error”

Set rootDSE = GetObject(“LDAP://rootDSE”)
Set objConnection = CreateObject(“ADODB.Connection”)
objConnection.Open “Provider=ADsDSOObject;”
Set ObjCommand = CreateObject(“ADODB.Command”)
ObjCommand.ActiveConnection = objConnection
ObjCommand.Properties(“Page Size”) = 10
DSEroot=rootDSE.Get(“DefaultNamingContext”)

Set objNewOU = GetObject(“LDAP://” & strNewOU & “,” & DSEroot)
ObjCommand.CommandText = “<ldap: “=”” &=”” strsearchou=”” “,”=”” dseroot=””>;(&(objectClass=User)(objectcategory=Person));adspath;” & strSearchDepth

msgbox “<ldap: “=”” &=”” strsearchou=”” “,”=”” dseroot=””>;(&(objectClass=User)(objectcategory=Person));adspath;” & strSearchDepth

Set objRecordset = ObjCommand.Execute

On Error Resume Next

While Not objRecordset.EOF
LastLogon = Null
intLogonTime = Null

Set objUser=GetObject(objRecordset.fields(“adspath”))

If DateDiff(“d”,objUser.WhenCreated,Now) > iLogonDays Then
Set objLogon=objUser.Get(“lastlogontimestamp”)
If Err.Number &lt;&gt; 0 Then
WriteError objUser, “Get LastLogon Failed”
DisableAccount objUser, “Never”
Else
intLogonTime = objLogon.HighPart * (2^32) + objLogon.LowPart
intLogonTime = intLogonTime / (60 * 10000000)
intLogonTime = intLogonTime / 1440
LastLogon=intLogonTime+#1/1/1601#

If DateDiff(“d”,LastLogon,Now) > iLogonDays Then
DisableAccount objUser, LastLogon
End If
End If
End If
WriteError objUser, “Unknown Error”
objRecordset.MoveNext
Wend
‘===========================================================================
‘ MAIN CODE ENDS
‘===========================================================================

‘===========================================================================
‘ SUBROUTINES
‘===========================================================================
Sub CreateFolder( strPath )
If Not oFSO.FolderExists( oFSO.GetParentFolderName(strPath) ) Then Call CreateFolder( oFSO.GetParentFolderName(strPath) )
oFSO.CreateFolder( strPath )
End Sub

Sub DisableAccount( objUser, lastLogon )
On Error Resume Next
If bDisable <> 0 Then
If objUser.accountdisabled=False Then
objUser.accountdisabled=True
objUser.SetInfo
WriteError objUser, “Disable Account Failed”
objNewOU.MoveHere objUser.adspath, “CN=”&amp;objUser.CN
WriteError objUser, “Account Move Failed”
Else
Err.Raise 1,,”Account already disabled. User not moved.”
WriteError objUser, “Disable Account Failed”
End If
End If
output.WriteLine objUser.samaccountname &vbTab& objUser.adspath &vbTab& lastLogon &vbTab& objUser.whencreated &vbTab& objUser.homedirectory
End Sub

Sub WriteError( objUser, strProblem )
If Err.Number &lt;&gt; 0 Then
errlog.WriteLine objUser.samaccountname &vbTab& objUser.adspath &vbTab& strProblem &vbTab& Replace(Err.Description,vbCrlf,””)
Err.Clear
End If
End Sub

‘===========================================================================
‘ END SUBROUTINES
‘===========================================================================

Powershell Script to get Active Directory User Logon Information

PowerShell

To get the last logon Date/Time of Users in AD

$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$ADSearch = New-Object System.DirectoryServices.DirectorySearcher
$ADSearch.PageSize = 100
$ADSearch.SearchScope = “subtree”
$ADSearch.SearchRoot = “LDAP://$Domain”
$ADSearch.Filter = “(objectClass=user)”
$ADSearch.PropertiesToLoad.Add(“distinguishedName”)
$ADSearch.PropertiesToLoad.Add(“sAMAccountName”)
$ADSearch.PropertiesToLoad.Add(“lastLogonTimeStamp”)
$userObjects = $ADSearch.FindAll()

foreach ($user in $userObjects)
{
$dn = $user.Properties.Item(“distinguishedName”)
$sam = $user.Properties.Item(“sAMAccountName”)
$logon = $user.Properties.Item(“lastLogonTimeStamp”)
if($logon.Count -eq 0)
{
$lastLogon = “Never”
}
else
{
$lastLogon = [DateTime]$logon[0]
$lastLogon = $lastLogon.AddYears(1600)
}

“””$dn””,$sam,$lastLogon”
}

Script explained by David Hoelzer

Many Thanks for this excellent explanation

Scripting Video

 

Microsoft Windows Powershell

What is PowerShell?

Windows PowerShell is Microsoft’s task automation framework, consisting of a command-line shell and associated scripting language built on top of .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems.

In PowerShell, administrative tasks are generally performed by cmdlets (pronounced command-lets), specialized .NET classes implementing a particular operation. Sets of cmdlets may be combined together in scripts, executables (which are standalone applications), or by instantiating regular .NET classes (or WMI/COM Objects) These work by accessing data in different data stores, like the filesystem or registry, which are made available to the PowerShell runtime via Windows PowerShell providers.

Windows PowerShell also provides a hosting API with which the Windows PowerShell runtime can be embedded inside other applications. These applications can then use Windows PowerShell functionality to implement certain operations, including those exposed via the graphical interface. This capability has been used by Microsoft Exchange Server 2007  to expose its management functionality as PowerShell cmdlets and providers and implement the graphical management tools as PowerShell hosts which invoke the necessary cmdlets. Other Microsoft applications including Microsoft SQL Server 2008 also expose their management interface via PowerShell cmdlets. With PowerShell, graphical interface-based management applications on Windows are layered on top of Windows PowerShell. A PowerShell scripting interface for Windows products is mandated by the Common Engineering Criteria.

Windows PowerShell includes its own extensive, console-based help, similar to man pages in Unix shells, via the Get-Help cmdlet.

Microsoft Page for PowerShell

http://technet.microsoft.com/en-us/library/bb978526.aspx

5 Introductory Videos

http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx

Hey Scripting Guy WebPage

http://blogs.technet.com/b/heyscriptingguy/

Technet Virtual Lab – PowerShell

https://msevents.microsoft.com/CUI/EventDetail.aspx?culture=en-US&EventId=1032314395

Script Resources for IT Professionals

http://gallery.technet.microsoft.com/scriptcenter