четверг, 5 декабря 2019 г.

POWERSHELL BASICS v3 FUNCTIONS/XML/JSON

ADVANCED  FUNCTIONS


Function Now-Advanced {
[CmdLetBinding()]Param($MyNumber)
[Parameter(Mandatory=$True, ValueFromPipeline=$True, HelpMessage="Enter the first two letters of your last name and 4 name digit employee number")]
[ValidatePattern("[a-z][a-z][0-9][0-9][0-9][0-9])]

$EmployeeID

# if dont set up process, function by default will show only the last record of file
Process{
Write-Host $EmployeeID
}
}

> Import-Csv C:\tmp\Employee.csv | Now-Advanced

Function with Help Information

Function Gather-Info {
<#
.SYNOPSIS
 Collect Details about a lot of Computers
.DESCRIPTION
 This function collects the computer name, operating system, IP addresses and the current date (for historical data in DHCP environments).
.PARAMETER Name
 Specifies the computer name for which the information is collected
.EXAMPLE
 Gather-Info -Name localhost
#>


[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$True)]
  [String[]]
  $Name
  )


# Collect IP Address(es) and split the single string into an array of IP’s
  $IP4Address=(Invoke-Command -ComputerName $Name -ScriptBlock{(Get-NetIPAddress).IPAddress})
  [array]$IPArray=$IP4Address.split(" ")

#Collect additional information about the computer from the input parameter 
  $PCName=$Name
  $Make=(Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $Name).Manufacturer
  $OS=(Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $Name).Caption
  $Today=(Get-Date -Format MM/dd/yyyy)


  $ComputerInformation=@{ComputerName=$PCName;
                         DateOfIP="$Today";
                         IPAddress=$IPAddie;
                         OperatingSystem=$OS;
                         Manufacturer="$Make";
                         WaranteeExpiration=[DateTime]"06/30/2020"}

#Return the collected information to the pipeline and as a hash table variable
  return $ComputerInformation

  }

(Get-ADComputer -Filter *).Name | Gather-Info | Out-File C:\ScriptOutput\ComputerInventory.txt -Append


 -WHATIF & -CONFIRM

#Attribute SupportsShouldProcess will add posibility to run -WhatIf flag & Confirm Option
Function Stop-Everything{
[CmdletBinding(SupportsShouldProcess)]Param()
  Get-Service | Stop-Service
}

>Stop-Everything -WhatIf
> Stop-Everything -Confirm

Available Validation Rules
AllowNull()
AllowEmpty()
ValidateCount()
ValidateRange()
ValidatePattern()

.NET IN POWERSHELL

.Net API
If you dont know what class called, just search : .net class what you looking for
Search Example: .net class sounds
> [system.media.SystemSounds]::Beep.Play()

Create Classes

class Wallet
  {

# Define properties of the Wallet class
  [string] $NameOnID
  [string] $CreditCard1Bank
  [float] $CreditCardBalance
  [string] $DebitCardBank
  [float] $DebitCardAvailFunds
  [int] $CashOnHand

# Define methods of the wallet class  
  [void] SpendCash([float]$Spent) {
      $this.CashOnHand -= $Spent
    }
  [void] ChargeIt([float]$Charged) {
    $this.CreditCardBalance += $Charged
    }
  [void]ChargeAccount([float]$CardSpend) {
    $this.DebitCardAvailFunds -= $CardSpend
    }
  }

$ScottWallet = [Wallet]::new()

$ScottWallet.NameOnID = 'Scott Miles Burrell'
$ScottWallet.CreditCard1Bank = '1st Bank of Money'
$ScottWallet.CreditCardBalance = 1461.03
$ScottWallet.DebitCardBank = '1st Bank of Money'
$ScottWallet.DebitCardAvailFunds = 2104.84
$ScottWallet.CashOnHand = 145

$ScottWallet.SpendCash(45)

$ScottWallet.ChargeAccount(216.92)


REST API REQUESTS

# Using web request and extra parameters
Invoke-WebRequest -Method Get -URI http://trainingxyz.com/api/posts/all | Select-Object -ExpandProperty Content | ConvertFrom-Json | Format-Table

# Using rest method (simpler)
Invoke-RestMethod -Method Get -URI http://trainingxyz.com/api/posts/all | Format-Table


CONTROLLER SCRIPT

# import modules that contain on-prem user and mailbox functions
Import-Module LandonHotelAD
Import-Module LHExchange

# gather information
$UserFirstName = Read-Host -Prompt "Enter the User's first name"
$UserLastName = Read-Host -Prompt "Enter the User's last name"
$Username = Read-Host -Prompt "Enter the username"
$JobTitle = Read-Host -Prompt "Enter the job title"
$EmpID = Read-Host -Prompt "Enter the employee ID#"

# create a basic user account with all company requirements
New-LHADUser -Fname $UserFirstName -Lname $UserLastName -UserName $UserName -Password $Password -Job $JobTitle -ID $EmpID

# create an exchange with all company requirements
Enable-LHMailbox -User $Username

Write-Host "The user account and mailbox were successfully created."



EXAMPLE: GET EXPIRED PASSWORDS

