Skip to content

PowerShell file operation

Files

Renaming files [replacing specific chars in files]

rename files, replacing any old_value with new_value

get-childitem * -r | foreach {rename-item $_ $_.name.replace("old_value","new_value")}

List the files in a directory and recurse replace old_value with new_value

ls *.md -r | Rename-Item -NewName {$_.name -replace "old_value","new_value"}

Replace file/folder name value from old_value to new_value

Get-ChildItem -r | Rename-Item -NewName { $_.name -replace 'old_value', 'new_value'} -verbose

Get file full path

Get full file path recursively from a directory, where the file extension is .md

get-childitem "C:\temp\test_folder" -recurse | where {$_.extension -eq ".md"} | % {Write-Host $_.FullName}

another way of doing it

Get-ChildItem "C:\temp\test_folder" *.md -Recurse | Select-Object FullName

Create a file

create a file in D:\Temp\Test Folder with name "Test File.txt"

New-Item -Path 'D:\temp\Test Folder\Test File.txt' -ItemType File

Check file existence

check if file test.txt exists in 'D:\temp\test directory'

Test-Path D:\temp\test\test.txt

Retrieving Item

reading a file's content 'D:\Temp\Test\Test.txt'

Get-Content D:\temp\Test\test.txt

Renaming a file

rename file test.txt to test1.txt

Rename-Item D:\temp\Test\test.txt test1.txt

Moving a file

move a file from one directory to another 'D:\Temp\Test\Test.txt' to 'D:\Temp\Test1'

Move-Item D:\temp\Test\Test.txt D:\temp\Test1

Deleting file(s)

delete file 'D:\temp\Test Folder\test.txt'

Remove-Item 'D:\temp\Test Folder\test.txt'

Delete all files in directory 'D:\temp\Test Folder'

Remove-Item 'D:\temp\Test Folder' -Recurse

Copying file(s)

delete file 'D:\temp\Test Folder\test.txt'

Copy-Item 'D:\temp\Test Folder\Test File.txt' 'D:\temp\Test Folder1\Test File1.txt'

Copy files from 1 directory to another

Copy-Item -Filter *.txt -Path 'D:\temp\Test Folder' -Recurse -Destination 'D:\temp\Test Folder1'

Folders

create a folder

create a folder in D:\Temp\ with name "Test Folder"

New-Item -Path 'D:\temp\Test Folder' -ItemType Directory

Copying a folder

copy a single folder D:\Temp\Test Folder as D:\Temp\Test Folder1

Copy-Item 'D:\temp\Test Folder' 'D:\temp\Test Folder1'

copy a folder recursively D:\Temp\Test Folder to D:\Temp\Test Folder1

Copy-Item 'D:\temp\Test Folder' -Destination 'D:\temp\Test Folder1'

Renaming a folder

renaming a folder D:\Temp\Test to D:\Temp\Test1

Rename-Item "D:\temp\Test Test1"

moving a folder

move a folder D:\Temp\Test to D:\Temp\Test1

Move-Item D:\temp\Test D:\temp\Test1

Deleting a folder

delete a folder D:\Temp\Test Folder1

Remove-Item 'D:\temp\Test Folder1'

deleting folders recursively in a directory D:\Temp\Test Folder1

Remove-Item 'D:\temp\Test Folder' -Recurse

Check folder existence

Check if path exists 'D:\temp\test'

Test-Path D:\temp\test