powershell list permissions for user + folder - windows

recently working with powershell.
Wonder if anybody knows some way to show allowed folders by user.
i get until this
Get-ADPrincipalGroupMembership username | select name
but i just get the groups, nothing for folder and if the user its assigned to a one folder without a group, it cannot be seen.
Im searching be able to find quickly all the permissions on a file server for one user.
Sorry for my english.
thank you.

You will have to loop through all the folders and files and check if their permissions includes the username you're looking for.
Like so:
$items = Get-Childitem C:\Temp
This gives you an object of files and folders, which you can then pass to the GetAccessControl method
The object looks like this:
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 24-05-2017 10:06 test
-a---- 23-05-2017 14:55 97 test.csv
Now, you can use your $items object with the GetAccessControl method, like so:
$items.GetAccessControl() | select -ExpandProperty Access
Again, this will return an object, containing the NTFS file permissions of each folder in the path you specified.
Which will look like this:
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : Domain\User
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : None
Try and play around with this information, and see if you can get started on a working example, for the community to help debug :)
Please keep your replies in the original post. Sucks we cannot just comment...
But still, yeah, what you see there, is all users/groups mentioned in the current file(in the pipeline)'s NTFS Access Control List.
Keep in mind that you can access the objects individual lines, to make your search easier.
Like so:
$Test[0].IdentityReference
Would yield "domain/user" for the first entry in the $Test array.
So you would loop through all entries using a foreach-object, or a
foreach($item in $test){
#Code here
# if($item.IdentityReference -eq $UserImLookingfor){Write-host "Match! -fo green" }
$i++
}

Related

Trying to write a powershell script that shows all locked files with computer names instead of IP address

The task given was to create a way for our staff to see who has the file open that they want to use, as Windows says it is either locked and doesn't name the person who has it locked, or it displays the person who made the file but not the person who currently has it open.
I can look it up in Computer Management on the fileserver, but were are hoping to speed up this for the end users.
I've written this powershell script on our fileserver and it works perfectly, I have this running every 5 minutes in Task Scheduler with administrative permissions:
get-smbopenfile -ClientUserName * |select clientcomputername,clientusername,path | Out-File -Encoding utf8 "S:\LockedFiles.txt" -width 300
The output looks like this:
clientcomputername clientusername path
------------------ -------------- ----
IPADDRESS DOMAIN\USERNAME S:\FOLDER\FILE.FILEEXTENSION
What I really want to do now is get the computer name rather than the IP address, just in case staff are logged into multiple machines at the same time.
I wondered if ClusterNodeName or PSComputerName would provide this, but the returned data is always blank.
I thought about this and below is one option (the first line is pseudocode), but as I see it that would mean recursively altering the piped data or reading in piped data, which I'm not even sure how to do.
$ipaddress = IPADDRESS
$Workstation = [System.Net.Dns]::GetHostByName($ipaddress)
Write-Host $Workstation.HostName
Anyone have any ideas on how I can do this? Is there a better way?
I assume you're looking to add a new property to your output object that has the resolved DNS Name from the IP Address found in the ClientComputerName property. For this you use Resolve-DnsName to attempt the name resolution and a Try Catch in case it fails to capture the exception message. For the export I would recommend you to use Export-Csv.
Get-SmbOpenFile -ClientUserName * | ForEach-Object {
$dnsName = try {
(Resolve-DnsName $_.ClientComputerName -ErrorAction Stop).NameHost
}
catch {
[ComponentModel.Win32Exception]::new($_.Exception.NativeErrorCode).Message
}
[pscustomobject]#{
ClientIpAddress = $_.ClientComputerName
ResolvedHostName = $dnsName
ClientUserName = $_.ClientUserName
Path = $_.Path
}
} | Export-Csv "S:\LockedFiles.csv" -Encoding utf8 -NoTypeInformation

Powershell - Checking # of files in a folder across a domain

So I'm trying to count the number of font files (that have different extensions) inside the local font folder of every computer in my domain at work to verify which computers have an up to date font installation using powershell.
So far I have
Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;
as a means of counting the files, I'm just at a loss on how exactly to replicate this and get a output that indicates the file count for the path for every computer on my domain (the file path is all the same for each)
How should I best proceed?
You will have to run the command against every computer. Assuming you have some sort of domain admin privelege and can access admin shares on all computers, you can use the c$ share.
The code below takes a list of computers in a single column CSV with no headers and runs the command against the admin share on each
$computers = Import-Csv -Path C:\computers.csv -Header Computer;
foreach($c in $computers)
{
Write-Host (Get-ChildItem "\\$($c.Computer)\c$\MyFolder" | Measure-Object).Count;
};

