Create a Folder Share
$Shares=[WMICLASS]'WIN32_Share'
$sd = ([WMIClass] "Win32_SecurityDescriptor").CreateInstance() 
$shares.create($FolderPath, $ShareName, 0, 100, "Description", "", $sd)
Details
Return all the domain and forest level FSMO roles.

Example
PS C:\> $FolderPath = 'C:\PSScripts\Share'
>> $ShareName='ScriptFiles$'
>> $Shares=[WMICLASS]'WIN32_Share'
>> $sd = ([WMIClass] "Win32_SecurityDescriptor").CreateInstance()
>> $shares.create($FolderPath, $ShareName, 0, 100, "Description", "", $sd)



__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0
PSComputerName   :


  |  
Create Folder If It Doesn’t Exist
If (-not(test-path $FolderPath)){
    New-Item -type directory -Path $FolderPath
}
Details
Check if a folder path exists using the Test-Path and if it doesn’t create the folder using New-Item

Example
PS C:\> $FolderPath = "C:\PSScripts"
>> If (-not(test-path $FolderPath)){
>>     New-Item -type directory -Path $FolderPath
>> }
  
Create Test Log Files
# Set number of days, in the past, to create log files for
$days = 14
# Set directory to create logs in
$directory = "C:\Test\Logs"

$i=1
While($i -lt $days){
    # Get Date and create log file
    $date = (Get-Date).AddDays(-$i)
    $logFile = "u_ex" + ($date.Year).ToString().Substring(2,2) + (($date.Month).ToString().PadLeft(2)).Replace(" ","0") + (($date.Day).ToString().PadLeft(2)).Replace(" ","0") + ".log"
    $logPath = join-path $directory $logFile
    $date | out-file $logPath

    # Set the Creation, Write, and Access time of log file to match date
    Get-Item $logPath | % { $_.CreationTime = $date; $_.LastWriteTime = $date; $_.LastAccessTime = $date }

    $i++
}
Details
These commands will create a log file for each day, go back as many days as specified. The file attributes will be set to the past as well. This is great for testing cleanup scripts.

  |  
Delete File if it Exists
If (Test-Path $FilePath){
	Remove-Item $FilePath
}
Details
This snippet uses the Test-Path to ensure the file exists. If it does, it will then delete it using Remove-Item

Example
PS C:\> $FilePath = "C:\temp\temp01.csv"
>> If (Test-Path $FilePath){
>> 	Remove-Item $FilePath
>> }
  
Delete Files Older Than Specified Number of Days
# Set number of days, in the past, to delete files
$days = 7
# Set directory to create logs in
$directory = "C:\Test\Logs"

# Get all files in the directory include '-recurse' to also get sub folders
$files = Get-ChildItem -Path $directory -File
# filter to ones last written to over X number of days
$ToDelete = $files | Where-Object{$_.LastWriteTime -lt (Get-Date).Date.AddDays(-$days)}
# Delete the files
$ToDelete | Remove-Item -Force
Details
These commands return all the files in a directory and remove the ones older than the specified number of days.

  |  
Get All Files and Folders in a Directory
# add '-recurse' to include sub folders
Get-ChildItem -Path $directory
Details
This command will return all the files and folders in a directory. Include ‘-recurse’ parameter to also return sub folders

Example
PS C:\> $directory = "C:\temp"
>> Get-ChildItem -Path $directory



    Directory: C:\temp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        6/19/2019  12:53 PM                Logs
-a----        6/19/2019  11:45 AM         528685 temp01.csv
-a----        6/19/2019  11:45 AM         528685 temp02.csv

  |  
Get All Files in a Directory
# add '-recurse' to include sub folders
Get-ChildItem -Path $directory -File
Details
This command will return all the files in a directory, and does not return the folders. Include ‘-recurse’ parameter to also return sub folders

Example
PS C:\> $directory = "C:\temp"
>> Get-ChildItem -Path $directory -File



    Directory: C:\temp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        6/19/2019  11:45 AM         528685 temp01.csv
-a----        6/19/2019  11:45 AM         528685 temp02.csv

  |  
Get All Files with a Certain Extension
# add '-recurse' to include sub folders
Get-ChildItem -Path $directory -Filter "*.CSV"
Details
This command will return all the files in a directory and returns the ones that match the filter criteria. Include ‘-recurse’ parameter to also return sub folders

Example
PS C:\> $directory = "C:\temp"
>> Get-ChildItem -Path $directory -Filter "*.CSV"



    Directory: C:\temp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        6/19/2019  11:45 AM         528685 temp01.csv
-a----        6/19/2019  11:45 AM         528685 temp02.csv

  |  
Get All Folders in a Directory
# add '-recurse' to include sub folders
Get-ChildItem -Path $directory -Directory
Details
This command will return all the folders in a directory, and does not return the files. Include ‘-recurse’ parameter to also return sub folders

Example
PS C:\> $directory = "C:\temp"
>> Get-ChildItem -Path $directory -Directory



    Directory: C:\temp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        6/19/2019  12:53 PM                Logs

  |  
Get File Name and Extension from Path
# Return just the file name
[System.IO.Path]::GetFileName($FilePath)

# Returns file name without the extension
[System.IO.Path]::GetFileNameWithoutExtension($FilePath)

