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 
}