# Import the Active Directory module for the Get-ADComputer CmdLet Import-Module ActiveDirectory # Get today's date for the report $today = Get-Date # Setup email parameters $subject = "RDP Sessions Report - " + $today $priority = "HIGH" $smtpServer = "SMTPSERVERHERE" $emailFrom = "RDPReport@YOURCO.local" $emailTo = "YOU@YOURCO.local" # Create a fresh variable to collect the results. You can use this to output as desired write-host "" write-host "" $SessionList = "ACTIVE SERVER SESSIONS REPORT - " + $today + "`n`n" # Query Active Directory for computers running a Server operating system $Servers = Get-ADComputer -Filter {OperatingSystem -like "*server*"} -Properties * | where{$_.description -notlike "Failover*"} # Loop through the list to query each server for login sessions ForEach ($Server in $Servers) { $ServerName = $Server.Name # When running interactively, uncomment the Write-Host line below to show which server is being queried # Write-Host "Querying $ServerName" # Run the qwinsta.exe and parse the output $queryResults = (qwinsta /server:$ServerName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv) # Pull the session information from each instance ForEach ($queryResult in $queryResults) { $RDPUser = $queryResult.USERNAME $sessionType = $queryResult.SESSIONNAME # We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number If (($RDPUser -match "[a-z]") -and ($RDPUser -ne $NULL)) { # When running interactively, uncomment the Write-Host line below to show the output to screen # Write-Host $ServerName logged in by $RDPUser on $sessionType $SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser } } } # When running interactively, uncomment the Write-Host line below to see the full list on screen $SessionList write-host "" write-host "" $SessionList2 = "Disconnected SERVER SESSIONS REPORT - " + $today + "`n`n" ForEach ($Server in $Servers) { $ServerName = $Server.Name # When running interactively, uncomment the Write-Host line below to show which server is being queried # Write-Host "Querying $ServerName" # Run the qwinsta.exe and parse the output $queryResults = (qwinsta /server:$ServerName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv) # Pull the session information from each instance ForEach ($queryResult in $queryResults) { $RDPUser = $queryResult.USERNAME $sessionType = $queryResult.SESSIONNAME $state=$queryResult.STATE # We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number If (($RDPUser -ne $NULL) -and ($sessionType -ne "console" )-and ($sessionType -ne "services")-and ($RDPUser -ne "65536" ) -and ($sessionType -ne "[1-9]") -and ($state -ne "Active")) { # When running interactively, uncomment the Write-Host line below to show the output to screen # Write-Host $ServerName logged in by $RDPUser on $sessionType $SessionList2 = $SessionList2 + "`n`n" + $ServerName + " has a disconnected session open by " + $sessionType } } } $SessionList2 $sessionlistfinal = $sessionlist + "`n`n" + $sessionlist2 # Send the report email Send-MailMessage -To $emailTo -Subject $subject -Body $SessionListfinal -SmtpServer $smtpServer -From $emailFrom -Priority $priority
Category Archives: Scom Tips
PowerShell Script RDP Sessions List
Powershell Search Thru IIS Logs for Text String
GET-CHILDITEM C:\Logs\W3SVC2 -recurse | SELECT-STRING –pattern YOURTEXT | export-csv -append -path “c:\logs\hits.csv”
PowerShell Reboot AD Based Computers
$computers = Get-ADComputer -SearchBase “OU=NYC,DC=Contoso,DC=Contoso,DC=com” -Filter * | Select-Object -ExpandProperty DNSHostName
Write-Host “Rebooting computers”
Write-Host “$($computers.Count) computers”
#$computers[0] | fl
Restart-Computer -ComputerName $computers -Force -ThrottleLimit 25
PowerShell Dump ACL of a Path Folder
$OutFile = “C:\Permissions.csv”
$Header = “Folder Path,IdentityReference,AccessControlType,IsInherited,InheritanceFlags,PropagationFlags”
Del $OutFile
Add-Content -Value $Header -Path $OutFile
$RootPath = “\\server\c$”
$Folders = dir $RootPath -recurse | where {$_.psiscontainer -eq $true}
foreach ($Folder in $Folders){
$ACLs = get-acl $Folder.fullname | ForEach-Object { $_.Access }
Foreach ($ACL in $ACLs){
$OutInfo = $Folder.Fullname + “,” + $ACL.IdentityReference + “,” + $ACL.AccessControlType + “,” + $ACL.IsInherited + “,” + $ACL.InheritanceFlags + “,” + $ACL.PropagationFlags
Add-Content -Value $OutInfo -Path $OutFile
}}
SCOM Maintenance Mode Group of Servers
From – https://gallery.technet.microsoft.com/scriptcenter/SCOM-2012-Maintenance-Mode-9187b6c2#content
# PS C:\SCOMMaintenanceModeFromFile> .\SCOM-MM.Ps1 -FileName servers.txt -Duration 10
#
########################################################################
# Functions
########################################################################
#####################################
# Module
#####################################
param(
[string]$FileName,
[string]$Duration
)
Import-Module OperationsManager
new-SCOMManagementGroupConnection -ComputerName Localhost
#####################################
# Script
#####################################
$path = “C:\MM”
$domain = “myco.com”
#####################################
# Params
#####################################
#Get Server list
$MyFile = Get-content “$path\$Filename”
$MyFile
foreach($srv in $MyFile)
{
Write-host “ServerName : $srv”
$startTime = [DateTime]::Now
$endTime = $startTime.AddMinutes($Duration)
$srv += “.$domain”
$Class = get-SCOMclass | where-object {$_.Name -eq “Microsoft.Windows.Computer”};
$Instance = Get-SCOMClassInstance -Class $Class | Where-Object {$_.Displayname -eq “$srv”};
Start-SCOMMaintenanceMode -Instance $Instance -Reason “PlannedOther” -EndTime $endTime -Comment “Scheduled SCOM Maintenance Window”
}
WMI Admin Access without Domain Admin Privilege
Setting up WMI-access through AD & GPO
First – Setting done from Active Directory
Open the Active Directory Administrative Center:
•Go to MyCo -> Users
•Right click and select New -> User
•Create user as a normal user and ways User UPN logon to wmiuser@MyCo.local
•Make sure Member of is set to Domain Users so that the user is in a valid group.
1 – Create the GPO (Group Policy Object)
Open the Group Policy Management:
•Create a new GPO and name it WMI Access
•Link it to MyCo.local domain (drag and drop the GPO on MyCo.local)
•Make sure that the GPO will be applied to all machines in the domain to be scanned (WMI adjust Security Filtering, etc.)
2 – Settings GPO
DCOM
•Right-click WMI Access (which is the GPO we just created), select Edit
•Go to Computer Configuration -> Policies -> Windows Settings -> Security Settings -> Local Policies -> Security Options
•Select Properties at: DCOM: Machine Access Restrictions in Security Descriptor Definition Language (SDDL) syntax
•Check the Define this policy setting
•Select Edit Security …
•Click Add …
•Under Enter the object names to select: Enter MyCowmiuser and click Check Names. The user is now filled in automatically
•Click OK
•Select wmiuser (wmiuser@MyCo.local)
•Under Permissions: Tick Allow on both Local Access and Remote Access
•Click OK
•Click OK
•Select Properties under: DCOM: Machine Launch Restrictions in Security Descriptor Definition Language (SDDL) syntax
•Check Define this policy setting
•Select Edit Security …
•Click Add …
•Under Enter the object names to select: Enter MyCowmiuser and click Check Names. The user is now filled in automatically
•Click OK
•Select wmiuser (wmiuser@MyCo.local)
•Under Permissions: Tick Allow at Local Launch, Remote Launch, Local Activation and Remote Activation
•Click OK
•Click OK
Firewall
•Right-click WMI Access (the GPO we just created), select Edit
•Go to Computer Configuration -> Policies -> Windows Settings -> Security Settings -> Windows Firewall with Advanced Security
•In the right pane, expand Windows Firewall with Advanced Security until Inbound Rules visible. Right-click on it
•Choose New Rule …
•Select Predefined and Windows Management Instrumentation (WMI) in the list
•Click Next
•Tick all the Windows Management Instrumentation-rules in the list (usually 3 pieces)
•Click Next
•Select Allow The Connection
•Click Finish
3 – Rights for WMI namespace
These settings can not be done with a regular GPO. For a user who is not Admin this step is critical and must be done exactly as instructed below. If not properly done, login attempts via WMI results in Access Denied.
•Write wmimgmt.msc in command prompt
•Right-click WMI Control, and select Properties
•Select the Security tab
•Select Root of the tree and click on Security
•Click Add …
•Under Enter the object names to select: Enter MyCowmiuser and click Check Names. The user is now filled in automatically
•Click OK
•Select wmiuser (wmiuser@MyCo.local)
•Select Allow for Execute Methods, Enable Account, Remote Enable and Read Security under Permissions for wmiuser
•Mark wmiuser and click Advanced
•Under the Permission tab: Select wmiuser
•Click Edit
•Under Applies To-list: Choose This namespace and all subnamespaces. It is very important that the rights are applied recursively down the entire tree!
•Click OK
•Click OK
•Click OK
•Click OK
Second – Settings done on each machine
4 – Verify
On the machines which are to be scanned by MyCoApp, make sure that the GPO is applied. To force an update:
•In a command prompt: type gpupdate/force
•Ensure that the GPO is applied: Enter gpresult/r
•Under COMPUTER SETTINGS in the printout, look for WMI Access (the GPO we created) under the Applied Group Policy Objects. If it is listed there, it means that it is applied to the machine.
•Scan machine with MyCoApp and enter MyCowmiuser as username and enter the correct password
•Verify the discovery result
5 – Additional Information
We recommend turning off UAC filtering on the target machines. It can be done by setting a registry key manually or through a GPO.
UAC can in some cases filter information through WMI so that the information is as complete as it could be. Usually you do not need to do this step, but if information is missing, do the following on the target machine:
•Open regedit
•Change the key:HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciessystemLocalAccountTokenFilterPolicy to “1”
•Close regedit
0 = Remote UAC access token filtering is enabled.
1 = Remote UAC is disabled.
Script to Update User Redirected Folders ACL
This script changes the owner of each folder within Redirected Folders to the administrators group. Then it grants full control to administrators and the user the folder is named after. It then changes the owner back to that user. It only works if your usernames are exactly the same as your folder names. Also it does not work for usernames with spaces in them.
By making the user the owner of the folder it keeps folder redirection working properly.
REM This script does not work when folders have spaces in them.
REM This script must be run as an admin in an elevated command line.
REM This script changes the owner of each folder within Redirected Folders to the administrators group. Then it grants full control to administrators and the user the folder is named after. It then changes the owner to that user.
SETLOCAL
SET “sourcedir=C:\Redirected Folders”
PUSHD %sourcedir%
FOR /f “tokens=1*” %%a IN (
‘dir /b /a:d’
) DO (
takeown /F %%a /R /D Y
icacls %%a /grant %%a:^(OI^)^(CI^)F /T
icacls %%a /grant administrators:^(OI^)^(CI^)F /T
icacls %%a /setowner %%a /T
)
POPD
GOTO :EOF
Windows 2012 R2 Folder Redirection Step by Step
This guide will give you the steps to set up basic user profile redirection for User folders (Documents, Favorites, Desktop etc.)
1. Create Folder for Redirected Profiles
Create a new folder on your target server. Set the permissions to Apply to: This folder Only (disable inheritance) “Authenticated Users” to match the following:
–Traverse Folder / Execute File
–List Folder / Read Data
–Read Attributes
–Read Permission
IMPORTANT: Also Domain Admins give Full Control
2. Configure Sharing for Redirected Profiles Folder
Open the properties for the folder created in step 1, and select the “Sharing Tab” and Select Advanced Sharing. By default, the share name will be the same as the folder name, you can change this if desired.
–Check the share this folder box.
–Click the “Permissions” button, and again remove the “Everyone” group and add “Authenticated Users” with Full Control.
3. Configure User Profiles to Redirect to Shared Folder
User Profile Redirection is configured in Active Directory Users and Computers. Launch AD and navigate to the OU that contains the user(s) you wish to redirect.
Right click the user account and select “Properties” and navigate to the “Profile” tab. In the “Home Folder” section, click the Connect radio button, select the drive letter you want to assign and add the UNC path to the shared folder, followed by the %username% variable, which will auto-populate the username.
The UNC path should look like this:
\\[servername]\[sharename]\%username%
Click “Apply”
4. Configure Home Drives for Multiple AD Users!
If you are setting up Home Drives for multiple users, you can edit multiple user’s at once.
Select the users you wish to apply the policy to (Ctrl+Click or Shift+Click), then right click and select Properties, open the “Profile” tab, check the “Home Folder” box and set the drive letter and path (\\[servername]\[share]\%username%)
5. Configure GPO to Redirect Documents Folder
Open Group Policy Management and create a new Group Policy Object (or edit an existing one if that suits you better).
In the GPO, configure folder redirection under the following:
User Configuration-> Policies-> Windows Settings->Folder Redirection
Choose the “Documents” folder, right click and select “Properties”.
Change the “Setting:” field to “Basic- redirect everyone’s folder to the same location” and set the “Target folder location” to “Redirect to the user’s home directory”
6. Configure Settings for Step 4
Select the Settings tab in the Documents Properties window and set according to the requirements in your environment.
7. Configure Redirection for Additional Folders
To redirect a user’s Music, Pictures and Video folder, right click each of these folders in the GPO Editor and select properties.
Under the “Setting:” field select “Follow the Documents folder” to automatically redirect the folder to the user’s now redirected Documents folder.
8. Apply Changes for Users
These changes will automatically go into effect the next time that a user logs in to their PC. I have seen it take one or two logins to move all of the files over to the new home folder, so be sure to check and make sure all of the documents have moved.
For VIP users, I manually run gpupdate /force and reboot their PC, then had them log back in and checked that the redirection worked.
To verify that the redirection is functioning, open My Computer and look at the Home drive to see if it matches the contents of My Documents.
Recent Comments