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

Get Script Path

$scriptFolder = ""
if ($psISE) { # If using ISE
    $scriptFolder = Split-Path -Parent $psISE.CurrentFile.FullPath
} elseif($PSVersionTable.PSVersion.Major -gt 3) { # If Using PowerShell 3 or greater
    $scriptFolder = $PSScriptRoot
} else { # If using PowerShell 2 or lower
    $scriptFolder = split-path -parent $MyInvocation.MyCommand.Path
}

echo $scriptFolder

Create File If Not Exits

$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