PowerShell to find usernames that have access - powershell

I am trying to get the ACL of a set of folders to see if a specific user is listed
For example
Users
|
---Person1
---Person2
---Person3
Person1 to 3 are home folders. We recently ran an icacls command to modify the folder permission. Some of them have the owner set to "IT Employee" instead of Person1
If it was only 3 folders, I would do this manually. However there are at least 1000 folders and manually would not be feasible to get the data back in a timely manner.
Basically there are 6 IT Employees and I want to make sure their name is not in any Person home folder (or it's sub folders). If it is there then I want to be able to remove them or at least get a console log.
I am using PowerShell 2 on Windows Server 2008
I can also execute VBScript or JavaScript

You could try something like this to get you started. I'm not connected to a network with a file server atm., so I'm not sure if Owner and IdentityReference contains DOMAIN\Username or SID (this happends for non-exisiting users, ex. deleted ones). I get <DOMAIN or ComputerName>\Username when I run it on m local machine. You may have to modify it to handle that.
$rootpath = "c:\users"
#Get all folders
Get-ChildItem -Path $rootpath -Recurse | Where-Object { $_.PSIsContainer }
#Get ACL for the folders
Get-Acl |
#Find ACLs with IT Employee-reference
Where-Object {
#Check if owner matches 'IT Employee' or ACL Access rules contains 'IT Employee'
if(($_.Owner -match 'IT Employee') -or ($_.Access | Where-Object { $_.IdentityReference.Value -match 'IT Employee' })) { $_ }
} |
#Process
ForEach-Object {
#Show folderpath...
$_.Path
#Here you could access the ACL-object $_, modify it (change owner/remove access rules) and save it by using 'Set-Acl -Path $_.Path -AclObject $_' etc.
}

Related

Im trying to create a powershell script that will find all of the groups or user names for multiple folders

I have successfully retrieved a list of folders from the selected drive and would like to iterate over this list for a list of groups or user names with access to the folder. What this means is that I am checking the permissions of each folder within the drive. Below is the code that I currently have.
#Import active directory module for running AD cmdlets
Import-Module activedirectory
#Get list of folders from the O drive
$folders = Get-ChildItem –Directory "O:\" | Select-Object -ExpandProperty Name
#for each folder retrieve the groups then export
ForEach ($folder in $folders)
{
$groups = Get-ACL "O:\$folder" | %{ $_.Access } | ft -property IdentityReference, AccessControlType, FileSystemRights
$folder | Export-CSV -Path FolderMembership.csv -Append
$groups | Export-CSV -Path FolderMembership.csv -Append
}
pause
When I run this code my csv file is filled with a length number and in between each length number are an arbitrary number of spaces that I believe coincide with the number of security groups for the folder that was supposed to be there. Can anyone help me figure out what is wrong with my get-ACL command? Also if there is a better command for this I would be happy to know what it is!

Remove network drive permissions of a user in all subdirectories

I am trying to remove a user from all subdirectories in a network share.
I have tried the following command: ICACLS X:\ /remove:g username /T
The command runs without failure (although it takes 3.5 hours due to the size of the shard drive) but after I check the permissions, the user's permissions are not deleted from anywhere.
If I navigate to a specific folder where I know that the user has access and run the command there (for example ICACLS X:\subdirectory /remove:g username /T ), it works just fine.
The issue seems to occur only if I try to run it from the root X:\ in which case, no permissions are deleted.
Any ideas why this might be the case?
P.S. I have F access on the root on the account I'm running the command with
Should do it with icacls /T. Unless the user running the command cannot read some directories. But if inheritance is enabled on the folders you probably have Administrators everywhere.
A simple PS Script can do it. With some try / catch around $acl | Set-Acl this can be used as a dry-mode in a non-privileged session. With a privileged session this will effectively replace the ACL on the directory.
$path = "X:"
$username = "Domain\User"
Get-Item -Path $path -Directory -Recurse | %{
$acl = Get-Acl -Path $_.FullName
$aces = $acl.Access | Where-Object { -not $_.IsInherited -and $_.IdentityReference.Value -eq $username }
if ($aces -ne $null -and $aces.Count -gt 0) {
Write-Host "Found $($aces.Count) ACE granted for $username on $($_.FullName)"
foreach($ace in $aces) {
$acl.RemoveAccessRule($ace)
}
$acl | Set-Acl -Path $_.FullName
}
}

How to export shared folder with permissions and groups associated

I'm working on a windows server 2008 r2 and I'm trying to export the configuration of shared folder with all the groups associated to them,permissions and file system permissions.
is there a way to do that?
maybe with powershell?
#edit: another problem is that I need to do that after a reboot, so I have to save the configuration in a file for example and then reimport it.
If you want to backup/restore all existing shares you could export/import the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Shares.
Backup:
reg export HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Shares shares.reg
Restore:
reg import shares.reg
net stop server && net start server
File/folder ACLs can be saved and restored like this:
Backup:
Get-WmiObject -Class Win32_Share -Filter 'Type = 0' | select -Expand Path | % {
$path = $_
Get-Acl $path | select #{n='Path';e={$path}}, Sddl
} | Export-Csv 'C:\path\to\acls.csv'
Restore:
Import-Csv 'C:\path\to\acls.csv' | % {
$acl = Get-Acl $_.Path
$acl.SetSecurityDescriptorSddlForm($_.Sddl)
Set-Acl -Path $_.Path -AclObject $acl
}
Interesting question, I think the only way to do so is manually getting the acl on original folder and then re-apply them to the copied folder. The cmdlet to be used are Get-Acl -path $youfolder, Copy-Item and Set-Acl
I'm working on a module (see here) that should be able to do this for you. It's a script module, so you can actually open it up and look at/modify the code. If you use it, you could do something like this (the Export-Csv call is commented out, but you can put it in after confirming this is the output you're looking for):
Get-WmiObject Win32_Share -ComputerName ServerName |
Get-AccessControlEntry #| Export-Csv -Path CsvLocation.csv
You'll get errors for built-in system shares, e.g., C$, so you may want to add an -ErrorAction SilentlyContinue and/or an -ErrorVariable to the Get-AccessControlEntry call.
To bring the permissions back in, you'd just feed the Get-AccessControl output into Add-AccessControlEntry:
Import-Csv -Path CsvLocation.csv | Add-AccessControlEntry -WhatIf
Add-AccessControlEntry prompts for confirmation by default. Use the -Force switch to suppress the prompts.
Changing this to work for the NTFS permissions is very easy, too. Just change the Get-WmiObject call into a Get-ChildItem call, and everything else should be the same.

Powershell Script to move multiple unknown files into correct locations

I am attempting to create a script for use when we perform manual data transfers at work, this can be tedious to perform when users have a ton of random data in random locations. I want to move those items from the old location on the old drive to our network location and then pull it back down. What I have below is a beta version of what I am looking to do, my issue is that I am unable to figure out why I am unable to find the current logged in user and exclude certain accounts.
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = 'C:\TextFiles'
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
$Include=#("*.*")
$Path=#("C:\Users\%USERNAME%\Documents","C:\Users\%USERNAME%\Pictures")
Get-ChildItem -Path $Path -Include $Include -Recurse | Move-Item -Destination C:\TextFiles
Mind you more will be added to this but I am unsure how to get the current user and have it exclude our administrator account on the units.
Thank you for any help.
You can use the environment variable named USERDOMAIN and USERNAME to determine the currently logged on user.
if ($env:UserName -eq 'Trevor.Sullivan') {
# Do something
}
To take it one step further, you could build an array of the user accounts that you want to exclude, and then check to see if the currently logged on user account is contained in that array. Here is an example:
# Build the list of excluded users
$ExcludedUserList = #(
'User1'
, 'User2'
, 'User3'
, 'User4'
);
# Check if user is contained in exclusion list
if ('User5' -notin $ExcludedUserList) {
# Do something here
}

Getting name of folder which has specific ACL

I've recently had the task of updating the permissions structures on our user home drives. I have a directory called home and a folder per user below home. There are two groups at the Home level, and these are forced down to each of the user folders. The user folders are set to inherit from their parent, and then the user is set to access only their folder.
I'm trying to write a powershell script which will show me if any folders have a specific ACL left behind. This is what I ended up with, and it just seems to return the sub-folder list for the specified directory where as I want only the folders which have the specified ACL.
$path = "\\server\share"
$folders = Get-ChildItem $path | where {$_.psiscontainer}
foreach ($folder in $folders)
{
$domain = "domname"
$aclname = "ACLname"
$aclfullname ="$domain\$aclname"
Get-Acl | select -ExpandProperty Access | where {$_.identityreference -contains $aclfullname}
Write-Host $folder.FullName
}
If I use the following, it returns only one result, but it returns the ACL and not the folder name.
$path = "\\node1\home"
$domain = "morgan-cole"
$aclname = "gsherlock"
$aclfullname ="$domain\$aclname"
Get-ChildItem $path | where {$_.psiscontainer} | Get-Acl | select -ExpandProperty Access | where {$_.identityreference -contains $aclfullname}
Any ideas? Hopefully my requirements make sense.
This will do the trick:
Get-ChildItem $path | where {$_.psiscontainer} | where { $_ | Get-Acl | select -ExpandProperty Access | where {$_.IdentityReference -contains $aclfullname}}
Some explanation:
The reason why yours was not working the way you wanted in the second example is that it starts off as a folder in the pipeline, but is then transformed to an ACL that matches what you are looking for. However, it is now transformed into an ACL and you wanted to folder - not the actual ACL.
So, the "trick" is to keep the folder in the pipeline but filter the folder based on the ACL. This is achieved by nesting another pipeline inside the second where-object clause.
PS. There is probably a way to combine the first part that looks for psicontainer into the second where clause but let's leave that for another day.