Monday, March 18, 2019

Create and remove new directory,file and folder using Power-Shell.


Creation and removal of directory\folder\file  in power shell is very easy .you just have pass simple command in script. Here we will see some of the example how we can create new Directory\Folder\File




Creating new Directory

New-Item -Path "c:\" -Name "Dir1" -ItemType "directory"

Creating multiple Dir using power shell

New-Item -ItemType "directory" -Path "c:\Dir1\Dir2"

New-Item -ItemType "directory" -Path "c:\Dir1\Dir2" -ErrorAction SilentlyContinue  

New-Item -ItemType Directory -Force -Path C:\Dir\You\Can\Create\Any\Time\Here


Check path exist or not condition here..

$path = "c:\Dir1\Dir2"

If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}

Creating new test file and enter new test values.

New-Item -Path C:\Temp\ -Name "testfile1.txt" -ItemType "file" -Value "This is a text string."

Create multiple files

New-Item -ItemType "file" -Path "c:\ps-test\test.txt", "c:\ps-test\Logs\test.log"




Removing files and folder from power shell

Remove-Item –path c:\Dir1\Dir2 –recurse

Remove-Item -Path "c:\Dir1\Dir2" -Force -Recurse

Remove-Item "c:\Dir1\Dir2" -Force  -Recurse -ErrorAction SilentlyContinue


The –recurse parameter will allow Power Shell to remove any child items without asking for permission

More Complex Delete Operations

Remove-Item –path c:\test\ remove-item * -include *.mp3 –recurse

More Complex Delete Operations

Remove-Item –path c:\folder\* -include *.txt


Delete the 'demo' registry key and all of its subkeys and values:

Remove-item hklm:\software\SS64\demo -Recurse


Note:- Please test script in your test environment before running in production directly.

No comments:

Post a Comment