Skip to content

Instantly share code, notes, and snippets.

@jacqinthebox
Last active October 25, 2017 14:51
Show Gist options
  • Save jacqinthebox/ee8f5ab44760328ad82c2ca1e8ecfdad to your computer and use it in GitHub Desktop.
Save jacqinthebox/ee8f5ab44760328ad82c2ca1e8ecfdad to your computer and use it in GitHub Desktop.
Powershell best practice (for me) in PowerShell #powershell

Powershell Patterns I use

Function Outline

Function New-PowershellFunction 
{
  [CmdletBinding()] 
  param(
    [Parameter(Mandatory = $true,
    ValueFromPipelineByPropertyName = $true)]
    [string]$LastName,
    
    [Parameter(Mandatory = $true,
    ValueFromPipelineByPropertyName = $true)]
    [ValidatePattern('^[a-zA-Z0-9 \-_]*$')]
    [ValidatePattern('^\S*$')]
    [string]$DepartmentName,

    [Parameter(Mandatory = $true,
    ValueFromPipelineByPropertyName = $true)]
    [ValidateRange(1,20)] 
    [Int]$Subfolders,
        
    [Parameter(Mandatory = $true,
    ValueFromPipelineByPropertyName = $false)]
    [ValidatePattern('^SRV')]
    [String]$FileServer,
        
    [Parameter(Mandatory = $true]
    [ValidateSet('c:','d:')]
    [String]$LocalDrive
  )
BEGIN {}
PROCESS {}
END {}
}

Help Outline

<#
    .Synopsis
    Creates DFS Department shares for Bla
    .DESCRIPTION
    The scripts also tests for AD security groups for Bla.
    Creates security groups for the particular DEPT with proper nesting. It creates the folders, subfolders and sets ACLS. 
    Then it creates SMB shares, then it is added to the DFS Namespace. ABE is set on the namespace.
    ACL's are set:  L-RG-$SiteCode-DEPT-L  is added with RX rights to on c:\DFSRoots\Dept\SiteName

    .EXAMPLE
    To create a single department folder:
    $folder = split-path -parent $psISE.CurrentFile.Fullpath
    cd $folder
    Remove-Module DWSMigrationToolkit -ErrorAction SilentlyContinue
    Import-Module ".\dwsmigrationtoolkit"
 
    $vars = @{
    SiteCode = '222US'
    SiteName = 'HAWAII'
    DepartmentName = 'ICT'
    }

    New-DepartmentShare @vars -verbose 

    .EXAMPLE
    Create shares in bulk
    $csvtext = @"
    DepartmentName,departmentDescription,Subfolders
    Bulk01,Folder for Bulk01,2
    Bulk02,Folder for Bulk02,2
    Bulk03,Folder for Bulk03,2
    "@

    Set-Content -path '.\import.csv' -Value $csvtext
    $csv = Import-Csv -Path .\import.csv 
#>

Test for Windows Feature

 if (((Get-WindowsFeature RSAT-DFS-Mgmt-Con ).Installed -eq $False)) {
      write-host "WindowsFeature RSAT-DFS-Mgmt-Con are not installed! Install the Cmdlets with the 'Add-WindowsFeature RSAT-DFS-Mgmt-Con' command. We will not proceed!"
      Break
    }

Try Catch Error Block

  Write-Verbose -Message 'Creating HOME security groups if not exist'   
    try 
    {
      Get-ADGroup -Identity "L-RG-$($SiteCode)-HOME-FC" -Server $SitesDomainController -ErrorAction Stop | Out-Null
    }
    catch 
    {
      Write-Verbose -Message "New-ADGroup -Name L-RG-$($SiteCode)-HOME-FC -DisplayName L-RG-$($Sitecode)-HOME-FC -GroupScope DomainLocal -Path $OUPath -Server $sitesDomainController"
      New-ADGroup -Name "L-RG-$($SiteCode)-HOME-FC" -DisplayName "L-RG-$($SiteCode)-HOME-FC" -GroupScope 'DomainLocal' -Path $OUPath -Server $SitesDomainController 
    }
        

Throw new

$subnet.ForEach(
    { 
      if ($_.Name -match $subnetName) {  
        $target = $_
      } else {
                throw [System.NullReferenceException] "$target not found."
      }
    }
  )

Splatting

$vars = @{
  SiteCode = '222US'
  SiteName = 'HAWAII'

}

New-FunnyFunction @vars -verbose

Void it

https://www.reddit.com/user/MysticRyuujin

Function PipeToNull
{
    $Array = New-Object System.Collections.ArrayList
    for ($i = 0; $i -lt 10000; $i++)
    {
        $Array.Add($i) | Out-Null
    }
}
Function VoidIt
{
    $Array = New-Object System.Collections.ArrayList
    for ($i = 0; $i -lt 10000; $i++)
    {
        [void]$Array.Add($i)
    }
}

Measure-Command { PipeToNull }
TotalMilliseconds : 205.4567

Measure-Command { VoidIt }
TotalMilliseconds : 4.3032

Heredoc notation

$setupComplete = @"
cmd.exe /c sc config winrm start= auto
cmd.exe /c net start winrm
"@

New-Item -Path 'C:\Windows\Setup\Scripts' -ItemType Directory -Force
Set-Content -path "C:\Windows\Setup\Scripts\SetupComplete.cmd" -Value $setupComplete

Just a beautiful script

Full of best practice.

Function Get-ExpiredAccounts {

$oud = Search-ADAccount -AccountExpired | Select-Object Name,ObjectClass,AccountExpirationDate,LastLogonDate,SamAccountName,telephoneNumber


foreach ($o in $oud)
 {
    $Phone = Get-AdUser -Identity $o.SamAccountName -Properties telephonenumber | Select Telephonenumber
    
        
    $object = [pscustomobject]@{
        
        Name = $o.Name
        samAccountname = $o.SamAccountName
        ExpiryDate = $o.AccountExpirationDate
        Phone = $($Phone.Telephonenumber)
    
    }
    Write-Output $object
  }

 }

Get-ExpiredAccounts | Sort-Object Expirydate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment