mardi 10 mars 2015

Powershell : Server's remote inventory

Hi !

Frequently, when working with technology, you have to inventory servers. You might need reports on group of server for particular jobs.

I developed a small script which lists of your servers.

It needs a CSV file which consists of a single column like this:

ServerName
Server1
Server2
Server3
[...]

Output is in an excel file that you can then use at will.

Enjoy !

Download the script.


<# ==============================================================================================

    Name : Server Inventory (Get-ServerInventory.ps1)
    Description : Get informations from remote servers with WMI and ouput in an Excel File                

    Author : Pierre-Alexandre Braeken
    Date : 10 March 2015   
    Thanks : Jesse Hamrick (https://gist.github.com/BDollar/5455098)
             https://social.technet.microsoft.com/Forums/windowsserver/en-US/6bfeeb89-8fa8-4e6b-8588-cabe7f7291ea/excel-with-powershell-and-this-big-problem-of-locale
             http://stackoverflow.com/questions/4105224/how-to-set-culture-in-powershell
   
    * Select list of servers from a CSV file with an OpenFileDialog
    * Get remotely Servers informations with WMI and Powershell :
    * General (Domain, role in the domain, hardware manufacturer, type and model, cpu number, memory capacity, operating system and sp level)
    * System (BIOS name, BIOS version, hardware serial number, time zone, WMI version, virtual memory file location, virtual memory current usage, virtual memory peak usage and virtual memory allocated)
    * Processor (Processor(s), processor type, family, speed in Mhz, cache size in GB and socket number)
    * Memory (Bank number, label, capacity in GB, form and type)
    * Disk (Disk type, letter, capacity in GB, free space in GB + display a chart Excel)
    * Network (Network card, DHCP enable or not, Ip address, subnet mask, default gateway, Dns servers, Dns registered or not, primary and secondary wins and wins lookup or not)
    * Installed Programs (Display name, version, install location and publisher)
    * Share swith NTFS rights (Share name, user account, rights, ace flags and ace type)
    * Services (Display name, name, start by, start mode and path name)
    * Scheduled Tasks (Name, last run time, next run time and run as)
    * Printers (Locationm, name, printer state and status, share name and system name)
    * Process (Name, Path and sessionID)
    * Local Users (Groups, users)
    * ODBC Configured (dsn, Server, Port, DatabaseFile, DatabaseName, UID, PWD, Start, LastUser, Database, DefaultLibraries, DefaultPackage, DefaultPkgLibrary, System, Driver, Description)
    * ODBC Drivers Installed (Driver, DriverODBCVer, FileExtns, Setup)   
    * MB to GB conversion
    * Display of the progress of the script

# ============================================================================================== #>

mardi 5 août 2014

"The licensing mode for the Remote Desktop Session Host server is not configured" and Cannot find the Remote Desktop Session Host Configuration tool in Windows Server 2012R2 ?

Dude, the Remote Desktop Session Host Configuration tool no longer exists in Windows Server 2012 :-p

But you still have to configure the licensing mode. You can dot it with GPO through Active Directory.

You can also do it via a local policy.

-->

Run > gpedit.msc

Computer Configuration>Administrative Templates>Windows Components>Remote Desktop Services>Remote Desktop Session Host







vendredi 11 juillet 2014

Add or remove permissions on directory with Powershell

Hi,

If you have to add or remove lot of permissions on different directories, it could be a pain.

But not with Powershell :-)

I write several functions to easily do it.

function Remove-Inheritance($folderPath) {
    $isProtected = $true
    $preserveInheritance = $true
   
    $oFS = New-Object IO.DirectoryInfo($folderPath)
    $DirectorySecurity = $oFS.GetAccessControl([System.Security.AccessControl.AccessControlSections]::Access)
   
    $DirectorySecurity.SetAccessRuleProtection($isProtected, $preserveInheritance)
   
    $oFS.SetAccessControl($DirectorySecurity)
}

function Remove-NTFSPermissions($folderPath, $accountToRemove, $permissionToRemove) {
    $fileSystemRights = [System.Security.AccessControl.FileSystemRights]$permissionToRemove
    $inheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
    $propagationFlag = [System.Security.AccessControl.PropagationFlags]"None"
    $accessControlType =[System.Security.AccessControl.AccessControlType]::Allow

    $ntAccount = New-Object System.Security.Principal.NTAccount($accountToRemove)
    if($ntAccount.IsValidTargetType([Security.Principal.SecurityIdentifier])) {
        $FileSystemAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($ntAccount, $fileSystemRights, $inheritanceFlag, $propagationFlag, $accessControlType)
       
        $oFS = New-Object IO.DirectoryInfo($folderPath)
        $DirectorySecurity = $oFS.GetAccessControl([System.Security.AccessControl.AccessControlSections]::Access)
       
        $DirectorySecurity.RemoveAccessRuleAll($FileSystemAccessRule)
       
        $oFS.SetAccessControl($DirectorySecurity)
       
        return "Permissions " + $permissionToRemove + " Removed on " + $folderPath + " folder"
    }
    return 0
}

function Add-NTFSPermissions($folderPath, $accountToAdd, $permissionToAdd) {
    $fileSystemRights = [System.Security.AccessControl.FileSystemRights]$permissionToAdd
    $inheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
    $propagationFlag = [System.Security.AccessControl.PropagationFlags]"None"
    $accessControlType =[System.Security.AccessControl.AccessControlType]::Allow

    $ntAccount = New-Object System.Security.Principal.NTAccount($accountToAdd)
    if($ntAccount.IsValidTargetType([Security.Principal.SecurityIdentifier])) {
        $FileSystemAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($ntAccount, $fileSystemRights, $inheritanceFlag, $propagationFlag, $accessControlType)
       
        $oFS = New-Object IO.DirectoryInfo($folderPath)
        $DirectorySecurity = $oFS.GetAccessControl([System.Security.AccessControl.AccessControlSections]::Access)
       
        $DirectorySecurity.AddAccessRule($FileSystemAccessRule)
       
        $oFS.SetAccessControl($DirectorySecurity)
       
        return "Permissions " + $permissionToAdd + " Added on " + $folderPath + " folder for " + $accountToAdd
    }
    return 0
}


Usage examples :


$folders = "\\server\c$\TestDirectory"

##Remove Inheritance from Top Folder and Child Objects
Foreach($folder in $folders) {
    Remove-Inheritance $folder
    Remove-NTFSPermissions $folder "Authenticated Users" "Read,Modify"
    Remove-NTFSPermissions $folder "Creator owner" "Read,Modify"
    Get-ChildItem -Path $folder -Recurse | ?{$_.PSisContainer} `
    | foreach {
        $subfolder = $_.FullName
        Remove-Inheritance $subfolder
        Remove-NTFSPermissions $subfolder "Authenticated Users" "Read,Modify"
        Remove-NTFSPermissions $subfolder "Creator owner" "Read,Modify"
        Add-NTFSPermissions $subfolder "Authenticated Users" "Read,Modify"       
      }
}








Get remote information of a server in Powershell ("Computer Name","Operating System","Manufacturer","Model","RAM","CPU","IPV4","diskData") Get-ADComputerDetails

Hi !

Your manager wants to know informations about servers joined to the company's Active Directory and you want to retrieve informations with Powerhsell ?

Let's get started !

This script will retrieve servers informations in a CSV file like this :

"Computer Name","Operating System","Manufacturer","Model","RAM","CPU","IPV4","diskData"
"VirtualServer","Windows Server 2008 R2 Standard","VMware, Inc.","VMware Virtual Platform","8 GB","2","10.193.17.42","C: 14.47 GB / 39.9 GB - D: 23.48 GB / 100 GB"
"PhysicalServer","Windows Server 2008 R2 Standard","IBM","IBM System x3550 M4 Server -[***43*G]-","32 GB","1","10.193.17.217","C: 33.36 GB / 100 GB - D: 373.54 GB / 456.61 GB"

$ADComputerProperties = @(`
"Operatingsystem",
"OperatingSystemServicePack",
"Created",
"Enabled",
"LastLogonDate",
"IPv4Address",
"CanonicalName"
)

