0% found this document useful (0 votes)
103 views

PowerShell Tutorial 25-32

The document discusses various PowerShell commands for managing files and folders on Windows systems. It covers how to view directory contents, create and delete files/folders, and copy files between local and remote locations. The commands provided can be used to automate routine file management tasks.

Uploaded by

erster
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

PowerShell Tutorial 25-32

The document discusses various PowerShell commands for managing files and folders on Windows systems. It covers how to view directory contents, create and delete files/folders, and copy files between local and remote locations. The commands provided can be used to automate routine file management tasks.

Uploaded by

erster
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

To add users to group from a CSV file, run the following PowerShell script:

Import-CSV C:\scripts\users.csv -Header users | ForEach-Object {Add-AdGroupMember


-Identity "Quality" -members $_.users}

If you want to copy all members from one group to another group, run the following script:

Get-ADGroupMember “Quality” | Get-ADUser | ForEach-Object {Add-ADGroupMember


-Identity “QualityControl” -Members $_}

2.9 Removing Users and Computers from a Group


To remove a user from a group, use the Remove-ADGroupMember cmdlet:

Remove-ADGroupMember -Identity Quality -Members J.Robinson

To remove a computer account from a group, specify the computer name with a dollar sign ($) at the end as
the value for the -Members parameter.

An easy way to remove multiple users from an AD group is to create a CSV file with the list of usernames and
then remove those users from the group object using this script:

Import-CSV C:\scripts\users.csv -Header users | ForEach-Object {Remove-ADGroupMember


-Identity "Quality" -members $_.users}

To remove a user from all groups, run this script:

Get-ADUser -Identity E.Franklin -Properties MemberOf | ForEach-Object {


$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false
}

25
Note that the user will lose all group membership except Domain Users, which can be removed manually if
needed.

Don’t forget to enable the Active Directory Recycle Bin feature so you can easily roll back your changes if
something goes wrong.

2.10 Moving Users and Computers to a New Organizational Unit


The PowerShell Move-ADObject cmdlet moves any object or set of objects (such as a user, a computer, a
group or an OU) to a specified OU. The -Identity parameter specifies which Active Directory object or
container to move. Note that you need to enter the full LDAP path or SID of the object; you cannot use its
SamAccountName. Here’s how to move the user “John Brown” to the “Districts” OU:

Move-ADObject -Identity "CN=John Brown,CN=Users,DC=enterprise,DC=com" -TargetPath


"OU=Districts,OU=IT,DC=Enterprise,DC=Com"

Use the same syntax to move computer objects. The following command will move the computer “R07GF” to
the “Computers” container:

Move-ADObject -Identity "CN=R07GF,OU=CEO,DC=enterprise,DC=com" -TargetPath


"CN=Computers,DC=Enterprise,DC=Com"

If you have a predefined list of objects to move, you can save it as a CSV file and then import that file to Active
Directory. The CSV list should be in the following format:

26
Use this PowerShell script to move AD user accounts listed in a CSV file:

# Specify target OU. This is where users will be moved.


$TargetOU = "OU=Districts,OU=IT,DC=enterprise,DC=com"
# Specify CSV path. Import CSV file and assign it to a variable.
$Imported_csv = Import-Csv -Path "C:\temp\MoveList.csv"

$Imported_csv | ForEach-Object {
# Retrieve DN of user.
$UserDN = (Get-ADUser -Identity $_.Name).distinguishedName
# Move user to target OU.
Move-ADObject -Identity $UserDN -TargetPath $TargetOU
}

To move AD computer accounts listed in a text file, use the following PowerShell script:

# Specify path to the text file with the computer account names.
$computers = Get-Content C:\Temp\Computers.txt

# Specify the path to the OU where computers will be moved.


$TargetOU = "OU=Districts,OU=IT,DC=enterprise,DC=com"
ForEach( $computer in $computers){
Get-ADComputer $computer |
Move-ADObject -TargetPath $TargetOU
}

27
3. Top 10 File System Management Tasks
Using PowerShell
Every day, system administrators have to perform a range of standard operations on the numerous files and
folders on their Windows servers, from managing user data on shared resources to maintaining backups
properly. Using the following information, you can automate many of these tasks and save time for more
important projects.

In this part, we explain how to automate file management and NTFS permissions management tasks with the
help of PowerShell scripts.

3.1 Viewing Objects in a Directory


To view the content of a directory on a Windows file server, use the Get-ChildItem cmdlet. To show all
hidden files, add the -Force parameter. The command below shows all root objects in the Shared folder:

Get-ChildItem -Force \\fs\Shared

If you want to also check all subfolders and their content, add the -Recurse parameter:

Get-ChildItem -Force \\fs\Shared -Recurse

To filter the output, add the Filter, Exclude, Include and Path parameters to the Get-ChildItem cmdlet. For
advanced object filtering, use the Where-Object cmdlet. The script below searches for all executable files in
the IT folder that were modified after April 1, 2018:

Get-ChildItem -Path \\fs\Shared\IT -Recurse -Include *.exe | Where-Object -FilterScript


