Problem with the setting IsInherited in my powershell script - windows

I have to make a script who change users domain of my shared folder and add them in addition to the existing users rights.
1st :
I do a script in PowerShell to get all NTFS rights of my directories (It worked perfectly) :
$FolderPath = Get-ChildItem -Directory -LiteralPath "C:\MYPATH" -Recurse -Force
$Report = #()
Foreach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
foreach ($Access in $acl.Access)
{
$Properties = [ordered]#{'FolderName'=$Folder.FullName;'Users'=$Access.IdentityReference;'Rights'=$Access.FileSystemRights;'Inherit'=$Access.IsInherited;}
$Report += New-Object -TypeName PSObject -Property $Properties
}
}
$Report | Export-Csv -Encoding UTF8 -LiteralPath "E:\MYPATH\FolderPermissions2.csv"
2nd : I modify my CSV to find and replace with my new domain.
There is a part of my CSV :
"E:\test migration\MYPATH\MYPATH à la tireuse plans","BUILTIN\Users","AppendData","True"
"E:\test migration\MYPATH\MYPATH","BUILTIN\Users","CreateFiles","True"
"E:\test migration\MYPATH","OLD_DOMAIN\user_name","FullControl","True"
"E:\test migration\MYPATH","OLD_DOMAIN\user_name","ReadAndExecute, Synchronize","True"
"E:\test migration\MYPATH","BUILTIN\Administrators","FullControl","True"
"E:\test migration\MYPATH","NT AUTHORITY\SYSTEM","FullControl","True"
"E:\test migration\MYPATH","OLD_DOMAIN\a_nbe","FullControl","True"
3rd : And I do another script to re-import all rights from my modified CSV and Set them to the same folder :
Import-Module NTFSSecurity
Import-Module ActiveDirectory
$CSV = Import-Csv -Delimiter "," -LiteralPath "E:\MYPATH\FolderPermissions2.csv"
$CSV | ForEach-Object {
$FolderName = $_.FolderName
$Users = $_.Users
$Rights = $_.Rights
$Inherit = $_.Inherit
Add-NTFSAccess -Path $FolderName -IdentityReference $Users -FileSystemRights $Rights
$acl = Get-Acl $FolderName
if ($Inherit = "True", $acl.SetAccessRuleProtection($false,$True)) {
} else {
$acl.SetAccessRuleProtection($false,$False)
}
}
The first part of this script worked perfectly, all of my folder get the "new users" with my new domain with exactly the same rights.
BUT the part where I define my "IsInherited" don't work, I get the path and not my boolean...
screenshot of the error
Anybody has an idea where I do a mistake, please ?
Thank you !

Related

Function to copy file on a remote service

I have written the below function to copy file on a remote server
Function deploy-file{
PARAM(
[Parameter(Mandatory=$true,Position=0)][STRING]$cred,
[Parameter(Mandatory=$true,Position=1)][STRING]$server,
[Parameter(Mandatory=$true,Position=2)][STRING]$destdir,
[Parameter(Mandatory=$true,Position=3)][STRING]$file
)
$parameters = #{
Name = $server
PSProvider = "FileSystem"
Root = $destdir
Credential = $cred
}
new-psdrive #parameters
$d=$server + ":\"
copy-item $file $d -force
remove-psdrive $server -ErrorAction SilentlyContinue
}
Now, I am calling the above function from the main file as below:
$sn=abc.com
$server=($sn -split "\.")[0]
$destdir = 'e:\folder'
$file = 'file.zip'
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $usr, $pa
deploy-file $cred $server $destdir $file
There is no issue with credentials.
My script keeps running and not even throwing any error. What is wrong with the script?
Copying a file to a remote host using a PSSession would be as follows:
function Deploy-File {
[cmdletbinding()]
param(
[Parameter(Mandatory, Position=0)]
[securestring] $cred,
[Parameter(Mandatory, Position=1)]
[string] $server,
[Parameter(Mandatory, Position=2)]
[string] $destdir,
[Parameter(Mandatory, Position=3)]
[string] $file
)
try {
[IO.FileInfo] $file = Get-Item $file
$session = New-PSSession -ComputerName $server -Credential $cred
Copy-Item -Path $file -Destination $destdir -ToSession $session
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
finally {
if($session) {
Remove-PSSession $session
}
}
}
By looking at your code is hard to tell what could be failing aside from what we know for sure is incorrect, the parameter $cred is being constrained to [string] when it actually should be [securestring]. By doing so you're rendering your PS Credential object unusable.

How to get the share folder level permission using powershell

#Cred= Get-Credential
$FolderPath = dir -Directory -Path "\\abc\dc\da" -Recurse -Force | where {$_.psiscontainer -eq $true}
$Report = #()
Foreach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
# $Name= Get-ChildItem $Folder -Recurse | where {!$_.PSIsContainer} |select-object fullname
foreach ($Access in $acl.Access)
{
$Properties = [ordered]#{'FolderName'=$Folder.FullName;'AD
Group or User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
$Report += New-Object -TypeName PSObject -Property $Properties
}
}
$Report | Export-Csv -path "C:\Output\Test_16-06-2021.csv"
In the above script, I'm able to get all my folder structure with permission but I want to do with a custom parameter like if I want to only folder level 3 it should get me the output as below
\\abc\a\b\c
\\abc\a\c\d
not like
\\abc\a\b\c\d\text.txt
\\abc\a\c\d\e\f\g\demo.pdf
If you're using PowerShell 5.0, you can use the -Recurse and -Depth parameters combined:
[string]$rootFolder = Read-Host -Prompt "Enter root folder path (no trailing '\')"
[int]$recursionDepth = Read-Host -Prompt "Enter recursion depth"
[string]$outputCsv = Read-Host -Prompt "Enter output .csv file (full path)"
$folders = Get-ChildItem -Directory -Path $rootFolder -Recurse -Depth $recursionDepth -Force | Where-Object { $_.PSIsContainer -eq $true }
[array]$report = #()
foreach ($folder in $folders) {
$acl = Get-Acl -Path $folder.FullName
foreach ($access in $acl.access) {
[hashtable]$properties = [ordered]#{
'FolderName' = $folder.FullName;
'AD Group or User' = $access.IdentityReference;
'Permissions' = $access.FileSystemRights;
'Inherited' = $access.IsInherited
}
$report += New-Object -TypeName PSObject -Property $properties
}
}
Write-Host $report
$report | Export-Csv -Path $outputCsv
If that isn't an option, you can try the following:
[string]$rootFolder = Read-Host -Prompt "Enter root folder path (no trailing '\')"
[int]$recursionDepth = Read-Host -Prompt "Enter recursion depth"
[string]$outputCsv = Read-Host -Prompt "Enter output .csv file (full path)"
[string]$recursionStr = if ($recursionDepth -eq 0) { "\*" } else { ("\*" * ($recursionDepth + 1)) }
$folders = Get-ChildItem -Directory -Path "$rootFolder$recursionStr" -Force | Where-Object { $_.PSIsContainer -eq $true }
[array]$report = #()
foreach ($folder in $folders) {
$acl = Get-Acl -Path $folder.FullName
foreach ($access in $acl.access) {
[hashtable]$properties = [ordered]#{
'FolderName' = $folder.FullName;
'AD Group or User' = $access.IdentityReference;
'Permissions' = $access.FileSystemRights;
'Inherited' = $access.IsInherited
}
$report += New-Object -TypeName PSObject -Property $properties
}
}
Write-Host $report
$report | Export-Csv -Path $outputCsv
See Limit Get-ChildItem recursion depth

add columns to existing file

i imported from file IDs and base on this ID i am trying to get information from AD...and insert this information as columns in original file...this is the code:
$import = Import-Csv C:\Temp\coputerstatus.csv
Foreach ($item in $import) {
$user = Get-ADUSer -Identity $item.ID
#$item = New-Object psobject
$item | Add-Member -MemberType NoteProperty -Name "office" -Value $user.office
$item | Add-Member -MemberType NoteProperty -Name "title" -Value $user.title
$item | Add-Member -MemberType NoteProperty -Name "displayname" -Value $user.name
} #foreach
$import | Export-Csv C:\temp\my.csv
but it is no working very well..i success to insert the headers but the value is empty(,,,)
i would like to same help
thanks
Get-ADUser and other active directory cmdlets operate a little funny. When you ask for an ADUser object Get-ADuser only returns a small subset of the properties available. Office and title are not available in this default set. To get what you want add the -Property parameter to Get-ADUser and ask for title and office in addition to the defaults it normally returns
$user = Get-ADUSer -Identity $item.ID -Property Title, Office
if you want to retrieve all possible properties use an asterisk
$user = Get-ADUSer -Identity $item.ID -Property *
It actually sounds like you may not be getting any user object back from Get-ADUser. Have a look at what is in the ID column in your csv files. Manually check what you are getting back from the import-csv command
$import = Import-Csv C:\Temp\coputerstatus.csv
$import | gm
Make sure that you have an ID property in that list. If so go ahead and check if your objects have ID values that you expect
$import.ID
If everything looks fine there try taking one of those IDs and manually running the Get-ADuser command replacing $item.ID with one of the actual IDs.
Get-ADUSer -Identity TESTID -Property Title, Office
Do you get anything back?
Two ways...you can use splatting to dump all of the properties into the CSV for each like this...
$import = Import-Csv C:\Temp\coputerstatus.csv
$myUsers = #()
Foreach ($item in $import) {
$user = Get-ADUSer -Identity $item.ID -Properties *
[pscustomobject]$MyItem = #{
"userProps" = $user
}
$myUsers += $MyItem.Values
} #foreach
$myUsers | Export-Csv 'C:\temp\my.csv' -NoTypeInformation
Or you can select specific properties that you care about, like this...
$import = Import-Csv C:\Temp\coputerstatus.csv
$myUsers = #()
Foreach ($item in $import) {
$user = Get-ADUSer -Identity $item.ID -Properties *
[pscustomobject]$MyItem = #{
"DisplayName" = $user.Name
"Office" = $user.office
"Title" = $user.title
}
$myUsers += $MyItem.Values
} #foreach
$myUsers | Export-Csv 'C:\temp\my.csv' -NoTypeInformation

get-acl in network drive group/user name instead SID

I need to collect the security permission for each folders in a share, the result returns me the SID but i need the username (or the group name), how i can do this?
$FolderPath = Get-ChildItem -Directory -Path "Y:\" -Recurse -Force
$Output = #()
ForEach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
ForEach ($Access in $Acl.Access) {
$Properties = [ordered]#{'Folder Name'=$Folder.FullName;'Group/User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
$Output += New-Object -TypeName PSObject -Property $Properties
}
}
$Output | Out-GridView
The Access property already maps to a code path that attempts to resolve the account identity from the SID, so if you're seeing SID strings instead of names, it might be an indication that the SID cannot be resolved by the machine.
You can still make an attempt to translate the individual SID value into an [NTAccount] object like this:
$Principal = try {
$Access.IdentityReference.Translate([System.Security.Principal.NTAccount])
}
catch {
# If the translation fails we fall back to SID
$Access.IdentityReference
}
Then use $Principal in place of $Access.IdentityReference in the property dictionary.

Get LastWriteTime of a particular file

I'm using Windows 10 Enterprise 1709 and PowerShell ISE v5. I am trying to get the last write time to the file deployment.properties by checking to see if the testpath holds the file and if it does, write the LastWriteTime of that file. I'm not sure I'm doing this the correct way. Any help showing me how to make this work would be appreciated. I've tried several options but this is the only one that doesn't produce an error. However, the code runs, completes without error but doesn't produce and output. My code is listed below first and then the output I see on the PowerShell ISE screen.
Set-ExecutionPolicy Bypass
$env:COMPUTERNAME = HostName
$DeplPath = "AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
$dateTime = foreach ($User in Get-ChildItem C:\Users -Directory) {
$folderFile = Join-Path $javauser.FullName $DeplPath
if (Test-Path $folderFile) {
$testResult = Get-ChildItem | select -Property fullName, LastWriteTime
} Else {
$testResult = "Not found - deployment.properties"
}
}
$dateTime
Below is the output I get which returns no information.
PS C:\WINDOWS\system32> Set-ExecutionPolicy Bypass
$env:COMPUTERNAME = HostName
$DeplPath = "AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
$dateTime = foreach ($User in Get-ChildItem C:\Users -Directory) {
$filelist = Join-Path $User.FullName $file
if (Test-Path $filelist) {
$testResult = Get-ChildItem $dateTime | select -Property fullName, LastWriteTime
} Else {
$testResult = "Not found - deployment.properties"
}
}
$dateTime
PS C:\WINDOWS\system32>
Newly modified code below
Set-ExecutionPolicy Bypass
$env:COMPUTERNAME = HostName
$DeplPath = "AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
$dateTime = foreach ($User in Get-ChildItem C:\Users -Directory) {
$folderFile = Join-Path $User.FullName $DeplPath
if (Test-Path $folderFile) {
$testResult = Get-ChildItem | select -Property fullName, $DeplPath.LastWriteTime
} Else {
$testResult = "Not found - deployment.properties"
}
[PSCustomObject]#{
"Computer Name" = $env:COMPUTERNAME
"Java User True/False" = $TestResult
"Users" = $user.Name
"Last Write Time" = $testResult.LastWriteTime
}
}
$dateTime
Try this out. Your property select for the get-childitem were mislabeled.
Set-ExecutionPolicy Bypass
$env:COMPUTERNAME = HostName
$DeplPath = "AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
$dateTime = foreach ($User in Get-ChildItem C:\Users -Directory) {
$folderFile = Join-Path $User.FullName $DeplPath
$test = Test-Path $folderFile
if ($test -eq $True) {
$testResult = Get-ChildItem $folderfile | select -Property Name, LastWriteTime
} Else {
$testResult = "Not found - deployment.properties"
}
[PSCustomObject]#{
"Computer Name" = $env:COMPUTERNAME
"Java User True/False" = $TestResult
"Users" = $user.Name
"Last Write Time" = $testResult.LastWriteTime
}
}
$dateTime

Resources