$SelectADComputerProperties = @(`
"Name",
"OperatingSystem",
"OperatingSystemServicePack",
"Created",
"Enabled",
"LastLogonDate",
"IPv4Address",
"CanonicalName"
)

$servers = Get-ADComputer -Filter * -SearchBase "ou=servers,ou=IT resources,DC=ad,DC=dieteren,DC=be" -Properties $ADComputerProperties | select $SelectADComputerProperties
Foreach ($server in $servers)
{
    $hostName = $server.Name
    $operatingSystem = $server.OperatingSystem
    $serverInfo = (Get-WmiObject -Computername $hostName Win32_ComputerSystem)
    $manufacturer = $serverInfo.Manufacturer
    $model = $serverInfo.Model
    $displayGB = [math]::round($serverInfo.TotalPhysicalMemory/1024/1024/1024, 0)
    $ipv4 = $server.IPv4Address
    $serverDiskInfo = (Get-WmiObject -Computername $server.Name win32_logicaldisk -Filter "drivetype='3'")

    $cpu = @(Get-WmiObject -Class Win32_processor -Computername $hostName)
    $c_socket = $cpu.count
    $c_core = $cpu[0].NumberOfCores * $c_socket
    $c_logical = $cpu[0].NumberOfLogicalProcessors * $c_socket
  
    $psobject = New-Object -TypeName psObject -Property ([ordered]@{
        'Computer Name' = $hostName
        'Operating System' = $operatingSystem
        'Manufacturer' = $manufacturer
        'Model' = $model
        'RAM' = "$displayGB GB"
        'CPU' = $c_socket
        'IPV4' = $ipv4
    })

    $psobject | Add-Member -type NoteProperty -name diskData -Value NotSet
   
    $i=0
    Foreach ($disk in $serverDiskInfo) {       
        $diskSize = [math]::Round($disk.size / 1gb,2)
        $diskFreeSpace = [math]::Round($disk.freespace / gb,2)                               
        Write-Host "$($disk.deviceid) $diskFreeSpace GB / $diskSize GB"      
        if($i -eq 0) {
            $psobject.diskData = "$($disk.deviceid) $diskFreeSpace GB / $diskSize GB"
        }
        else {
            $psobject.diskData += " - $($disk.deviceid) $diskFreeSpace GB / $diskSize GB"
        }
        $i++
    }     
    
   
    $psobject | Export-Csv C:\ComputerDetails.csv -Append 
}



lundi 16 juin 2014

Microsoft DFS-R problem : The sysvol permissions for one or more GPOs on this domain controller are not in sync with the permissions for the GPOs on the baseline domain

Hello,
Recently, I encountered a Distributed File System Replication problem in our Active Directory.
Notice : pay attention that the AD replication and Sysvol replication are two very different things. Indeed, the replication of Sysvol is done wit DFS mechanism which replaced FRS since 2008.
In windows 2012r2, through the new Group Policy Management, when I click on "Detect Now", results show ACLs not in sync with the baseline domain...



The sysvol permissions for one or more GPOs on this domain controller are not in sync with the permissions for the GPOs on the baseline domain

First thing, the level of the domain and forest functionnal level is 2008r2.

I check first the DFS Replication with tools provided by Microsoft in the DFS Management Console on the baseline DC (Health Report, Propagation test et Propagation report). The result was ok...
You can use dfsrdiag to check DFS-R operations.
dfsrdiag.exe syncnow /rgname:“domain system volume” /partner:yourBaselineDC /time:1 /verbose

Steps to solve the problem :

1. DNS check on all DCs (the first DNS server must be the DC itself)
2. Resume replication on volume c:\ on the baseline DC
Get the volumeGuid
GWMI -namespace root\cimv2 -class win32_volume | FL -property DriveLetter, DeviceID
Resume replication on volume
wmic /namespace:\\root\microsoftdfs path dfsrVolumeConfig where 'volumeGuid="ce3fb9d1-6ecf-447e-b99c-6e451cab8012"' call ResumeReplication
3. Force the authoritative synchronisation for the DFSR-replicated SYSVOL (was the "D4" when we used FRS in the past) from the PDC Emulator (http://support.microsoft.com/kb/2218556)
a)
Get-ADObject "CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=YourPDCEmulation,OU=Domain Controllers,DC=domain,DC=com" -properties * 
b) 
Set-ADObject "CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=YourPDCEmulation,OU=Domain Controllers,DC=domain,DC=com" -Replace @{"msDFSR-Enabled"="FALSE";"msDFSR-Options"=1} 
c) On all other DCs
Set-ADObject "CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=DCx,OU=Domain Controllers,domain,DC=com" -Replace @{"msDFSR-Enabled"="FALSE"} 
d) repadmin /syncall /AdeP
e) Start of the DFSR service on the PDC Emulator.
f) On the PDC Emulator :
Set-ADObject "CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=YourPDCEmulation,OU=Domain Controllers,DC=domain,DC=com" -Replace @{"msDFSR-Enabled"="TRUE"} 
g) repadmin /syncall /AdeP
h) From the PDC Emulator in an elevated command prompt : DFSRDIAG POLLAD
i)  Start of the DFSR service on all other DCs
j) On all other DCs  :
Set-ADObject "CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=DCx,OU=Domain Controllers,domain,DC=com" -Replace @{"msDFSR-Enabled"="TRUE"} 
k) On all other non-authoritative DCs  in an elevated command prompt : DFSRDIAG POLLAD
4) Then reset permissions of all listed GPOs 
In Group Policy Management Console, click on a GPO>delegation tab>Advanced>Advanced>Restore Defaults (or make a script to restore defaults permissions and to keep custom permissions.


Note :

Remember that it's recommended to edit your GPOs from the PDC Emulator. The PDC Emulator is the prefered admistration entry point for services like GPOs and DFS.

When using Remote Server Administration Tools, you can choose the domain controlter to use.

In Administrative Users and Computers console>right click on your domain>change domain controller



Then choose the DC to use.