# Returns the file extension only
[System.IO.Path]::GetExtension($FilePath)
Details
Show examples of how to get the file name and extension information from the full file path

Example
PS C:\> $FilePath = "C:\Scripts\ScriptSearcher.ps1"
>> [System.IO.Path]::GetFileName($FilePath)
>> [System.IO.Path]::GetFileNameWithoutExtension($FilePath)
>> [System.IO.Path]::GetExtension($FilePath)

ScriptSearcher.ps1
ScriptSearcher
.ps1
  
Get Folder Path of the Current Script
Function Get-ScriptDirectory{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
    if($Invocation.PSScriptRoot){
        $Invocation.PSScriptRoot;
    }
    elseif($Invocation.MyCommand.Path){
        Split-Path $Invocation.MyCommand.Path
    }
    elseif($Invocation.InvocationName.LastIndexOf("\") -gt 0){
        $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
    }
    else {
        Get-PSDrive | Where-Object{$_.Provider.Name -eq 'FileSystem'} | Foreach-Object {
            Join-Path -Path $_.Root -ChildPath $_.CurrentLocation
        }
    }
}
Details
Returns the path of the script being executed. If unavailable, it will return the path of the PowerShell console.

Example
PS C:\> Function Get-ScriptDirectory{
>>     $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
>>     if($Invocation.PSScriptRoot){
>>         $Invocation.PSScriptRoot;
>>     }
>>     elseif($Invocation.MyCommand.Path){
>>         Split-Path $Invocation.MyCommand.Path
>>     }
>>     elseif($Invocation.InvocationName.LastIndexOf("\") -gt 0){
>>         $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
>>     }
>>     else {
>>         Get-PSDrive | Where-Object{$_.Provider.Name -eq 'FileSystem'} | Foreach-Object {
>>             Join-Path -Path $_.Root -ChildPath $_.CurrentLocation
>>         }
>>     }
>> }
>> Get-ScriptDirectory

C:\Scripts
  
Get User’s Desktop Path
$ShellFolders = Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
$ShellFolders.Desktop
Details
Check the User Shell Folders registry keys for the path to the user’s desktop. This is better than using environmental variables as they may be using folder redirects.
  |  |  
Grant Permissions to Folder Share
Grant-SmbShareAccess -name $ShareName -AccountName $Account -AccessRight Full -Force
Details
Grants share permissions to a user or group

Example
PS C:\> $ShareName = 'ScriptFiles


>> $Account = 'Domain Admins'
>> Grant-SmbShareAccess -name $ShareName -AccountName $Account -AccessRight Full -Force


Name                    ScopeName               AccountName             AccessControlType       AccessRight
----                    ---------               -----------             -----------------       -----------
ScriptFiles$            *                       DOWST\Domain Admins     Allow                   Full

  |  |  
Revoke All Permissions From Folder Share
Get-SmbShareAccess -name $ShareName | Foreach {Revoke-SmbShareAccess -name $ShareName  -AccountName $_.AccountName -Force}
Details
Gets all the permissions for the share, then revokes them.

Example
PS C:\> $ShareName='ScriptFiles

>> Get-SmbShareAccess -name $ShareName | Foreach {Revoke-SmbShareAccess -name $ShareName  -AccountName $_.AccountName -Force}


Name                    ScopeName               AccountName             AccessControlType       AccessRight
----                    ---------               -----------             -----------------       -----------
ScriptFiles$            *                       NT AUTHORITY\SYSTEM     Allow                   Full
ScriptFiles$            *                       *S-1-5-5-0-158796760    Allow                   Read
ScriptFiles$            *                       *S-1-5-5-0-158796760    Allow                   Read
ScriptFiles$            *                       Everyone                Deny                    Full

  |  |  
Zip All Files in Folder
# Get the files to zip
$FilesToZip = Get-ChildItem -Path $FolderPath -File

# Load the assembly to get the zip functionality
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null
# Set compression level
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal

# Set Zip file pathc based on folder
$ZipPath = Join-Path $FolderPath "$(Split-Path $FolderPath -Leaf).zip"

# initialize the zip file
$Archive = [System.IO.Compression.ZipFile]::Open( $ZipPath, "Update" )

# add each file to the zip
Foreach($file in $FilesToZip){
    $AddZip = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($Archive, $file.FullName, $file.Name, $compressionLevel)
}

# release the zip
$Archive.Dispose()
Write-Output "The file '$ZipPath' has been created"
Details
Creates a zip file and add every file from the specified directory into it. The zip file is named after the folder and will be placed inside of it.

Example
PS C:\> $FolderPath = "C:\Scripts\Logs"
>> $FilesToZip = Get-ChildItem -Path $FolderPath -File
>> [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null
>> $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
>> $ZipPath = Join-Path $FolderPath "$(Split-Path $FolderPath -Leaf).zip"
>> $Archive = [System.IO.Compression.ZipFile]::Open( $ZipPath, "Update" )
>> Foreach($file in $FilesToZip){
>>     $AddZip = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($Archive, $file.FullName, $file.Name, $compressionLevel)
>> }
>> $Archive.Dispose()
>> Write-Output "The file '$ZipPath' has been created"

The file 'C:\Scripts\Logs\Logs.zip' has been created
  |  |  |