Professional Documents
Culture Documents
PowerShellBasics:ManagingFilesandFolders
ByTimFerrill ,SEPTEMBER19,20142:00PM
1.Find,Copy,Move&DeleteFileswithPowerShell
EverySysAdminhastodealwithmanagingfilesandfolders.Forrepetitivetasks,suchasfind,copy,moveanddelete,youcansavetime
byusingPowerShelltoautomatethetasks.
RegardlessofyournicheintheITindustry,chancesaresomepartofyourdailygrindinvolvesmanagingfilesandfoldersinsomeway.Whetherit'smovingfolderstoanother
locationonaserver,archivinglogfiles,orlookingforlargefilesalmosteverysystemadministratorspendspartoftheirdaymanagingfilesandfolders.Incaseswhererepetitive
tasksarebeingrepeatedonmultiplefiles,orthesamesetoftasksarerunrepeatedly,automationthroughtheuseofPowerShellcanbearealtimesaver.See:PowerShellTools,
Cmdlets&Modules
FindingFilesandFolders
Oneofthefirstcommandlinetoolsadministratorswouldlearninyeoldendaysofcomputerswasthedircommand.Forthosenewtothegame,dirwouldlistthefilesandfolders
containedwithinthespecifieddirectory.PowerShellfeaturesasimilarcommandintheformoftheGetChildItemcmdlet.GetChildItemallowsyoutoquicklybuildalistingofthe
filesinadirectoryinawaythatyoucanthenactonthesefileseitherthroughapipedcommandorbyassigningtheoutputtoavariable.
Atitsmostbasic,GetChildItemcanbeusedsimplybyprovidingapath,eitherthroughthepipeline,usingthePathparameter,orimmediatelyfollowingthecmdletname.Inorder
totunetheresponsereturnedbyGetChildItemitiskeytotakealookatsomeoftheparametersmadeavailablebythecmdlet.
TheFilterparameterisonewayyoucansearchforfilesmatchingaspecificnameorfiletype.Bydefault,theGetChildItemcmdletonlyreturnsdirectchildrenofthetarget
directory,functionalitywhichcanbeexpandedusingtheRecurseswitch,whichrecursivelysearchesdirectoriescontainedwithinthecurrentfolder.
InPowerShell4.0GetChildItemaddstheabilitytolimittheresulttoeitherafileorfolderbyusingtheFileorDirectoryswitches.PriorversionsofPowerShellhadtopipethe
resulttoWhereObject,filteringonthePSIsContainerpropertyinordertomakethisdetermination.Anexampleofbothtechniquesbeingusedtoreturnthefolderscontainedin
C:Usersisshownhere:
GetChildItemC:UsersDirectory
GetChildItemC:Users|WhereObject{$_.PSIsContainereq$true}
InordertodiscoverhiddenorsystemfilestheForceswitchmustbeused.GetChildIteminPowerShell4.0canalsobeusedtoreturnonlythosefileswhicharehidden,readonly,
orsystemfilesusingtheHidden,ReadOnly,andSystemswitchesrespectively.ThesamefunctionalitycanbeachievedinpriorversionsbyfilteringontheModepropertyusing
WhereObject:
GetChildItemC:Users|WhereObject{$_.Modelike'*R*'}
CheckingifaFileExists
Oftenwhenworkingwithfiles,allweneedtoknowiswhetherafileexistsorafolderpathisvalid.PowerShelloffersacmdlettoperformthisvalidationintheformofTestPath,
whichreturnseitheratrueorfalsevalue.
TestPathisoftenusefulasaprecautionarysteppriortoattemptingtocopyordeleteaparticularfile.
Copying,Moving,andDeletingFiles
Asyouwouldexpect,PowerShellisfullycapableofperformingstandardfileoperationsonnumerousobjectsinasinglepass.TheCopyItemcmdletcanbeusedtocopyoneor
morefilesorfoldersfromonelocation,identifiedbythePathparameter,tothelocationspecifiedbytheDestinationoption.
LikewisetheMoveItemcmdletisusedwhenrelocatingafileorfolder.Whenafolderstructureisbeingcopiedormoved,theRecurseswitchshouldbeusedinordertohavethe
cmdletperformtheactiononthefolderanditscontents.InsomecasestheForceswitchisneeded,suchaswhenareadonlyfileisbeingoverwrittenbythecopyoperation.
FilesandfolderscanbedeletedusingtheRemoveItemcmdlet.Asisthethemewithmanyofthecmdletsdiscussedhere,theForceswitchmustbeusedwhenhiddenorread
onlyfilesareencountered,andRecurseshouldbeusedwhendeletingafolderanditscontents.
UsingPowerShellWhatIfandConfirm
It'sbeensaidofscriptsthattheyenablepeopletodostupidthingsextremelyquickly.Beforeyoupullthetriggeronabigdeleteoperation,makeuseoftheWhatIfswitchoffered
forthemajorityofthecmdletsdiscussedhere.
TheWhatIfswitchallowsyoutoseewhatwillhappenifyouactuallyrunthescriptorcommand,withoutthepotentialnegativeeffectsofdeletingcriticalbusinessdata.It'salso
worthnotingthatWhatIfisn'tlimitedtofileoperations,it'swidelyusedthroughoutPowerShell.
Forscriptsthatyouintendtomanuallyrunorworse,haveasubordinatemanuallyrun,considerusingConfirm.Thisallowsyoutorequireuserinteractionpriortotheoperation
actuallytakingplace.Oftenthisispreferabletosimplyassumingeverythingisreadytogo(filebackupscomplete,replicationdisabled,etc.)priortolargefileoperationsbeing
initiated.
RELATED:
AccessingWindowsRegistrywithPowerShell
TricksforManagingActiveDirectorywithPowerShell
EasilyAddUserstoActiveDirectorywithPowerShell
MorePowerShellHowTos
HotTopics
FollowTomsITPro
Hardware
Management
Security
Servers
Software
Storage
Virtualization
AboutTom'sITPro
Advertising|AboutUs|Contact|Privacy|Pressreleases
Tom'sITProispartofBestofmediaNetworkCopyright2015BestofmediaAllRightsReserved.