Scripts for Files & Folders
Scripts for Files & Folders 관련
cd-autostart.ps1
This PowerShell script changes the working directory to the user's autostart folder.
PS> ./cd-autostart.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-autostart.ps1
# 📂C:\Users\Markus\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
#
<#
.SYNOPSIS
Sets the working directory to the user's autostart folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's autostart folder.
.EXAMPLE
PS> ./cd-autostart.ps1
📂C:\Users\Markus\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "$HOME/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup"
if (-not(Test-Path "$Path" -pathType container)) {
throw "Autostart folder at 📂$Path doesn't exist (yet)"
}
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-desktop.ps1
This PowerShell script changes the working directory to the user's desktop folder.
PS> ./cd-desktop.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-desktop
# 📂/home/Markus/Desktop
#
<#
.SYNOPSIS
Sets the working directory to the user's desktop folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's desktop folder.
.EXAMPLE
PS> ./cd-desktop
📂/home/Markus/Desktop
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) {
$Path = Resolve-Path "~/Desktop"
} else {
$Path = [Environment]::GetFolderPath('DesktopDirectory')
}
if (Test-Path "$Path" -pathType container) {
Set-Location "$Path"
"📂$Path"
exit 0 # success
}
throw "User's desktop folder at 📂$Path doesn't exist (yet)"
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-docs.ps1
This PowerShell script changes the working directory to the documents folder.
PS> ./cd-docs.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-docs
# 📂C:\Users\Markus\Documents
#
<#
.SYNOPSIS
Sets the working directory to the documents folder
.DESCRIPTION
This PowerShell script changes the working directory to the documents folder.
.EXAMPLE
PS> ./cd-docs
📂C:\Users\Markus\Documents
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) {
$Path = Resolve-Path "$HOME/Documents"
} else {
$Path = [Environment]::GetFolderPath('MyDocuments')
}
if (-not(Test-Path "$Path" -pathType container)) {
throw "Documents folder at 📂$Path doesn't exist (yet)"
}
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-downloads.ps1
This PowerShell script changes the working directory to the user's downloads folder.
PS> ./cd-downloads.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-downloads
# 📂C:\Users\Markus\Downloads
#
<#
.SYNOPSIS
Sets the working directory to the user's downloads folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's downloads folder.
.EXAMPLE
PS> ./cd-downloads
📂C:\Users\Markus\Downloads
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) {
$Path = Resolve-Path "~/Downloads"
} else {
$Path = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path
}
if (Test-Path "$Path" -pathType container) {
Set-Location "$Path"
"📂$Path"
exit 0 # success
}
throw "User's downloads folder at 📂$Path doesn't exist (yet)"
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-dropbox.ps1
This PowerShell script changes the working directory to the user's Dropbox folder.
PS> ./cd-dropbox.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-dropbox
# 📂C:\Users\Markus\Dropbox
#
<#
.SYNOPSIS
Sets the working directory to the user's Dropbox folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's Dropbox folder.
.EXAMPLE
PS> ./cd-dropbox
📂C:\Users\Markus\Dropbox
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "$HOME/Dropbox"
if (-not(Test-Path "$Path" -pathType container)) {
throw "Dropbox folder at 📂$Path doesn't exist (yet)"
}
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-home.ps1
This PowerShell script changes the working directory to the user's home directory.
PS> ./cd-home.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-home
# 📂C:\Users\Markus
#
<#
.SYNOPSIS
Sets the working directory to the user's home folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's home directory.
.EXAMPLE
PS> ./cd-home
📂C:\Users\Markus
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path -Path "~"
if (Test-Path "$Path" -pathType container) {
Set-Location "$Path"
"📂$Path"
exit 0 # success
}
throw "User's home folder at 📂$Path doesn't exist (yet)"
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-music.ps1
This PowerShell script changes the working directory to the user's music folder.
PS> ./cd-music.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-music
# 📂C:\Users\Markus\Music
<#
.SYNOPSIS
Sets the working directory to the user's music folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's music folder.
.EXAMPLE
PS> ./cd-music
📂C:\Users\Markus\Music
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) {
$Path = Resolve-Path "~/Music"
} else {
$Path = [Environment]::GetFolderPath('MyMusic')
}
if (Test-Path "$Path" -pathType container) {
Set-Location "$Path"
"📂$Path"
exit 0 # success
}
throw "User's music folder at 📂$Path doesn't exist (yet)"
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-onedrive.ps1
This PowerShell script changes the working directory to the user's OneDrive folder.
PS> ./cd-onedrive.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-onedrive
# 📂C:\Users\Markus\OneDrive
#
<#
.SYNOPSIS
Sets the working directory to the user's OneDrive folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's OneDrive folder.
.EXAMPLE
PS> ./cd-onedrive
📂C:\Users\Markus\OneDrive
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "$HOME/OneDrive"
if (-not(Test-Path "$Path" -pathType container)) {
throw "OneDrive folder at 📂$Path doesn't exist (yet)"
}
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-pics.ps1
This PowerShell script changes the working directory to the user's pictures folder.
PS> ./cd-pics.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-pics
# 📂C:\Users\Markus\Pictures
#
<#
.SYNOPSIS
Sets the working directory to the user's pictures folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's pictures folder.
.EXAMPLE
PS> ./cd-pics
📂C:\Users\Markus\Pictures
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) {
$Path = Resolve-Path "$HOME/Pictures"
} else {
$Path = [Environment]::GetFolderPath('MyPictures')
}
if (-not(Test-Path "$Path" -pathType container)) { throw "Pictures folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-recycle-bin.ps1
PS> ./cd-recycle-bin.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-recycle-bin.ps1
#
<#
.SYNOPSIS
Sets the working directory to the user's recycle bin folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's recycle bin folder.
.EXAMPLE
PS> ./cd-recycle-bin
📂C:\$Recycle.Bin\S-1-5-21-123404-23309-294260-1001
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
function GetCurrentUserSID { [CmdletBinding()] param()
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
return ([System.DirectoryServices.AccountManagement.UserPrincipal]::Current).SID.Value
}
try {
if ($IsLinux) {
$Path = "$HOME/.local/share/Trash/"
} else {
$Path = "C:\$Recycle.Bin\" + "$(GetCurrentUserSID)"
}
if (-not(Test-Path "$Path" -pathType container)) { throw "Recycle bin folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-repos.ps1
This PowerShell script changes the working directory to the user's Git repositories folder.
PS> ./cd-repos.ps1 [[-Subpath] <String>] [<CommonParameters>]
-Subpath <String>
Specifies an additional relative subpath (optional)
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-repos
# 📂C:\Users\Markus\source\Repos
#
<#
.SYNOPSIS
Sets the working directory to the user's repos folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's Git repositories folder.
.PARAMETER Subpath
Specifies an additional relative subpath (optional)
.EXAMPLE
PS> ./cd-repos
📂C:\Users\Markus\source\Repos
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$Subpath = "")
try {
if (Test-Path "$HOME/Repos" -pathType Container) { # try short name
$Path = "$HOME/Repos/$Subpath"
} elseif (Test-Path "$HOME/Repositories" -pathType Container) { # try long name
$Path = "$HOME/Repositories/$Subpath"
} elseif (Test-Path "$HOME/source/repos" -pathType Container) { # try Visual Studio default
$Path = "$HOME/source/repos/$Subpath"
} else {
throw "The folder for Git repositories in your home directory doesn't exist (yet)."
}
if (-not(Test-Path "$Path" -pathType Container)) { throw "The path to 📂$Path doesn't exist (yet)." }
$Path = Resolve-Path "$Path"
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error: $($Error[0])"
exit 1
}
cd-root.ps1
This PowerShell script changes the current working directory to the root directory (C:\
on Windows).
PS> ./cd-root.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-root
# 📂C:\
#
<#
.SYNOPSIS
Sets the working directory to the root directory
.DESCRIPTION
This PowerShell script changes the current working directory to the root directory (C:\ on Windows).
.EXAMPLE
PS> ./cd-root
📂C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) { $Path = "/" } else { $Path = "C:\" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-scripts.ps1
This PowerShell script changes the working directory to the PowerShell scripts folder.
PS> ./cd-scripts.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-scripts
# 📂C:\Users\Markus\source\repos\PowerShell\Scripts
#
<#
.SYNOPSIS
Sets the working directory to the PowerShell scripts folder
.DESCRIPTION
This PowerShell script changes the working directory to the PowerShell scripts folder.
.EXAMPLE
PS> ./cd-scripts
📂C:\Users\Markus\source\repos\PowerShell\Scripts
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "$PSScriptRoot"
if (-not(Test-Path "$Path" -pathType container)) { throw "PowerShell scripts folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-ssh.ps1
This PowerShell script changes the working directory to the user's SSH folder.
PS> ./cd-ssh.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-ssh
# 📂C:\Users\Markus\.ssh
#
<#
.SYNOPSIS
Sets the working directory to the user's SSH folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's SSH folder.
.EXAMPLE
PS> ./cd-ssh
📂C:\Users\Markus\.ssh
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "~/.ssh"
if (-not(Test-Path "$Path" -pathType container)) { throw "User's SSH folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-up.ps1
This PowerShell script changes the working directory to one directory level up.
PS> ./cd-up.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-up
# 📂C:\Users
#
<#
.SYNOPSIS
Sets the working directory to one level up
.DESCRIPTION
This PowerShell script changes the working directory to one directory level up.
.EXAMPLE
PS> .\cd-up
📂C:\Users
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path ".."
if (-not(Test-Path "$Path" -pathType container)) { throw "Folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-up2.ps1
This PowerShell script changes the working directory to two directory level up.
PS> ./cd-up2.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-up2
# 📂C:\
#
<#
.SYNOPSIS
Sets the working directory to two directory levels up
.DESCRIPTION
This PowerShell script changes the working directory to two directory level up.
.EXAMPLE
PS> ./cd-up2
📂C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "../.."
if (-not(Test-Path "$Path" -pathType container)) { throw "Folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-up3.ps1
This PowerShell script changes the working directory to three directory levels up.
PS> ./cd-up3.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-up3
📂C:\
<#
.SYNOPSIS
Sets the working directory to three directory levels up
.DESCRIPTION
This PowerShell script changes the working directory to three directory levels up.
.EXAMPLE
PS> ./cd-up3
📂C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "../../.."
if (-not(Test-Path "$Path" -pathType container)) { throw "Folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-up4.ps1
This PowerShell script changes the working directory to four directory levels up.
PS> ./cd-up4.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-up4
# 📂C:\
#
<#
.SYNOPSIS
Sets the working directory to four directory levels up
.DESCRIPTION
This PowerShell script changes the working directory to four directory levels up.
.EXAMPLE
PS> ./cd-up4
📂C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path "../../../.."
if (-not(Test-Path "$Path" -pathType container)) { throw "Folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
cd-videos.ps1
This PowerShell script changes the working directory to the user's videos folder.
PS> ./cd-videos.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./cd-videos
# 📂C:\Users\Markus\Videos
#
<#
.SYNOPSIS
Sets the working directory to the user's videos folder
.DESCRIPTION
This PowerShell script changes the working directory to the user's videos folder.
.EXAMPLE
PS> ./cd-videos
📂C:\Users\Markus\Videos
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) {
$Path = Resolve-Path "$HOME/Videos"
} else {
$Path = [Environment]::GetFolderPath('MyVideos')
}
if (-not(Test-Path "$Path" -pathType container)) { throw "Videos folder at 📂$Path doesn't exist (yet)" }
Set-Location "$Path"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
check-symlinks.ps1
This PowerShell script checks every symbolic link in a folder (including subfolders). It returns the number of broken symlinks as exit value.
PS> ./check-symlinks.ps1 [[-Folder] <String>] [<CommonParameters>]
-Folder <String>
Specifies the path to the folder
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./check-symlinks C:\Users
# ⏳ Checking symlinks at 📂C:\Users including subfolders...
# ✔️ Found 0 broken symlinks at 📂C:\Users in 60 sec
#
<#
.SYNOPSIS
Checks symlinks in a folder
.DESCRIPTION
This PowerShell script checks every symbolic link in a folder (including subfolders).
It returns the number of broken symlinks as exit value.
.PARAMETER folder
Specifies the path to the folder
.EXAMPLE
PS> ./check-symlinks C:\Users
⏳ Checking symlinks at 📂C:\Users including subfolders...
✔️ Found 0 broken symlinks at 📂C:\Users in 60 sec
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$Folder = "")
try {
if ($Folder -eq "" ) { $Folder = read-host "Enter the path to the folder" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
$FullPath = Resolve-Path "$Folder"
"⏳ Checking symlinks at 📂$FullPath including subfolders..."
[int]$NumTotal = [int]$NumBroken = 0
Get-ChildItem $FullPath -recurse | Where { $_.Attributes -match "ReparsePoint" } | ForEach-Object {
$Symlink = $_.FullName
$Target = ($_ | Select-Object -ExpandProperty Target -ErrorAction Ignore)
if ($Target) {
$path = $_.FullName + "\..\" + ($_ | Select-Object -ExpandProperty Target)
$item = Get-Item $path -ErrorAction Ignore
if (!$item) {
$NumBroken++
"Symlink $Symlink to: $Target seems broken (#$NumBroken)"
}
}
$NumTotal++
}
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
if ($NumTotal -eq 0) {
"✔️ No symlink found at 📂$FullPath in $Elapsed sec"
} elseif ($NumBroken -eq 1) {
"✔️ Found $NumBroken broken symlink at 📂$FullPath in $Elapsed sec"
} else {
"✔️ Found $NumBroken broken symlinks at 📂$FullPath in $Elapsed sec"
}
exit $NumBroken
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
check-xml-file.ps1
This PowerShell script checks the given XML file for validity.
PS> ./check-xml-file.ps1 [[-file] <String>] [<CommonParameters>]
-file <String>
Specifies the path to the XML file to check
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./check-xml-file myfile.xml
# ✔️ XML file is valid
#
<#
.SYNOPSIS
Checks the given XML file for validity
.DESCRIPTION
This PowerShell script checks the given XML file for validity.
.PARAMETER file
Specifies the path to the XML file to check
.EXAMPLE
PS> ./check-xml-file myfile.xml
✔️ XML file is valid
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$file = "")
try {
if ($file -eq "" ) { $file = read-host "Enter path to XML file" }
$XmlFile = Get-Item $file
$script:ErrorCount = 0
# Perform the XSD Validation
$ReaderSettings = New-Object -TypeName System.Xml.XmlReaderSettings
$ReaderSettings.ValidationType = [System.Xml.ValidationType]::Schema
$ReaderSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessInlineSchema -bor [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessSchemaLocation
$ReaderSettings.add_ValidationEventHandler({ $script:ErrorCount++ })
$Reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $ReaderSettings)
while ($Reader.Read()) { }
$Reader.Close()
if ($script:ErrorCount -gt 0) {
write-warning "Invalid XML file"
exit 1
}
"✔️ XML file is valid"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
clear-recycle-bin.ps1
This PowerShell script removes the content of the recycle bin folder permanently. IMPORTANT NOTE: this cannot be undo!
PS> ./clear-recycle-bin.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./clear-recycle-bin.ps1
#
<#
.SYNOPSIS
Clears the recycle bin folder
.DESCRIPTION
This PowerShell script removes the content of the recycle bin folder permanently.
IMPORTANT NOTE: this cannot be undo!
.EXAMPLE
PS> ./clear-recycle-bin
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
Clear-RecycleBin -Confirm:$false
if ($lastExitCode -ne "0") { throw "'Clear-RecycleBin' failed" }
& "$PSScriptRoot/speak-english.ps1" "It's clean now."
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
copy-photos-sorted.ps1
PS> ./copy-photos-sorted.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./copy-photos-sorted.ps1
#
<#
.SYNOPSIS
Copy photos sorted by year and month
.DESCRIPTION
This PowerShell script copies image files from sourceDir to targetDir sorted by year and month.
.PARAMETER sourceDir
Specifies the path to the source folder
.PARAMTER targetDir
Specifies the path to the target folder
.EXAMPLE
PS> ./copy-photos-sorted.ps1 D:\iPhone\DCIM C:\MyPhotos
⏳ Copying IMG_20230903_134445.jpg to C:\MyPhotos\2023\09 SEP\...
✔️ Copied 1 photo to 📂C:\MyPhotos in 41 sec
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$sourceDir = "", [string]$targetDir = "")
function CopyFile { param([string]$sourcePath, [string]$targetDir, [int]$date, [string]$filename)
[int]$year = $date / 10000
[int]$month = ($date / 100) % 100
$monthDir = switch($month) {
1 {"01 JAN"}
2 {"02 FEB"}
3 {"03 MAR"}
4 {"04 APR"}
5 {"05 MAY"}
6 {"06 JUN"}
7 {"07 JUL"}
8 {"08 AUG"}
9 {"09 SEP"}
10 {"10 OCT"}
11 {"11 NOV"}
12 {"12 DEC"}
}
$TargetPath = "$targetDir/$year/$monthDir/$filename"
if (Test-Path "$TargetPath" -pathType leaf) {
Write-Host "⏳ Skipping existing $targetDir\$year\$monthDir\$filename..."
} else {
Write-Host "⏳ Copying $filename to $targetDir\$year\$monthDir\..."
New-Item -path "$targetDir" -name "$year" -itemType "directory" -force | out-null
New-Item -path "$targetDir/$year" -name "$monthDir" -itemType "directory" -force | out-null
Copy-Item "$sourcePath" "$TargetPath" -force
}
}
try {
if ($sourceDir -eq "") { $sourceDir = Read-Host "Enter file path to the source directory" }
if ($targetDir -eq "") { $targetDir = Read-Host "Enter file path to the target directory" }
$stopWatch = [system.diagnostics.stopWatch]::startNew()
Write-Host "⏳ Checking source directory 📂$($sourceDir)..."
if (-not(Test-Path "$sourceDir" -pathType container)) { throw "Can't access source directory: $sourceDir" }
$files = (Get-ChildItem "$sourceDir\*.jpg" -attributes !Directory)
Write-Host "⏳ Checking target directory 📂$($targetDir)..."
if (-not(Test-Path "$targetDir" -pathType container)) { throw "Can't access target directory: $targetDir" }
foreach($file in $files) {
$filename = (Get-Item "$file").Name
if ("$filename" -like "IMG_*_*.jpg") {
$Array = $filename.split("_")
CopyFile "$file" "$targetDir" $Array[1] "$filename"
} elseif ("$filename" -like "IMG-*-*.jpg") {
$Array = $filename.split("-")
CopyFile "$file" "$targetDir" $Array[1] "$filename"
} elseif ("$filename" -like "PANO_*_*.jpg") {
$Array = $filename.split("_")
CopyFile "$file" "$targetDir" $Array[1] "$filename"
} elseif ("$filename" -like "PANO-*-*.jpg") {
$Array = $filename.split("-")
CopyFile "$file" "$targetDir" $Array[1] "$filename"
} elseif ("$filename" -like "SAVE_*_*.jpg") {
$Array = $filename.split("_")
CopyFile "$file" "$targetDir" $Array[1] "$filename"
} else {
Write-Host "⏳ Skipping $filename with unknown filename format..."
}
}
[int]$elapsed = $stopWatch.Elapsed.TotalSeconds
"✔️ Copied $($files.Count) photos to 📂$targetDir in $elapsed sec"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
decrypt-file.ps1
This PowerShell script decrypts a file using the given password and AES encryption.
PS> ./decrypt-file.ps1 [[-Path] <String>] [[-Password] <String>] [<CommonParameters>]
-Path <String>
Specifies the path to the file to decrypt
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-Password <String>
Specifies the password
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./decrypt-file.ps1 C:\MyFile.txt "123"
#
<#
.SYNOPSIS
Decrypts a file
.DESCRIPTION
This PowerShell script decrypts a file using the given password and AES encryption.
.PARAMETER Path
Specifies the path to the file to decrypt
.PARAMETER Password
Specifies the password
.EXAMPLE
PS> ./decrypt-file.ps1 C:\MyFile.txt "123"
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$Path = "", [string]$Password = "")
function DecryptFile {
[CmdletBinding(DefaultParameterSetName='SecureString')]
[OutputType([System.IO.FileInfo[]])]
Param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath','LiteralPath')]
[string[]]$FileName,
[Parameter(Mandatory=$false, Position=2, ValueFromPipelineByPropertyName=$true)]
[ValidateSet('AES','DES','RC2','Rijndael','TripleDES')]
[String]$Algorithm = 'AES',
[Parameter(Mandatory=$true, Position=3, ValueFromPipelineByPropertyName=$true, ParameterSetName='SecureString')]
[System.Security.SecureString]$Key,
[Parameter(Mandatory=$true, Position=3, ParameterSetName='PlainText')]
[String]$KeyAsPlainText,
[Parameter(Mandatory=$false, Position=4, ValueFromPipelineByPropertyName=$true)]
[System.Security.Cryptography.CipherMode]$CipherMode = 'CBC',
[Parameter(Mandatory=$false, Position=5, ValueFromPipelineByPropertyName=$true)]
[System.Security.Cryptography.PaddingMode]$PaddingMode = 'PKCS7',
[Parameter(Mandatory=$false, Position=6)]
[String]$Suffix,
[Parameter()]
[Switch]$RemoveSource
)
Process
{
try
{
if($PSCmdlet.ParameterSetName -eq 'PlainText')
{
$Key = $KeyAsPlainText | ConvertTo-SecureString -AsPlainText -Force
}
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Key)
$EncryptionKey = [System.Convert]::FromBase64String([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR))
$Crypto = [System.Security.Cryptography.SymmetricAlgorithm]::Create($Algorithm)
$Crypto.Mode = $CipherMode
$Crypto.Padding = $PaddingMode
$Crypto.KeySize = $EncryptionKey.Length*8
$Crypto.Key = $EncryptionKey
}
Catch
{
Write-Error $_ -ErrorAction Stop
}
if(-not $PSBoundParameters.ContainsKey('Suffix'))
{
$Suffix = ".$Algorithm"
}
$Files = Get-Item -LiteralPath $FileName
ForEach($File in $Files)
{
If(-not $File.Name.EndsWith($Suffix))
{
Write-Error "$($File.FullName) does not have an extension of '$Suffix'."
Continue
}
$DestinationFile = $File.FullName -replace "$Suffix$"
Try
{
$FileStreamReader = New-Object System.IO.FileStream($File.FullName, [System.IO.FileMode]::Open)
$FileStreamWriter = New-Object System.IO.FileStream($DestinationFile, [System.IO.FileMode]::Create)
[Byte[]]$LenIV = New-Object Byte[] 4
$FileStreamReader.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null
$FileStreamReader.Read($LenIV, 0, 3) | Out-Null
[Int]$LIV = [System.BitConverter]::ToInt32($LenIV, 0)
[Byte[]]$IV = New-Object Byte[] $LIV
$FileStreamReader.Seek(4, [System.IO.SeekOrigin]::Begin) | Out-Null
$FileStreamReader.Read($IV, 0, $LIV) | Out-Null
$Crypto.IV = $IV
$Transform = $Crypto.CreateDecryptor()
$CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write)
$FileStreamReader.CopyTo($CryptoStream)
$CryptoStream.FlushFinalBlock()
$CryptoStream.Close()
$FileStreamReader.Close()
$FileStreamWriter.Close()
if($RemoveSource){Remove-Item $File.FullName}
Get-Item $DestinationFile | Add-Member –MemberType NoteProperty –Name SourceFile –Value $File.FullName -PassThru
}
Catch
{
Write-Error $_
If($FileStreamWriter)
{
$FileStreamWriter.Close()
Remove-Item -LiteralPath $DestinationFile -Force
}
Continue
}
Finally
{
if($CryptoStream){$CryptoStream.Close()}
if($FileStreamReader){$FileStreamReader.Close()}
if($FileStreamWriter){$FileStreamWriter.Close()}
}
}
}
}
try {
if ($Path -eq "" ) { $Path = read-host "Enter path to file" }
if ($Password -eq "" ) { $Password = read-host "Enter password" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
$PasswordBase64 = [System.Convert]::ToBase64String($Password)
DecryptFile "$Path" -Algorithm AES -KeyAsPlainText $PasswordBase64 -RemoveSource
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ file decrypted in $Elapsed sec"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
download-dir.ps1
This PowerShell script downloads a folder (including subfolders) from the given URL.
PS> ./download-dir.ps1 [[-URL] <String>] [<CommonParameters>]
-URL <String>
Specifies the URL where to download from
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./download-dir.ps1 https://www.cnn.com
#
<#
.SYNOPSIS
Downloads a folder (including subfolders) from an URL
.DESCRIPTION
This PowerShell script downloads a folder (including subfolders) from the given URL.
.PARAMETER URL
Specifies the URL where to download from
.EXAMPLE
PS> ./download-dir.ps1 https://www.cnn.com
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$URL = "")
try {
if ($URL -eq "") { $URL = Read-Host "Enter directory URL to download" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
& wget --version
if ($lastExitCode -ne "0") { throw "Can't execute 'wget' - make sure wget is installed and available" }
& wget --mirror --convert-links --adjust-extension --page-requisites --no-parent $URL --directory-prefix . --no-verbose
if ($lastExitCode -ne "0") { throw "Can't execute 'wget --mirror $URL'" }
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ downloaded directory from $URL in $Elapsed sec"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
download-file.ps1
This PowerShell script downloads a file from the given URL
PS> ./download-file.ps1 [[-URL] <String>] [<CommonParameters>]
-URL <String>
Specifies the URL where to download from
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./download-file.ps1 https://www.cnn.com/index.html
#
<#
.SYNOPSIS
Downloads a file from an URL
.DESCRIPTION
This PowerShell script downloads a file from the given URL
.PARAMETER URL
Specifies the URL where to download from
.EXAMPLE
PS> ./download-file.ps1 https://www.cnn.com/index.html
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$URL = "")
try {
if ($URL -eq "") { $URL = read-host "Enter file URL to download" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
& wget --version
if ($lastExitCode -ne "0") { throw "Can't execute 'wget' - make sure wget is installed and available" }
& wget --mirror --convert-links --adjust-extension --page-requisites --no-parent $URL --directory-prefix . --no-verbose
if ($lastExitCode -ne "0") { throw "Can't execute 'wget --mirror $URL'" }
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ downloaded file from $URL in $Elapsed sec"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
edit.ps1
This PowerShell script opens a text editor to edit the given file.
PS> ./edit.ps1 [[-Filename] <String>] [<CommonParameters>]
-Filename <String>
Specifies the path to the filename
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./edit.ps1 C:\MyFile.txt
#
<#
.SYNOPSIS
Opens an editor to edit a file
.DESCRIPTION
This PowerShell script opens a text editor to edit the given file.
.PARAMETER Filename
Specifies the path to the filename
.EXAMPLE
PS> ./edit.ps1 C:\MyFile.txt
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$Filename = "")
try {
if ($IsLinux) {
& vi "$Filename"
if ($lastExitCode -ne "0") { throw "Can't execute 'vi' - make sure vi is installed and available" }
} else {
& notepad.exe "$Filename"
if ($lastExitCode -ne "0") { throw "Can't execute 'notepad.exe' - make sure notepad.exe is installed and available" }
}
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
encrypt-file.ps1
This PowerShell script encrypts a file using the given password and AES encryption.
PS> ./encrypt-file.ps1 [[-Path] <String>] [[-Password] <String>] [<CommonParameters>]
-Path <String>
Specifies the path to the file to encrypt
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-Password <String>
Specifies the password to use
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./encrypt-file.ps1 C:\MyFile.txt "123"
#
<#
.SYNOPSIS
Encrypts a file
.DESCRIPTION
This PowerShell script encrypts a file using the given password and AES encryption.
.PARAMETER Path
Specifies the path to the file to encrypt
.PARAMETER Password
Specifies the password to use
.EXAMPLE
PS> ./encrypt-file.ps1 C:\MyFile.txt "123"
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$Path = "", [string]$Password = "")
function EncryptFile {
[CmdletBinding(DefaultParameterSetName='SecureString')]
[OutputType([System.IO.FileInfo[]])]
Param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath','LiteralPath')]
[string[]]$FileName,
[Parameter(Mandatory=$false, Position=2)]
[ValidateSet('AES','DES','RC2','Rijndael','TripleDES')]
[String]$Algorithm = 'AES',
[Parameter(Mandatory=$false, Position=3, ParameterSetName='SecureString')]
[System.Security.SecureString]$Key = (New-CryptographyKey -Algorithm $Algorithm),
[Parameter(Mandatory=$true, Position=3, ParameterSetName='PlainText')]
[String]$KeyAsPlainText,
[Parameter(Mandatory=$false, Position=4)]
[System.Security.Cryptography.CipherMode]$CipherMode,
[Parameter(Mandatory=$false, Position=5)]
[System.Security.Cryptography.PaddingMode]$PaddingMode,
[Parameter(Mandatory=$false, Position=6)]
[String]$Suffix = ".$Algorithm",
[Parameter()]
[Switch]$RemoveSource
)
begin {
try {
if ($PSCmdlet.ParameterSetName -eq 'PlainText') {
$Key = $KeyAsPlainText | ConvertTo-SecureString -AsPlainText -Force
}
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Key)
$EncryptionKey = [System.Convert]::FromBase64String([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR))
$Crypto = [System.Security.Cryptography.SymmetricAlgorithm]::Create($Algorithm)
if ($PSBoundParameters.ContainsKey('CipherMode')) {
$Crypto.Mode = $CipherMode
}
if ($PSBoundParameters.ContainsKey('PaddingMode')) {
$Crypto.Padding = $PaddingMode
}
$Crypto.KeySize = $EncryptionKey.Length*8
$Crypto.Key = $EncryptionKey
} catch {
Write-Error $_ -ErrorAction Stop
}
}
process {
$Files = Get-Item -LiteralPath $FileName
foreach($File in $Files) {
$DestinationFile = $File.FullName + $Suffix
try {
$FileStreamReader = New-Object System.IO.FileStream($File.FullName, [System.IO.FileMode]::Open)
$FileStreamWriter = New-Object System.IO.FileStream($DestinationFile, [System.IO.FileMode]::Create)
$Crypto.GenerateIV()
$FileStreamWriter.Write([System.BitConverter]::GetBytes($Crypto.IV.Length), 0, 4)
$FileStreamWriter.Write($Crypto.IV, 0, $Crypto.IV.Length)
$Transform = $Crypto.CreateEncryptor()
$CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write)
$FileStreamReader.CopyTo($CryptoStream)
$CryptoStream.FlushFinalBlock()
$CryptoStream.Close()
$FileStreamReader.Close()
$FileStreamWriter.Close()
if ($RemoveSource) {
Remove-Item -LiteralPath $File.FullName
}
$result = Get-Item $DestinationFile
$result | Add-Member –MemberType NoteProperty –Name SourceFile –Value $File.FullName
$result | Add-Member –MemberType NoteProperty –Name Algorithm –Value $Algorithm
$result | Add-Member –MemberType NoteProperty –Name Key –Value $Key
$result | Add-Member –MemberType NoteProperty –Name CipherMode –Value $Crypto.Mode
$result | Add-Member –MemberType NoteProperty –Name PaddingMode –Value $Crypto.Padding
$result
} catch {
Write-Error $_
if ($FileStreamWriter) {
$FileStreamWriter.Close()
Remove-Item -LiteralPath $DestinationFile -Force
}
continue
} finally {
if($CryptoStream){$CryptoStream.Close()}
if($FileStreamReader){$FileStreamReader.Close()}
if($FileStreamWriter){$FileStreamWriter.Close()}
}
}
}
}
try {
if ($Path -eq "" ) { $Path = read-host "Enter path to file" }
if ($Password -eq "" ) { $Password = read-host "Enter password" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
[char[]]$PasswordAsArray = $Password
$PasswordAsBase64 = [System.Convert]::ToBase64String($PasswordAsArray)
EncryptFile "$Path" -Algorithm AES -KeyAsPlainText $PasswordAsBase64 -RemoveSource
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ file encrypted in $Elapsed sec"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
get-md5.ps1
This PowerShell script calculates and prints the MD5 checksum of the given file.
PS> ./get-md5.ps1 [[-file] <String>] [<CommonParameters>]
-file <String>
Specifies the path to the file
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./get-md5 C:\MyFile.txt
# ✔️ MD5 hash is 041E16F16E60AD250EB794AF0681BD4A
#
<#
.SYNOPSIS
Prints the MD5 checksum of a file
.DESCRIPTION
This PowerShell script calculates and prints the MD5 checksum of the given file.
.PARAMETER file
Specifies the path to the file
.EXAMPLE
PS> ./get-md5 C:\MyFile.txt
✔️ MD5 hash is 041E16F16E60AD250EB794AF0681BD4A
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$file = "")
try {
if ($file -eq "" ) { $file = Read-Host "Enter path to file" }
$Result = Get-Filehash $file -algorithm MD5
"✔️ MD5 hash is $($Result.Hash)"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
get-sha1.ps1
This PowerShell script calculates and prints the SHA1 checksum of the given file.
PS> ./get-sha1.ps1 [[-file] <String>] [<CommonParameters>]
-file <String>
Specifies the path to the file
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./get-sha1 C:\MyFile.txt
# ✔️ SHA1 hash is 8105D424D350E308AED92BD9DDEB74A1B53C5D7C
#
<#
.SYNOPSIS
Prints the SHA1 checksum of a file
.DESCRIPTION
This PowerShell script calculates and prints the SHA1 checksum of the given file.
.PARAMETER file
Specifies the path to the file
.EXAMPLE
PS> ./get-sha1 C:\MyFile.txt
✔️ SHA1 hash is 8105D424D350E308AED92BD9DDEB74A1B53C5D7C
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$file = "")
try {
if ($file -eq "" ) { $file = Read-Host "Enter the filename" }
$Result = get-filehash $file -algorithm SHA1
"✔️ SHA1 hash is $($Result.Hash)"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
get-sha256.ps1
This PowerShell script calculates and prints the SHA256 checksum of the given file.
PS> ./get-sha256.ps1 [[-file] <String>] [<CommonParameters>]
-file <String>
Specifies the path to the file
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./get-sha256 C:\MyFile.txt
# ✔️ SHA256 hash is: CEB4AD71524996EB8AA3ADCE04F1E45636A4B58B8BF4462E6971CF2E56B4293E
#
<#
.SYNOPSIS
Prints the SHA256 checksum of a file
.DESCRIPTION
This PowerShell script calculates and prints the SHA256 checksum of the given file.
.PARAMETER file
Specifies the path to the file
.EXAMPLE
PS> ./get-sha256 C:\MyFile.txt
✔️ SHA256 hash is: CEB4AD71524996EB8AA3ADCE04F1E45636A4B58B8BF4462E6971CF2E56B4293E
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$file = "")
try {
if ($file -eq "" ) { $file = Read-Host "Enter the filename" }
$Result = get-filehash $file -algorithm SHA256
"✔️ SHA256 hash is: $($Result.Hash)"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
inspect-exe.ps1
This PowerShell script prints basic information of an executable file.
PS> ./inspect-exe.ps1 [[-PathToExe] <String>] [<CommonParameters>]
-PathToExe <String>
Specifies the path to the executable file
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./inspect-exe C:\MyApp.exe
#
<#
.SYNOPSIS
Prints basic information of an executable file
.DESCRIPTION
This PowerShell script prints basic information of an executable file.
.PARAMETER PathToExe
Specifies the path to the executable file
.EXAMPLE
PS> ./inspect-exe C:\MyApp.exe
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$PathToExe = "")
try {
if ($PathToExe -eq "" ) { $PathToExe = read-host "Enter path to executable file" }
Get-ChildItem $PathToExe | % {$_.VersionInfo} | Select *
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
❌ list-dir-tree.ps1
list-empty-dirs.ps1
This PowerShell script scans and lists all empty subfolders within the given directory tree.
PS> ./list-empty-dirs.ps1 [[-DirTree] <String>] [<CommonParameters>]
-DirTree <String>
Specifies the path to the directory tree (current working directory by default)
Required? false
Position? 1
Default value "$PWD"
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-empty-dirs.ps1 C:\
#
<#
.SYNOPSIS
Lists empty subfolders
.DESCRIPTION
This PowerShell script scans and lists all empty subfolders within the given directory tree.
.PARAMETER DirTree
Specifies the path to the directory tree (current working directory by default)
.EXAMPLE
PS> ./list-empty-dirs.ps1 C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$DirTree = "$PWD")
try {
$StopWatch = [system.diagnostics.stopwatch]::startNew()
$DirTree = Resolve-Path "$DirTree"
Write-Progress "⏳Listing empty subfolders in $DirTree..."
[int]$Count = 0
Get-ChildItem "$DirTree" -attributes Directory -recurse | Where {$_.GetFileSystemInfos().Count -eq 0} | ForEach-Object {
"📂$($_.FullName)"
$Count++
}
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ found $Count empty subfolders within directory tree $DirTree in $Elapsed sec."
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
list-empty-files.ps1
This PowerShell script scans and lists all empty files within the given directory tree.
PS> ./list-empty-files.ps1 [[-DirTree] <String>] [<CommonParameters>]
-DirTree <String>
Specifies the path to the directory tree
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-empty-files.ps1 C:\
#
<#
.SYNOPSIS
Lists empty files within a directory tree
.DESCRIPTION
This PowerShell script scans and lists all empty files within the given directory tree.
.PARAMETER DirTree
Specifies the path to the directory tree
.EXAMPLE
PS> ./list-empty-files.ps1 C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$DirTree = "")
try {
if ($DirTree -eq "" ) { $DirTree = read-host "Enter the path to the directory tree" }
[int]$Count = 0
Write-Progress "⏳Listing empty files in $DirTree ..."
get-childItem $DirTree -attributes !Directory -recurse | where {$_.Length -eq 0} | foreach-object {
write-output $_.FullName
$Count++
}
"✔️ found $Count empty file(s)"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
list-files.ps1
This PowerShell script lists all files within the given directory tree.
PS> ./list-files.ps1 [[-DirTree] <String>] [<CommonParameters>]
-DirTree <String>
Specifies the path to the directory tree
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-files.ps1 C:\
#
<#
.SYNOPSIS
Lists all files in a directory tree
.DESCRIPTION
This PowerShell script lists all files within the given directory tree.
.PARAMETER DirTree
Specifies the path to the directory tree
.EXAMPLE
PS> ./list-files.ps1 C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$DirTree = "")
try {
if ($DirTree -eq "" ) { $DirTree = read-host "Enter path to directory tree" }
Get-ChildItem -path $DirTree -recurse | select FullName
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
list-folder.ps1
This PowerShell script lists the content of a directory (alphabetically formatted in columns).
PS> ./list-folder.ps1 [[-searchPattern] <String>] [<CommonParameters>]
-searchPattern <String>
Specifies the search pattern ("*" by default which means anything)
Required? false
Position? 1
Default value *
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-folder.ps1 C:\*
#
<#
.SYNOPSIS
Lists a folder
.DESCRIPTION
This PowerShell script lists the content of a directory (alphabetically formatted in columns).
.PARAMETER SearchPattern
Specifies the search pattern ("*" by default which means anything)
.EXAMPLE
PS> ./list-folder.ps1 C:\*
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$searchPattern = "*")
function GetFileIcon { param([string]$suffix)
switch ($suffix) {
".csv" {return "📊"}
".epub" {return "📓"}
".exe" {return "⚙️"}
".gif" {return "📸"}
".iso" {return "📀"}
".jpg" {return "📸"}
".mp3" {return "🎵"}
".mkv" {return "🎬"}
".zip" {return "🎁"}
default {return "📄"}
}
}
function ListFolder { param([string]$searchPattern)
$items = Get-ChildItem -path "$searchPattern"
foreach ($item in $items) {
$name = $item.Name
if ($name[0] -eq '.') { continue } # hidden file/dir
if ($item.Mode -like "d*") { $icon = "📂" } else { $icon = GetFileIcon $item.Extension }
New-Object PSObject -property @{ Name = "$icon$name" }
}
}
try {
ListFolder $searchPattern | Format-Wide -autoSize
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
list-hidden-files.ps1
This PowerShell script scans and lists all hidden files in a directory tree.
PS> ./list-hidden-files.ps1 [[-DirTree] <String>] [<CommonParameters>]
-DirTree <String>
Specifies the path to the directory tree
Required? false
Position? 1
Default value "$PWD"
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-hidden-files.ps1 C:\
#
<#
.SYNOPSIS
Lists hidden files in a directory tree
.DESCRIPTION
This PowerShell script scans and lists all hidden files in a directory tree.
.PARAMETER DirTree
Specifies the path to the directory tree
.EXAMPLE
PS> ./list-hidden-files.ps1 C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$DirTree = "$PWD")
try {
$DirTree = resolve-path "$DirTree"
Write-Progress "⏳Listing hidden files in $DirTree ..."
[int]$Count = 0
get-childItem "$DirTree" -attributes Hidden -recurse | foreach-object {
"📄 $($_.FullName)"
$Count++
}
"✔️ directory tree $DirTree has $Count hidden file(s)"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
list-recycle-bin.ps1
This PowerShell script lists the content of the recycle bin folder.
PS> ./list-recycle-bin.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-recycle-bin.ps1
#
<#
.SYNOPSIS
Lists the content of the recycle bin folder
.DESCRIPTION
This PowerShell script lists the content of the recycle bin folder.
.EXAMPLE
PS> ./list-recycle-bin.ps1
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
(New-Object -ComObject Shell.Application).NameSpace(0x0a).Items() | Select-Object Name,Size,Path
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
list-unused-files.ps1
This PowerShell script scans and lists files in a folder with last access time older than number of days.
PS> ./list-unused-files.ps1 [[-DirTree] <String>] [[-Days] <Int32>] [<CommonParameters>]
-DirTree <String>
Specifies the path to the directory tree
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-Days <Int32>
Specifies the number of days
Required? false
Position? 2
Default value 100
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-unused-files.ps1 C:\ 100
#
<#
.SYNOPSIS
Lists unused files in a directory tree
.DESCRIPTION
This PowerShell script scans and lists files in a folder with last access time older than number of days.
.PARAMETER DirTree
Specifies the path to the directory tree
.PARAMETER Days
Specifies the number of days
.EXAMPLE
PS> ./list-unused-files.ps1 C:\ 100
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$DirTree = "", [int]$Days = 100)
write-host "Listing files in $DirTree with last access time older than $Days days"
try {
$cutOffDate = (Get-Date).AddDays(-$Days)
Get-ChildItem -path $DirTree -recurse | Where-Object {$_.LastAccessTime -le $cutOffDate} | select fullname
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
list-workdir.ps1
This PowerShell script lists the path to current working directory (but not the content itself).
PS> ./list-workdir.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./list-workdir.ps1
# 📂C:\Users\Markus
#
<#
.SYNOPSIS
Lists the current working directory
.DESCRIPTION
This PowerShell script lists the path to current working directory (but not the content itself).
.EXAMPLE
PS> ./list-workdir.ps1
📂C:\Users\Markus
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
$Path = Resolve-Path -Path "$PWD"
"📂$Path"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
make-install.ps1
This PowerShell script copies newer EXE's + DLL's from the build directory to the installation directory.
PS> ./make-install.ps1 [<CommonParameters>]
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./make-install.ps1
#
<#
.SYNOPSIS
Copies newer EXE's + DLL's from the build directory to the installation directory
.DESCRIPTION
This PowerShell script copies newer EXE's + DLL's from the build directory to the installation directory.
.EXAMPLE
PS> ./make-install.ps1
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
set SRC_DIR=%1
set "DST_DIR=C:\Program Files\MyApp\bin"
set FILTER=*.exe *.dll
set OPTIONS=/E /njh /np
try {
title Syncing to %DST_DIR% ...
robocopy %SRC_DIR% %DST_DIR% %FILTER% %OPTIONS%
echo ------------------------------------------------------------------------------
echo.
"✔️ synced to %DST_DIR%"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
new-shortcut.ps1
This PowerShell script creates a new shortcut file.
PS> ./new-shortcut.ps1 [[-shortcut] <String>] [[-target] <String>] [[-description] <String>] [<CommonParameters>]
-shortcut <String>
Specifies the shortcut filename
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-target <String>
Specifies the path to the target
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
-description <String>
Specifies a description
Required? false
Position? 3
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./new-shortcut C:\Temp\HDD C:\
<#
.SYNOPSIS
Creates a new shortcut file
.DESCRIPTION
This PowerShell script creates a new shortcut file.
.PARAMETER shortcut
Specifies the shortcut filename
.PARAMETER target
Specifies the path to the target
.PARAMETER description
Specifies a description
.EXAMPLE
PS> ./new-shortcut C:\Temp\HDD C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$shortcut = "", [string]$target = "", [string]$description)
try {
if ($shortcut -eq "" ) { $shortcut = read-host "Enter new shortcut filename" }
if ($target -eq "" ) { $target = read-host "Enter path to target" }
if ($description -eq "" ) { $description = read-host "Enter description" }
$sh = new-object -ComObject WScript.Shell
$sc = $sh.CreateShortcut("$shortcut.lnk")
$sc.TargetPath = "$target"
$sc.WindowStyle = "1"
$sc.IconLocation = "C:\Windows\System32\SHELL32.dll, 3"
$sc.Description = "$description"
$sc.save()
"✔️ created new shortcut $shortcut ⭢ $target"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
new-symlink.ps1
This PowerShell script creates a new symbolic link file.
PS> ./new-symlink.ps1 [[-symlink] <String>] [[-target] <String>] [<CommonParameters>]
-symlink <String>
Specifies the new symlink filename
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-target <String>
Specifies the path to target
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./new-symlink.ps1 C:\Temp\HDD C:\
#
<#
.SYNOPSIS
Creates a new symbolic link file
.DESCRIPTION
This PowerShell script creates a new symbolic link file.
.PARAMETER symlink
Specifies the new symlink filename
.PARAMETER target
Specifies the path to target
.EXAMPLE
PS> ./new-symlink.ps1 C:\Temp\HDD C:\
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$symlink = "", [string]$target = "")
try {
if ($symlink -eq "" ) { $symlink = read-host "Enter new symlink filename" }
if ($target -eq "" ) { $target = read-host "Enter path to target" }
new-item -path "$symlink" -itemType SymbolicLink -Value "$target"
"✔️ created new symlink $symlink ⭢ $target"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
new-zipfile.ps1
This PowerShell script creates a new .ZIP file from a folder (including subfolders).
PS> ./new-zipfile.ps1 [[-folder] <String>] [<CommonParameters>]
-folder <String>
Specifies the path to the folder
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./new-zipfile.ps1 C:\Windows
#
<#
.SYNOPSIS
Creates a new .ZIP file from a folder (including subfolders)
.DESCRIPTION
This PowerShell script creates a new .ZIP file from a folder (including subfolders).
.PARAMETER folder
Specifies the path to the folder
.EXAMPLE
PS> ./new-zipfile.ps1 C:\Windows
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$folder = "")
try {
if ($folder -eq "" ) { $folder = read-host "Enter the path to the folder to zip" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
$folder = resolve-path $folder
compress-archive -path $folder -destinationPath $folder.zip
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ created zip file $($folder).zip in $Elapsed sec"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
publish-to-ipfs.ps1
This script publishes the given files and folders to IPFS.
PS> ./publish-to-ipfs.ps1 [[-FilePattern] <String>] [[-HashList] <String>] [[-DF_Hashes] <String>] [<CommonParameters>]
-FilePattern <String>
Specifies the file pattern
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-HashList <String>
Specifies the path to the resulting hash list
Required? false
Position? 2
Default value IPFS_hashes.txt
Accept pipeline input? false
Accept wildcard characters? false
-DF_Hashes <String>
Specifies the path to the resulting digital forensic hashes
Required? false
Position? 3
Default value file_checksums.xml
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./publish-to-ipfs C:\MyFile.txt
#
<#
.SYNOPSIS
Publishes files & folders to IPFS
.DESCRIPTION
This script publishes the given files and folders to IPFS.
.PARAMETER FilePattern
Specifies the file pattern
.PARAMETER HashList
Specifies the path to the resulting hash list
.PARAMETER DF_Hashes
Specifies the path to the resulting digital forensic hashes
.EXAMPLE
PS> ./publish-to-ipfs C:\MyFile.txt
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$FilePattern = "", [string]$HashList = "IPFS_hashes.txt", [string]$DF_Hashes = "file_checksums.xml")
try {
if ($FilePattern -eq "") { $FilePattern = read-host "Enter file(s)/directories to publish" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
Write-Host "⏳ (1/3) Searching for IPFS executable..." -NoNewline
& ipfs --version
if ($lastExitCode -ne "0") { throw "Can't execute 'ipfs' - make sure IPFS is installed and available" }
if (test-path "$FilePattern" -pathType container) {
"⏳ (2/3) Publishing folder $FilePattern/..."
& ipfs add -r "$FilePattern" > $HashList
[int]$Count = 1
""
"⏳ (3/3) Calculating digital forensics hashes to $DF_HASHES ..."
& nice hashdeep -c md5,sha1,sha256 -r -d -l -j 1 "$FilePattern" > $DF_Hashes
} else {
$FileList = (get-childItem "$FilePattern")
foreach ($File in $FileList) {
if (test-path "$FilePattern" -pathType container) {
"⏳ (2/3) Publishing folder $File/..."
& ipfs add -r "$File" >> $HashList
} else {
"⏳ (3/3) Publishing file $File..."
& ipfs add "$File" >> $HashList
}
}
[int]$Count = $FileList.Count
}
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ published $Count file(s)/folder(s) to IPFS in $Elapsed sec"
" NOTE: to publish it to IPNS execute: ipfs name publish <HASH>"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
remove-empty-dirs.ps1
This PowerShell script removes all empty subfolders within a directory tree.
PS> ./remove-empty-dirs.ps1 [[-DirTree] <String>] [<CommonParameters>]
-DirTree <String>
Specifies the path to the directory tree
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./remove-empty-dirs C:\Temp
#
<#
.SYNOPSIS
Removes all empty subfolders within a directory tree
.DESCRIPTION
This PowerShell script removes all empty subfolders within a directory tree.
.PARAMETER DirTree
Specifies the path to the directory tree
.EXAMPLE
PS> ./remove-empty-dirs C:\Temp
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$DirTree = "")
try {
if ($DirTree -eq "" ) { $DirTree = read-host "Enter the path to the directory tree" }
$Folders = @()
foreach ($Folder in (Get-ChildItem -path "$DirTree" -Recurse | Where { $_.PSisContainer })) {
$Folders += New-Object PSObject -Property @{
Object = $Folder
Depth = ($Folder.FullName.Split("\")).Count
}
}
$Folders = $Folders | Sort Depth -Descending
$Deleted = @()
foreach ($Folder in $Folders)
{
if ($Folder.Object.GetFileSystemInfos().Count -eq 0) {
$Deleted += New-Object PSObject -Property @{
Folder = $Folder.Object.FullName
Deleted = (Get-Date -Format "hh:mm:ss tt")
Created = $Folder.Object.CreationTime
'Last Modified' = $Folder.Object.LastWriteTime
Owner = (Get-Acl $Folder.Object.FullName).Owner
}
Remove-Item -Path $Folder.Object.FullName -Force
}
}
"✔️ Done."
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
replace-in-files.ps1
This PowerShell script searches and replaces a pattern in the given files by the replacement.
PS> ./replace-in-files.ps1 [[-pattern] <String>] [[-replacement] <String>] [[-files] <String>] [<CommonParameters>]
-pattern <String>
Specifies the pattern to look for
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-replacement <String>
Specifies the replacement
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
-files <String>
Specifies the file to scan
Required? false
Position? 3
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./replace-in-files NSA "No Such Agency" C:\Temp\*.txt
<#
.SYNOPSIS
Search and replace a pattern in the given files by the replacement
.DESCRIPTION
This PowerShell script searches and replaces a pattern in the given files by the replacement.
.PARAMETER pattern
Specifies the pattern to look for
.PARAMETER replacement
Specifies the replacement
.PARAMETER files
Specifies the file to scan
.EXAMPLE
PS> ./replace-in-files NSA "No Such Agency" C:\Temp\*.txt
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$pattern = "", [string]$replacement = "", [string]$files = "")
function ReplaceInFile { param([string]$FilePath, [string]$Pattern, [string]$Replacement)
[System.IO.File]::WriteAllText($FilePath,
([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
)
}
try {
if ($pattern -eq "" ) { $pattern = read-host "Enter search pattern" }
if ($replacement -eq "" ) { $replacement = read-host "Enter replacement" }
if ($files -eq "" ) { $files = read-host "Enter files" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
$fileList = (get-childItem -path "$files" -attributes !Directory)
foreach($file in $fileList) {
ReplaceInFile $file $pattern $replacement
}
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"OK, replaced '$pattern' by '$replacement' in $($fileList.Count) files in $Elapsed sec."
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
search-filename.ps1
This PowerShell script serves as a quick Powershell replacement to the search functionality in Windows After you pass in a root folder and a search term, the script will list all files and folders matching that phrase.
PS> ./search-filename.ps1 [-path] <Object> [-term] <Object> [<CommonParameters>]
-path <Object>
Specifies the path
Required? true
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-term <Object>
Specifies the search term
Required? true
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./search-filename
#
<#
.SYNOPSIS
Lists all files and folder names matching a search pattern
.DESCRIPTION
This PowerShell script serves as a quick Powershell replacement to the search functionality in Windows
After you pass in a root folder and a search term, the script will list all files and folders matching that phrase.
.PARAMETER path
Specifies the path
.PARAMETER term
Specifies the search term
.EXAMPLE
PS> ./search-filename
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param(
[Parameter(Mandatory=$true)]
$path,
[Parameter(Mandatory=$true)]
$term
)
# Recursive search function
Write-Host "Results:"
function Search-Folder($FilePath, $SearchTerm) {
# Get children
$children = Get-ChildItem -Path $FilePath
# For each child, see if it matches the search term, and if it is a folder, search it too.
foreach ($child in $children) {
$name = $child.Name
if ($name -match $SearchTerm) {
Write-Host "$FilePath\$name"
}
$isdir = Test-Path -Path "$FilePath\$name" -PathType Container
if ($isdir) {
Search-Folder -FilePath "$FilePath\$name" -SearchTerm $SearchTerm
}
}
}
# Call the search function
Search-Folder -FilePath $path -SearchTerm $term
exit 0 # success
search-files.ps1
This PowerShell script searches for a pattern in the given files.
PS> ./search-files.ps1 [[-pattern] <String>] [[-files] <String>] [<CommonParameters>]
-pattern <String>
Specifies the search pattern
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-files <String>
Specifies the files
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> ./search-files UFO C:\Temp\*.txt
<#
.SYNOPSIS
Searches for a pattern in files
.DESCRIPTION
This PowerShell script searches for a pattern in the given files.
.PARAMETER pattern
Specifies the search pattern
.PARAMETER files
Specifies the files
.EXAMPLE
PS> ./search-files UFO C:\Temp\*.txt
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$pattern = "", [string]$files = "")
function ListLocations { param([string]$Pattern, [string]$Path)
$List = Select-String -Path $Path -Pattern "$Pattern"
foreach ($Item in $List) {
New-Object PSObject -Property @{
'Path' = "$($Item.Path)"
'Line' = "$($Item.LineNumber)"
'Text' = "$($Item.Line)"
}
}
write-output "(found $($List.Count) locations with pattern '$pattern')"
}
try {
if ($pattern -eq "" ) { $pattern = read-host "Enter search pattern" }
if ($files -eq "" ) { $files = read-host "Enter path to files" }
ListLocations $pattern $files | format-table -property Path,Line,Text
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
upload-file.ps1
This PowerShell script uploads a local file to a FTP server.
PS> ./upload-file.ps1 [[-File] <String>] [[-URL] <String>] [[-Username] <String>] [[-Password] <String>] [<CommonParameters>]
-File <String>
Specifies the path to the local file
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-URL <String>
Specifies the FTP server URL
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
-Username <String>
Specifies the user name
Required? false
Position? 3
Default value
Accept pipeline input? false
Accept wildcard characters? false
-Password <String>
Specifies the password
Required? false
Position? 4
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
PS> .\upload-file.ps1
#
<#
.SYNOPSIS
Uploads a local file to a FTP server
.DESCRIPTION
This PowerShell script uploads a local file to a FTP server.
.PARAMETER File
Specifies the path to the local file
.PARAMETER URL
Specifies the FTP server URL
.PARAMETER Username
Specifies the user name
.PARAMETER Password
Specifies the password
.EXAMPLE
PS> .\upload-file.ps1
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$File = "", [string]$URL = "", [string]$Username = "", [string]$Password = "")
try {
if ($File -eq "") { $File = read-host "Enter local file to upload" }
if ($URL -eq "") { $URL = read-host "Enter URL of FTP server" }
if ($Username -eq "") { $Username = read-host "Enter username for login" }
if ($Password -eq "") { $Password = read-host "Enter password for login" }
[bool]$EnableSSL = $true
[bool]$UseBinary = $true
[bool]$UsePassive = $true
[bool]$KeepAlive = $true
[bool]$IgnoreCert = $true
$StopWatch = [system.diagnostics.stopwatch]::startNew()
# check local file:
$FullPath = Resolve-Path "$File"
if (-not(test-path "$FullPath" -pathType leaf)) { throw "Can't access file: $FullPath" }
$Filename = (Get-Item $FullPath).Name
$FileSize = (Get-Item $FullPath).Length
"⏳ Uploading 📄$Filename ($FileSize bytes) to $URL ..."
# prepare request:
$Request = [Net.WebRequest]::Create("$URL/$Filename")
$Request.Credentials = New-Object System.Net.NetworkCredential("$Username", "$Password")
$Request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$Request.EnableSSL = $EnableSSL
$Request.UseBinary = $UseBinary
$Request.UsePassive = $UsePassive
$Request.KeepAlive = $KeepAlive
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$IgnoreCert}
$fileStream = [System.IO.File]::OpenRead("$FullPath")
$ftpStream = $Request.GetRequestStream()
$Buf = New-Object Byte[] 32KB
while (($DataRead = $fileStream.Read($Buf, 0, $Buf.Length)) -gt 0)
{
$ftpStream.Write($Buf, 0, $DataRead)
$pct = ($fileStream.Position / $fileStream.Length)
Write-Progress -Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) -PercentComplete ($pct * 100)
}
# cleanup:
$ftpStream.Dispose()
$fileStream.Dispose()
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"✔️ uploaded 📄$Filename to $URL in $Elapsed sec"
exit 0 # success
} catch {
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0]) after $Elapsed sec."
exit 1
}