{($_.LastWriteTime -gt '2018-04-01')}

28
3.2 Creating Files and Folders
To create new objects with Windows PowerShell, you can use the New-Item cmdlet and specify the type of
item you want to create, such as a directory, file or registry key. For example, this command creates a folder:

New-Item -Path '\\fs\Shared\NewFolder' -ItemType Directory

And this command creates an empty file:

New-Item -Path '\\fs\Shared\NewFolder\newfile.txt' -ItemType File

If you need to create a file and write data to it, there are at least two built-in methods. The first is to use the
Out-File cmdlet:

$text = 'Hello World!' | Out-File $text -FilePath C:\data\text.txt

To overwrite an existing file, use the –Force switch parameter.

Alternatively, you can create files using the Export-Csv cmdlet, which exports the output to a csv file that can
be opened in Excel:

Get-ADuser -Filter * | Export-Csv -Path C:\data\ADusers.csv

3.3 Deleting Files and Folders


To delete objects, use the Remove-Item cmdlet. If the object is not empty, you’ll be prompted to confirm the
deletion. Here’s how to delete the “IT” folder and all the subfolders and files inside it:

Remove-Item -Path '\\fs\shared\it\'


Confirm
The item at \\pdc\shared\it has children and the Recurse parameter was not specified. If you
continue, all children will be removed with the item. Are you sure you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):

29
If you have already made sure that every object inside the folder should be deleted, you can use the
-Recurse switch to skip the confirmation step:

Remove-Item -Path '\\fs\shared\it\' -Recurse

Sometimes you need to clean up old files from a certain directory. Here’s the way to accomplish that:

$Folder = "C:\Backups"

#delete files older than 30 days


Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
ForEach-Object {
$_ | del -Force
$_.FullName | Out-File C:\log\deletedbackups.txt -Append
}

#delete empty folders and subfolders if any exist


Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {$_.PsIsContainer -eq $True} |
? {$_.getfiles().count -eq 0} |
ForEach-Object {
$_ | del -Force
$_.FullName | Out-File C:\log\deletedbackups.txt -Append
}

30
Here’s how to check whether a file exists and delete it if it does:

$FileName = 'C:\data\log.txt'
If (Test-Path $FileName){
Remove-Item $FileName
}

To delete files from remote PCs, you must have the appropriate security permissions to access them.
Be sure to use UNC paths so the script will correctly resolve the file locations.

$filelist = @(" \c$\Temp", "\c$\Backups") #variable to delete files and folder


$computerlist = Get-Content C:\data\pc.txt #get list of remote pc's
foreach ($computer in $computerlist){
foreach ($file in $filelist){
$filepath= Join-Path "\\$computer\" "$filelist" #generate unc paths to files or folders
if (Test-Path $filepath)
{
Remove-Item $filepath -force -recurse -ErrorAction Continue}}}

3.4 Copying Files and Folders


The Copy-Item cmdlet enables you to copy objects from one path to another. The following command
creates a backup by copying the file users.xlsx from one remote computer (fs) and saving it to another (fs2)
over the network:

Copy-Item -Path \\fs\Shared\it\users.xlsx -Destination \\fs2\Backups\it\users.xlsx

If the target file already exists, the copy attempt will fail. To overwrite the existing file, even if it is in
Read-Only mode, use the -Force parameter:

Copy-Item -Path \\fs\Shared\it\users.xlsx -Destination \\fs2\Backups\it\users.xlsx -Force

If you’re copying files to or from remote computers, be sure to use UNC paths. For example, use this
command to copy files from a remote file server to the local C: directory:

Copy-Item \\fs\c$\temp -Recurse C:\data\

31
To copy files from your local directory to the remote folder, simply reverse the source and destination
locations:

Copy-Item C:\data\ -Recurse \\fs\c$\temp

You can also copy files from one remote server to another. The following script recursively copies the
\\fs\Shared\temp folder to \\fs\Shared\test:

Copy-Item \\fs\Shared\temp -Recurse \\fs\Shared\test

To copy only certain files from the source content to the destination, use the -Filter parameter. For instance,
the following command copies only txt files from one folder to another:

Copy-Item -Filter *.txt -Path \\fs\Shared\it -Recurse -Destination \\fs2\Shared\text

You can also run the XCOPY and ROBOCOPY commands to copy files, or use COM objects as in the example
below:

(New-Object -ComObject Scripting.FileSystemObject).CopyFile('\\fs\Shared', 'fs2\Backup')

3.5 Moving Files and Directories


The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location
to another. It can also move a file or subdirectory from one directory to another location.

The following command moves a specific backup file from one location to another:

Move-Item -Path \\fs\Shared\Backups\1.bak -Destination \\fs2\Backups\archive\1.bak

This script moves the entire Backups folder and its content to another location:

Move-Item -Path \\fs\Shared\Backups -Destination \\fs2\Backups\archive

The Backups directory and all its files and subfolders will then appear in the archive directory.

32

You might also like