markdown PowerShell #powershell中的Powershell最佳实践(对我而言)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown PowerShell #powershell中的Powershell最佳实践(对我而言)相关的知识,希望对你有一定的参考价值。

# Powershell Patterns I use

## Function Outline
```Powershell
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
```Powershell
<#
    .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

```powershell
 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

```powershell
  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

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

## Splatting

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

}

New-FunnyFunction @vars -verbose
```

## Void it

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

```powershell
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

```powershell
$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.
```powershell
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

```

以上是关于markdown PowerShell #powershell中的Powershell最佳实践(对我而言)的主要内容,如果未能解决你的问题,请参考以下文章

markdown Powershell基础知识

markdown Windows Powershell

markdown windows - powershell - 命令参考

markdown 通过PowerShell运行Windows Update

markdown 通过PowerShell运行Windows Update

markdown Windows Powershell提示的快速设置