PowerShell Snippets: Output list of folders and sub-folders

PowerShellThis post is part of the series on PowerShell Snippets.

The following PowerShell command will export a list of folders and sub-folders from the specified location (the first highlighted section is the starting folder and the second the output path for the CS file):

Get-ChildItem -Path \\nas3\public\movies -Recurse -Directory -ErrorAction SilentlyContinue | Select-Object FullName | Export-CSV c:\temp\export.txt

Run escalated PowerShell script from a batch file

PowerShellI posted a Power Shell snippet a while ago on bypassing the execution policy. More recently I needed to combine that with running a script with administrator permissions. I did a little exploring and found an article by Adam Dimech which contained this code which can be run from a batch file:

Change the highlighted section to your saved ps1 file and you can run that script escalated with administrator permissions.

PowerShell  -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""{path and filename of ps1 file}""' -Verb RunAs}"

Unlock BitLocker protected drive with PowerShell

PowerShellI recently needed to unlock a HDD encrypted with BitLocker a number of times. I rapidly decided that entering the password manually every time was not something I wanted to do, so for that day, I needed a command line method of doing it. Fortunately, PowerShell has a commandlet available to do this:

$SecureString = ConvertTo-SecureString "{password}" -AsPlainText -Force
Unlock-BitLocker -MountPoint "X:" -Password $SecureString

The above came from the PowerShell section of the Microsoft Docs site.

The highlighted section, including braces, should be replaced with the password for the drive.

As the PowerShell script has to have the password embedded within it, this is not something I would recommend for every day use.

PowerShell to run script bypassing execution policy

PowerShellIn yesterday’s article, I posted a script which can be used to download and delete files from a folder on an FTP site. When I tested it on one computer it worked fine, but on another it failed as the running of PowerShell is restricted. To avoid this error the PowerShell script can be saved to a file with a ps1 extension and then executed using the following (replace the highlighted section with your filename):

powershell -executionpolicy bypass -File "download files.ps1"

This will bypass the execution policy restricting the script from running and allow it to run without issue.

PowerShell script to download all files from FTP folder then delete files

PowerShellA few weeks ago, I did an article on making folder backups on an FTP site and compressed MySQL backups using Cron.

With the backups made, they need to be downloaded and this is not something I want to do manually. My initial thought was VBA until common sense kicked in and I opted for PowerShell. I found a post on Stack overflow which had the required script to connect to an FTP site and download files which got me half of what I needed.

I did some reading up and was able to work out the function to delete files on an FTP site and have included that in the PowerShell below so that this script both downloads files and deletes them.

There are several parameters which need to be set and these are placed at the top and highlighted to make them easy to identify; make sure all of the highlighted parts are replaced including the curly brackets.

#FTP Server Information - SET VARIABLES
$ftp = "{ftp site}"
$user = "{user}"
$pass = "{password}"
$folder = "{source folder}"
$target = "{destination folder}"

#Register get FTP Directory function
function Get-FtpDir ($url, $credentials) {
	$request = [Net.WebRequest]::Create($url)
	$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory

	if ($credentials) { $request.Credentials = $credentials }
	
	$response = $request.GetResponse()
	$reader = New-Object IO.StreamReader $response.GetResponseStream() 
	
	while(-not $reader.EndOfStream) {
		$reader.ReadLine()
	}
	
	$reader.Close()
	$response.Close()
}

#Register Delete function
function Del-FtpFile($source, $credentials) {
    $source2 = [system.URI] $source
	
    $ftp = [System.Net.FtpWebRequest]::create($source2)
    $ftp.Credentials = $credentials

    $ftp.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile
	
    $ftp.GetResponse()
}

#Set Crednetials
$credentials = new-object System.Net.NetworkCredential($user, $pass)

#set folder path
$folderPath= $ftp + "/" + $folder + "/"

$files = Get-FTPDir -url $folderPath -credentials $credentials

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = $credentials 
$counter = 0
foreach ($file in ($files | where {$_ -like "*.gz"})){
	$source = $folderPath + $file  
	$destination = $target + $file 
	$webclient.DownloadFile($source, $destination)
	
	#PRINT FILE NAME AND COUNTER
	$counter++
	$source
	
	# DELETE FILE
	Del-FtpFile -source $source -credentials $credentials
}

PowerShell Snippets: Start-Sleep

PowerShellThis post is part of the series on PowerShell Snippets.

The following PowerShell command will sleep for the supplied number of milliseconds (replace the highlighted section with the number of milliseconds to sleep):

Start-Sleep -Milliseconds {milliseconds}

PowerShell Snippets: Write-Output

PowerShellThis post is part of the series on PowerShell Snippets.

The following PowerShell command will output the supplied message to the PowerShell console (replace the highlighted section with the message to output):

Write-Output {message]

PowerShell Snippets: Series Index

PowerShellFrom time to time, I write snippets of PowerShell, which I am going to post into this series for easy recall in future.

PowerShell Snippets
Write-Output
Start-Sleep
PowerShell to run script bypassing execution policy
Unlock BitLocker protected drive with PowerShell
Run escalated PowerShell script from a batch file
Output list of folders and sub-folders
Delete File
Run Application (Such as 7-zip)
Format Json for Curl
Use Curl
Use Curl
Use Curl
Use Curl
Get One Value from GitHub Json
Get Numeric Value from String
Prompt for User Input
Prompt User for Password
Prompt for Multiple Inputs
Prompt for Multiple Inputs

PowerShell for Hyper-V: Resume VM

Hyper-VThis post is part of the series on PowerShell for Hyper-V.

The following PowerShell command can be used to resume a suspended virtual machine (replace the highlighted section with the name of your virtual machine):

Resume-VM -Name {VM name}

PowerShell for Hyper-V: Suspend VM

Hyper-VThis post is part of the series on PowerShell for Hyper-V.

The following PowerShell command can be used to suspend (pause) a virtual machine (replace the highlighted section with the name of your virtual machine):

Suspend-VM -Name {VM name}