Trying to back up my Bitlocker Key to ADDS Through Script

I'm trying to automatize the process of storing BitLocker Keys to ADDS.
I wanna be able to run the following script at logon, in order to do that, as the OS is deployed through WDS which already encrypts the drive:
$BitVolume = Get-BitLockerVolume -MountPoint $env:SystemDrive
$RecoveryKey = $BitVolume.KeyProtector | Where-Object { $_.KeyProtectorType -eq 'RecoveryPassword' }
Backup-BitLockerKeyProtector -MountPoint $env:SystemDrive -KeyProtectorId $RecoveryKey.KeyProtectorID
BackupToAAD-BitLockerKeyProtector -MountPoint $env:SystemDrive -KeyProtectorId $RecoveryKey.KeyProtectorID
I always get access denied as this has to run as admin...
Is there any command I can use prior the code to run it as admin?
I've googled but I found no useful info to actually do this...
As for the access denied part... as was already sated, you need to start your PowerShell session as an admin. However, as a point of note about your code, you are only targeting the system/os volume... which may not be the only volume that's encrypted. If you want to programmatically backup all of the encrypted volumes, may I suggest one of the two following options...
One-liner:
Get-BitLockerVolume | where {$_.VolumeStatus -like "FullyEncrypted"} | foreach {foreach($Key in $_.KeyProtector){if($Key -like "RecoveryPassword"){Backup-BitLockerKeyProtector -MountPoint $_.mountpoint -KeyProtectorId $key.KeyProtectorId}}}
Or, if you prefer something a little bit easier to read...
Script Block:
foreach ($BLV in Get-BitLockerVolume){
if ($BLV.VolumeStatus -like "FullyEncrypted"){
foreach ($Key in $BLV.KeyProtector) {
if ($Key -like "RecoveryPassword") {
Backup-BitLockerKeyProtector -MountPoint $BLV.MountPoint -KeyProtectorId $Key.KeyProtectorId
}#if
}#foreach
}#if
}#foreach
Neither is super eloquent... but, with this method it will grab all of the encrypted volumes on the system and add them to AD. You would need to modify the code slightly to add the AAD backup option you cited of course.
P.S. I'm only responding because I recently had to solve this problem of multi-volume backups as a one-liner solution and figured I would share it since your post was a top search result when I looked for a pre-canned solution. Cheers! :)

How can I use Powershell to open a file with spaces in it in an auxiliary application, using a function?

Function npp {
Param([String]$filepath)
start 'D:\Program Files (x86)\Notepad++\notepad++.exe' &($filepath)
}
Function nteract {
$file = $args[0]
start 'D:\Program Files\nteract\nteract.exe' &($file)
}
I wrote two beginner functions for the purpose of recreating the much easier aliases in bash and fish. I have tried two ways of capturing a file argument as shown above. Neither of them work. Instead I receive the following.
Say I am opening the file '.\01 Getting started.ipynb' in nteract.
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
7 Job7 BackgroundJob Running True localhost Microsoft.PowerShell.Man…
.\01. Getting started.ipynb
This displays in my console, and opens a default instance of nteract with an empty notebook. The same happens with Notepad++ with other files.
Insert a complaint here about how confusing it is to get this functionality working compared to Linux shells. What am I doing wrong?
-==-
EDIT: This question has been answered sufficiently, but I did notice strange behavior the first time I commented out the functions I wrote in my profile.
PS D:\julitory\JuliaBoxTutorials\introductory-tutorials\intro-to-julia> . $profile
PS D:\julitory\JuliaBoxTutorials\introductory-tutorials\intro-to-julia> nteract '.\02. Strings.ipynb'
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
5 Job5 BackgroundJob Running True localhost
.\02. Strings.ipynb
For some reason, this occured the first time I commented them out. So I uncommented them, and it began to work again... then, the next time I commented them, they continued to work. I think I'm just too tired for this, but thanks all.
PowerShell has Set-Alias for that purpose. Define, for example:
Set-Alias -Name nteract -Value "D:\Program Files\nteract\nteract.exe"
Then use the alias as:
nteract ".\01 Getting started.ipynb"
Aliases defined this way are only available during the current PowerShell session. For ways to make them persist see How to create permanent PowerShell Aliases
.

