Author : MD TAREQ HASSAN | Updated : 2021/09/25

Check File and Folder Exists

Folder

$folderPath = "$PSScriptRoot\NewFolder"

if(!(Test-Path $folderPath))
{
    # create folder
}

File

$filePath = "$PSScriptRoot\NewFolder\xyz.txt"

if(Test-Path $filePath)
{
    # File exists, do something
}

Get Downloads Folder

#
# Windows PowerShell 5.1
#
$downloadsFolder = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path

Write-Host "Downloads folder: $downloadsFolder"




#
# PowerShell Core
#
$downloadsFolder = "$env:USERPROFILE\Downloads"

Write-Host "Downloads folder: $downloadsFolder"

Create folder

$folderPath = "$PSScriptRoot\NewFolder"
if(!(Test-Path $folderPath))
{
    New-Item -ItemType Directory -Force -Path $folderPath
}

#
# One liner
#
[System.IO.Directory]::CreateDirectory($folderPath)

Create File

$fileNameWithExtension = ''
$targetFolder = ''
$filePath = "$targetFolder\$fileNameWithExtension"

if (!(Test-Path $filePath)) {
  New-Item -ItemType File -Path $targetFolder -Name $fileNameWithExtension
}

Create File and Write Content

$targetFilePath = 'x\y\z.json'

$content = @'
{
"x" : "...",
"y" : "...",
"y" : "..."
}
'@

echo $content > $targetFilePath

If you face encoding problem, you can use this to create a file and add content

Write Content To File

function Write-ContentToFile {
    param (
        [Parameter(Mandatory)]
        [string] $Content,
        [Parameter(Mandatory)]
        [string] $FileUriWithExtension
    )

    try {
        Write-Output $Content > $FileUriWithExtension
    }
    catch {
        Write-Warning $Error[0]
    }
}

Read Json as Hashtable

function Read-JsonFileAsHashTable {
    param (
        [Parameter(Mandatory)]
        [string] $JsonFileUriWithExtension
    )

    $ht = @{}

    try {

        $ht = Get-Content -Raw -Path $JsonFileUriWithExtension | ConvertFrom-Json -AsHashtable
    }
    catch {

        Write-Warning $Error[0]
    }

    return $ht
}

Cleanup Folder

$dirPath = '.\test-dir'

if (Test-Path $dirPath) {
    # Clean up folder
    Remove-Item $dirPath\* -Force -Recurse | Out-Null
} else {
    # Create folder
    New-Item -Path .\$dirPath -ItemType Directory | Out-Null
}

Delete a Folder

Remove-Item -LiteralPath "foldertodelete" -Force -Recurse

Remove-Item $folderPath -Force -Recurse -ErrorAction SilentlyContinue