Powershell


Creating new folders

Create new folder or folders with the New-Item -ItemType Directory command.
If the folder already exists, we will get an error

New-Item -ItemType Directory -Path C:\Powershell\Path\That\May\Or\May\Not\Exist

Creating new file

New-Item -ItemType File: This will create file with content using -Value parameter. We assume path already exists.
If any element of path does not exist or the file already exists, we will get a "file already exists" error.

New-Item -ItemType File -Path C:\Powershell\Path\That\May\Or\May\Not\Exist -Name "file1.txt"  -Value "Hello World"

Creating file, same as above but using variables

$path  = "C:\Powershell\Path\That\May\Or\May\Not\Exist"
$file  = "file1.txt"
$value = "Hello World"			

New-Item -ItemType File -Path $path -Name $file -Value $value 

Add the -Force parameter to create missing folders, and overrise existing file

The Force parameter lets you create a file in the profile path, even when the folders in the path do not exist. It will also ovewright existing content.

    
$path  = "C:\Powershell\Path\That\May\Or\May\Not\Exist"
$file  = "file1.txt"
$value = "Hello World"			

New-Item -ItemType File -Path $path -Name $file -Value $value -Force

Trapping errors with Try, Catch, ErrorAction and ErrorVariable

Parameter ErrorAction determines how the cmdlet responds when an error occurs. Permitted values on ErrorAction: Continue, Stop, SilentlyContinue, Inquire
Parameter ErrorVariable specifies a variable that stores errors from the command during processing.

try{
    New-Item -ItemType File -Path F:\Powershell\Path\That\May\Or\May\Not\Exist -Name "file2.txt" -Force -ErrorAction Stop
}
catch{
    Write-Output "Write failed"
}

try{
    New-Item -ItemType File -Path F:\Powershell\Path\That\May\Or\May\Not\Exist -Name "file2.txt" -Force -ErrorAction Stop -ErrorVariable error
}
catch{
    Write-Output  $error
}
Write-Output "end"