Searching For A Registry Value Then Change It

On all the Windows 10 computers I re-image, I want to disable the option in Sound for giving exclusive control to each device to applications. I have located the registry keys and values:
HKLM\Software\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture\RANDOM_STRING\Properties
HKLM\Software\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\RANDOM_STRING\Properties
Within each of these keys (1st one is for Mics and 2nd is for Speakers) their are the two DWORD-32 values in each:
{b3f8fa53-0004-438e-9003-51a46e139bfc},3
{b3f8fa53-0004-438e-9003-51a46e139bfc},4
I want to basically make a batch script that will find these two values and set them to 0 for each audio devices. I'll have it run via Task Scheduler or something to make sure it gets new devices too.
The problem for me is that RANDOM_STRING portion of each path. Each one is ~25 random characters; it looks similar to the value names with the ,# at the end. I know how to change a value via a specific path, but here their is that randomized key name, and then new ones as new devices are plugged in.
Is their any way for me to create a batch file (or VBS/PowerShell) that will search the registry (or just Audio to narrow it down quicker) for those two values, and change their values to 0? Or if any other ways of going about this if so?
An example of the process I'd like (or again, something else similar):
Search for the DWORD-32 value "{b3f8fa53-0004-438e-9003-51a46e139bfc},3" within
the path
"HKLM\Software\Microsoft\Windows\CurrentVersion\MMDevices\Audio\"
and all the sub-keys within.
Set the value of the DWORD-32 value
"{b3f8fa53-0004-438e-9003-51a46e139bfc},3" to 0.
Search for the DWORD-32 value "{b3f8fa53-0004-438e-9003-51a46e139bfc},4" within
the path
"HKLM\Software\Microsoft\Windows\CurrentVersion\MMDevices\Audio\"
and all the sub-keys within.
Set the value of the DWORD-32 value
"{b3f8fa53-0004-438e-9003-51a46e139bfc},4" to 0.
I hope you know what are you doing. Manipulating registry is very risky. If you are absolutely sure, take a look at this script:
ls 'HKLM:\Software\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture\*\Properties\' | `
where {$_.Property -contains '{b3f8fa53-0004-438e-9003-51a46e139bfc},3'} | `
Get-ItemProperty -Name '{b3f8fa53-0004-438e-9003-51a46e139bfc},3'
#Set-ItemProperty -Name '{b3f8fa53-0004-438e-9003-51a46e139bfc},3' -Value 0
Make sure this script (with Get-ItemProperty) gets only desired keys. To change values, replace last line with commented one. Make sure you have proper permissions. And finally: do it at you own risk :)
I was unable to get the other answer working. I am trying to ban the Netflix app from being unbearably loud (which it does if it gets exclusive control of the sound device) every time I reinstall the geforce drivers (when the exclusive control resets).
So:
Get-ChildItem -recurse -path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\'| `
Foreach-Object { if ($_.Property -eq '{b3f8fa53-0004-438e-9003-51a46e139bfc},3') {$_|Get-ItemProperty -Name '{b3f8fa53-0004-438e-9003-51a46e139bfc},3'} }`
Gives me this output:
{b3f8fa53-0004-438e-9003-51a46e139bfc},3 : 0
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\
Windows\CurrentVersion\MMDevices\Audio\Render\{94743724-8af1-4abc-8d45-275
7184ec5f2}\Properties
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\
Windows\CurrentVersion\MMDevices\Audio\Render\{94743724-8af1-4abc-8d45-275
7184ec5f2}
PSChildName : Properties
PSProvider : Microsoft.PowerShell.Core\Registry
{b3f8fa53-0004-438e-9003-51a46e139bfc},3 : 0
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\
Windows\CurrentVersion\MMDevices\Audio\Render\{b4ed07ae-0ee7-4ffb-8370-8bb
08a59a941}\Properties
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\
Windows\CurrentVersion\MMDevices\Audio\Render\{b4ed07ae-0ee7-4ffb-8370-8bb
08a59a941}
PSChildName : Properties
PSProvider : Microsoft.PowerShell.Core\Registry
This looks good.
To write it the Get-ItemProperty needs to change to Set-ItemProperty but it results in a security error, please consult https://stackoverflow.com/a/35844259/308851 to take ownership of the relevant key.

Resources