Function Get-ExpiringPasswords
  { 
  Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties "DisplayName","msDS-UserPasswordExpiryTimeComputed" |
  
  Where {
    $Difference = New-Timespan (Get-Date) ([datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed"))
    $Difference.Days -le 45 -and $Difference.Days -ge 0
    } |

  Select-Object -Property "DisplayName",@{Name="Password Expires";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
  }

$Header = @"
<style>
TABLE {border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse;}
TH {border-width: 1px; padding: 3px; border-style: solid; border-color: black; background-color: #6495ED;}
TD {border-width: 1px; padding: 3px; border-style: solid; border-color: black;}
</style>
"@

Get-ExpiringPasswords |
ConvertTo-Html -Head $Header | 
Out-File C:\ScriptOutput\Output.html

XML

XML Example

<?xml version="1.0"?><roster>  <employee id="010101">    <name>Robertson, Robert</name>    <jobdescription>VP of Sales</jobdescription>    <date_of_hire>09/16/1998</date_of_hire>    <email_address>rrobertson@landonhotel.com</email_address>    <pe_3month>12/21/1998 Exceeds</pe_3month>    <pe_1year>09/17/1999 Exceeds</pe_1year>    <pe_5year>09/21/2003 Exceeds</pe_5year>    <pe_10year>09/19/2008 Meets</pe_10year>    <pe_15year>09/16/2013 Exceeds</pe_15year>    <pe_20year>09/17/2018 Exceeds</pe_20year>  </employee>  <employee id="020202">    <name>Jansdotter, Janice</name>    <jobdescription>VP of Marketing</jobdescription>    <date_of_hire>05/01/2002</date_of_hire>    <email_address>jjansdotter@landonhotel.com</email_address>    <pe_3month>08/02/2002 Exceeds</pe_3month>    <pe_1year>05/02/2003 Meets</pe_1year>    <pe_5year>05/1/2007 Meets</pe_5year>    <pe_10year>05/4/2012 Exceeds</pe_10year>    <pe_15year>05/5/2017 Exceeds</pe_15year>  </employee>  <employee id="030303">    <name>Chase, Montgomery</name>    <jobdescription>Director of Regulatory Compliance</jobdescription>    <date_of_hire>10/02/2017</date_of_hire>    <email_address>cmontgomery@landonhotel.com</email_address>    <pe_3month>01/02/2018 Exceeds</pe_3month>    <pe_1year>10/02/2018 Meets</pe_1year>  </employee>  <employee id="040404">    <name>White, Cindy</name>    <jobdescription>Director of IT</jobdescription>    <date_of_hire>05/11/2010</date_of_hire>    <email_address>cwhite@landonhotel.com</email_address>    <pe_3month>08/11/2010 Meets</pe_3month>    <pe_1year>05/11/2011 Meets</pe_1year>    <pe_5year>05/15/2015 Exceeds</pe_5year>  </employee>
  <employee id="111111">    <name>Karter, Raymond</name>    <jobdescription>Restaurant Waiter</jobdescription>    <date_of_hire>05/22/2017</date_of_hire>    <email_address>rkarter@landonhotel.com</email_address>    <pe_3month>08/24/2017 Exeeds</pe_3month>    <pe_1year>05/26/2018 Exeeds</pe_1year>  </employee>
</roster>

Select Data

$XMLPath = 'C:\ScriptOutput\roster.xml'
$EmployeeRoster = [xml](Get-Content $XMLPath) 

$EmployeeRoster.roster.employee | Format-Table

# *.SelectNodes is a method of xml style variables, //name is xpath syntax
$EmployeeRoster.SelectNodes("//name")

$EmployeeRoster.SelectNodes("//pe_3month")

$EmployeeRoster.SelectSingleNode("//employee[4]")      

Update existing element

$XMLPath = 'C:\ScriptOutput\roster.xml'
$EmployeeRoster = [xml](Get-Content $XMLPath) 

$EmployeeRoster.roster.employee | Format-Table

$EmployeeRoster.SelectSingleNode("//employee[3]")

# Place the workspace in a variable
$Bernie = $EmployeeRoster.roster.employee[2]

# Update an existing element
$Bernie.jobdescription = 'Landscaping'

# Save changes
$EmployeeRoster.Save($XMLPath)

Add element

$XMLPath = 'C:\ScriptOutput\roster.xml'
$EmployeeRoster = [xml](Get-Content $XMLPath) 

$EmployeeRoster.roster.employee | Format-Table

$EmployeeRoster.SelectSingleNode("//employee[8]")
$Bernie = $EmployeeRoster.roster.employee[7]

#Add an element
$Bernie.AppendChild($EmployeeRoster.CreateElement("pe_1Year"))
$Bernie.pe_1Year = "7/18/2018 Exceeds"

#Add a node, or employee
$NewHire = $Bernie.Clone()
$NewHire.id = '191919'
$NewHire.name = 'Blair, Jovanny'
$NewHire.jobdescription = 'Front Desk Supervisor'
$NewHire.date_of_hire = '8/20/2018'
$NewHire.email_address = 'jblair@landonhotel.com'
$EmployeeRoster.roster.AppendChild($NewHire)


#Save changes
$EmployeeRoster.Save($XMLPath)

JSON (rest api)

@"
 [ 
  {
    "FirstName": "Robert",
    "LastName": "Robertson",
    "EmployeeID": 010101,
    "DateOfHire": {
      "Month": "September",
      "Day": 16,
      "Year": 1998
      },
    "SkillSets": [
      "Sales",
      "Social Media Marketing",
      "Public Speaking",
      "Clarinet"
      ],
    "Management": true,
    "LastUpdate": "\/Date(1540112320855)\/"
  },
  {
    "FirstName": "Elena",
    "LastName": "Warren",
    "EmployeeID": 070707,
    "DateOfHire": {
      "Month": "August",
      "Day": 11,
      "Year": 2011
      },
    "SkillSets": [
      "Customer Service",
      "Training",
      "Party Planning",
      "Bonzai Trees"
      ],
    "Management": false,
    "LastUpdate": "\/Date(1540002320855)\/"
  }
 ]
"@ | ConvertFrom-Json | Format-Table



Sources:

Комментариев нет: