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.
Related
Good morning,
Hopefully this will be a quick and easy one to answer.
I am trying to run a PS script and have it export to csv based on a list of IP addresses from a text file. At the moment, it will run but only produce one csv.
Code Revision 1
$computers = get-content "pathway.txt"
$source = "\\$computer\c$"
foreach ($computer in $computers) {
Get-ChildItem -Path "\\$Source\c$" -Recurse -Force -ErrorAction SilentlyContinue |
Select-Object Name,Extension,FullName,CreationTime,LastAccessTime,LastWriteTime,Length |
Export-CSV -Path "C:\path\$computer.csv" -NoTypeInformation
}
Edit
The script is now creating the individual server files as needed and I did change the source .txt file to list the servers by HostName rather than IP. The issue now is that no data is populating in the .csv files. It will create them but nothing populates. I have tried different source file paths to see if maybe its due to folder permissions or just empty but nothing seems to populate in the files.
The $computer file lists a number of server IP addresses so the script should run against each IP and then write out to a separate csv file with the results, naming the csv file the individual IP address accordingly.
Does anyone see any errors in the script that I provided, that would prevent it from writing out to a separate csv with each run? I feel like it has something to do with the foreach loop but I cannot seem to isolate where I am going wrong.
Also, I cannot use any third-party software as this is a closed network with very strict FW rules so I am left with powershell (which is okay). And yes this will be a very long run for each of the servers but I am okay with that.
Edit
I did forget to mention that when I run the script, I get an error indicating that the export-csv path is too long which doesn't make any sense unless it is trying to write all of the IP addresses to a single name.
"Export-CSV : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
At line:14 char:1
TIA
Running the script against C: Drive of each computer is strongly not advisable that too with Recurse option. But for your understanding, this is how you should pass the values to the variables. I haven't tested this code.
$computer = get-content "pathway.txt"
foreach ($Source in $computer) {
Get-ChildItem -Path "\\$Source\c$" -Recurse -Force -ErrorAction SilentlyContinue |
Select-Object Name,Extension,FullName,CreationTime,LastAccessTime,LastWriteTime,Length | Export-Csv -Path "C:\Path\$source.csv" -NoTypeInformation
}
$computer will hold the whole content and foreach will loop the content and $source will get one IP at a time. I also suggest instead of IP's you can have hostname so that your output file have servername.csv for each server.
In hopes that this helps someone else. I have finally got the script to run and create the individual .csv files for each server hostname.
$servers = Get-Content "path"
Foreach ($server in $servers)
{
Get-ChildItem -Path "\\$server\c$" -Recurse -Force -ErrorAction SilentlyContinue |
Select-Object Name,Extension,FullName,CreationTime,LastAccessTime,LastWriteTime,Length |
Export-CSV -Path "path\$server.csv" -NoTypeInformation
}
I have a script that I feel that I am close to being ready to run but need some help fine tuning things.
My primary objective is this:
From each text file (named after the computer it was generated from), run each script using the data that exists within the .txt file. Each file is output from the C:\Users folder on the computer, listing each user profile that exists on that machine. I need to be able to run the script so that it deletes the specified folders/files for each user profile on that machine.
# Name: CacheCleanup
# Description: Deletes cache files per user on each computer
# Syntax: .\CacheCleanup.ps1
# Author: Nicholas Nedrow
# Created: 06/15/2021
#Text file contains list of all machines that have recently pinged and are online
$Computers = Get-Content "C:\Temp\CacheCleanUp\ComputerUp.txt"
#Users are listed in individual text files assigned with the name of their PC.
$Users = Get-Content "C:\Temp\CacheCleanUp\Computer Users\*.txt"
#Base path for deletion paths
$Path = "\\$PC\c$\users\$user\appdata\local"
#Delete User\Temp files
Remote-Item -Path "$Path\temp\*" -Recurse -Force -EA SilentlyContinue -Verbose
#Delete Teams files
Remove-Item -Path "$Path\Microsoft\Teams" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-ITem -Path "$Path\Microosft\TeamsMeetingAddin" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -Path "$Path\Microsoft\TeamsPresenceAddin" -Recurse -Force -EA SilentlyContinue -Verbose
#Delete Chrome Cache
Remove-Item -Path "$Path\Google\Chrome\User Data\Default\Cache\*" -Recurse -Force -EA SilentlyContinue -Verbose
#Delete IE Cache
Remove-Item -Path "$Path\Microsoft\Windows\INetCache\*" -Recurse -Force -EA SilentlyContinue -Verbose
#Delete Firefox cache
Remove-Item -Path "$Path\Mozilla\Firefox\Profiles\*.default\cache\*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -Path "$Path\Mozilla\Firefox\Profiles\*.default\cache\*.*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -Path "$Path\Mozilla\Firefox\Profiles\*.default\cache\cache2\entries\*.*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -Path "$Path\Mozilla\Firefox\Profiles\*.default\cache\thumbnails\*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -Path "$Path\Mozilla\Firefox\Profiles\*.default\cache\cookies.sqlite" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -Path "$Path\Mozilla\Firefox\Profiles\*.default\cache\webappstore.sqlite" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -Path "$Path\Mozilla\Firefox\Profiles\*.default\cache\chromeapstore.sqlite" -Recurse -Force -EA SilentlyContinue -Verbose
#How to Run each script for each user on each machine
#How to generate detailed log with results of deletion for each section
I will state right away that I am still learning scripting and am unfamiliar with functions, even though I am pretty sure that is what I need to develop here. This is a domain network so the appropriate path for the computer name has been taken into consideration. Each script does run independently, with the computer name specified but I run into issues when it comes to trying to call out each user profile on that computer.
If possible, it would be nice to have some sort of generated report with the outcome of each user profile and what was ran successfully. I don't need to necessarily know every file that was deleted but maybe a list of those files that were unable to be deleted due to conflicts with running programs or permission issues.
You need to use loops. Consider the following code:
$configFiles = "C:\Temp\CacheCleanUp";
Get-Content "$configFiles\TESTComputers.txt" | % {
$PC = $_;
Write-Host "Attempting to clean cache on computer: $PC";
Get-Content "$configFiles\TESTusers.txt" | % {
$user = $_;
$Path = "\\$PC\c$\users\$user\appdata\local"
Write-Host "`tCleaning $Path"
<# Your code goes here #>
}
}
TESTusers.txt contains:
dave
bob
amy
TESTComputers.txt contains:
10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4
10.0.0.5
This is the output of the above code and computer/user files:
Attempting to clean cache on computer: 10.0.0.1
Cleaning \\10.0.0.1\c$\users\dave\appdata\local
Cleaning \\10.0.0.1\c$\users\bob\appdata\local
Cleaning \\10.0.0.1\c$\users\amy\appdata\local
Attempting to clean cache on computer: 10.0.0.2
Cleaning \\10.0.0.2\c$\users\dave\appdata\local
Cleaning \\10.0.0.2\c$\users\bob\appdata\local
Cleaning \\10.0.0.2\c$\users\amy\appdata\local
Attempting to clean cache on computer: 10.0.0.3
Cleaning \\10.0.0.3\c$\users\dave\appdata\local
Cleaning \\10.0.0.3\c$\users\bob\appdata\local
Cleaning \\10.0.0.3\c$\users\amy\appdata\local
Attempting to clean cache on computer: 10.0.0.4
Cleaning \\10.0.0.4\c$\users\dave\appdata\local
Cleaning \\10.0.0.4\c$\users\bob\appdata\local
Cleaning \\10.0.0.4\c$\users\amy\appdata\local
Attempting to clean cache on computer: 10.0.0.5
Cleaning \\10.0.0.5\c$\users\dave\appdata\local
Cleaning \\10.0.0.5\c$\users\bob\appdata\local
Cleaning \\10.0.0.5\c$\users\amy\appdata\local
Few things to note about the code:
Get-Content "filename" | % - this is going to loop through the contents of the file one line at a time. % is a shortcut for ForEach-Object.
$_ when inside a foreach loop is an automatic variable created by PowerShell that contains the current item in the loop.
If you have a loop inside a loop and you need to access both $_ values from the inner and outer loop, you can create a new variable (eg $PC = $_;) in the outer loop that can be used within the inner loop (eg $Path = "\\$PC\c$\users\$user\appdata\local").
You should definitely learn to use functions, and then in the future you can combine functions into modules. This is a big help in organising your code, and you can avoid duplication by sharing functions between different scripts - but your current script doesnt need functions (but theyre a good idea).
Depending on your network, you might be able to use PowerShell remoting instead of the Administrative shares to achieve the same effect. This is a more advanced topic, there is some configuration required on the machines you want to connect but the advantage is your computer sends the script to each target, and the target computer runs the script and reports its results.
Another possible change i would suggest is only using a list of computers - then on each computer use get-childitem -path c:\users to actually get the list of each profile currently on that target computer.
I currently have this script working but only able to get it to run locally, I would like to have it read a text file that would be stored on c:\List_of_PCs.txt that would have computer names that it would also run the same script on. That way I can update the text file instead of modify the code.
Set-ExecutionPolicy RemoteSigned
# Get all users
$users = Get-ChildItem -Path "C:\Users"
# Loop through users and delete the Teams file
$users | ForEach-Object {
Remove-Item -Path "C:\Users\$($_.Name)\AppData\Roaming\Microsoft\Teams\Cache\f*" -Force
Remove-Item -Path "C:\Users\$($_.Name)\AppData\Roaming\Microsoft\Teams\Application Cache\Cache\f*" -Force
}
Any help on this I've tried multiple things every which way, I'm sure this is something simple but I'm still very new to PowerShell.
Try something like this...
Requires PowerShell remoting to be enabled and using an account that is an admin on the remote computer
$ComputerList = Import-Csv -Path 'c:\List_of_PCs.txt'
$ComputerList | % {
Invoke-Command -ComputerName $_ -ScriptBlock {
# Set-ExecutionPolicy RemoteSigned # this is something that should be set via GPO for all systems, not your script, so that it is centrally controlled and monitored.
# Get all users
$users = Get-ChildItem -Path "C:\Users"
# Loop through users and delete the Teams file
$users | ForEach-Object {
Remove-Item -Path "C:\Users\$($_.Name)\AppData\Roaming\Microsoft\Teams\Cache\f*" -Force
Remove-Item -Path "C:\Users\$($_.Name)\AppData\Roaming\Microsoft\Teams\Application Cache\Cache\f*" -Force
}
}
}
I am trying to test a script to delete a folder in APPdata local folder for a user on machine but testing it locally on my test machine. i cannot use the %userprofile% so technically need to delete a test folder at c:/users/testusername/appdata/local/test
Whats the correct command to delete folders or files from a local user account? I don't want to use the exact name of user.
Also for power shell if i want to delete folders that begin with test_foldername is there a way i can wild card to delete anything with "test_"?
Thanks
Ended up using the following
$users = Get-ChildItem C:\Users
foreach ($user in $users){$folder = "$($user.fullname)\AppData\Local\Test"
If (Test-Path $folder) {Remove-Item $folder -Recurse -Force -ErrorAction silentlycontinue } }
Get-Childitem -Directory -Path $env:LOCALAPPDATA | where {$_.Name -like 'test_*'} | Remove-Item -Force -Recurse -WhatIf
Remove the -WhatIf to actual perform the delete
$env:LOCALAPPDATA will refer to the oaming app data location for the user running the script
I'm trying to delete some users from AD and also take out their home directories. However, we have a script that denies us Administrators rights to their desktop.ini's because that stops their folder name being resolved in Explorer. However, when I want to blow out their whole home directory, the fact that there desktop.ini is still there means the parent folder can't be deleted either. I thought the below script would give me rights but it hasn't. What am I missing guys?
If (Test-Path $homeDir) {
$user = $_.uname
Set-ItemProperty -Path "\\server\students\home\$user" -Name Attributes -Value "Normal"
$acl = Get-Acl "\\server\students\home\$user"
$acl.access | where-object {$_.AccessControlType -eq "Deny"} | Foreach-object { $acl.RemoveAccessRule($_) }
(Get-Item "\\server\students\home\$user").SetAccessControl($acl)
Get-ChildItem -Path "\\server\students\home\$user\*" -Recurse | Remove-Item -Force -Recurse
Remove-Item "\\server\students\home\$user" -Recurse
Write-host "$user's home directory deleted successfully"
}
It's external to PowerShell (runs within PS just fine though) but I would suggest using icalcs as it makes this much simpler...
icacls "\\server\students\home\$user" /grant administrators:F /t