Powershell usage

From Help
Jump to: navigation, search


Format: Brief Scope

Return to Main Page

Basic commands

  • Changing directories: use the set-location command to change locations
PS C:\ps> set-location c:\
PS C:\>
  • run another script: use .\$SCRIPT
./myscript.ps1
  • Aliases: making an alias, useful for often-used commands like write-host: Set Alias $name $command
set-alias wh write-host
  • To find out what PowerShell version your running:
$PSVersionTable.PSVersion

will return something like:

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

Return to Top

Updating Powershell

Powershell 5.1 is avalible here:

Return to Top

Out-String

  • To get your output to show the entirety of it's return value:
Get-Alias -Definition Invoke-* | Format-Table -Property * -AutoSize | Out-String -Width 4096
  • This will make your output table width at a max of 4096

Return to Top

importing from text

import-csv “c:tempcomputers.csv”
import-csv “c:tempcomputers.csv”| where-object {$_.owner -eq "russellsmith"}
import-csv “c:tempcomputers.csv” –header Name, IP, Location, User –delimiter :
$computers = “c:tempcomputers.txt” $output = (import-csv $computers).length write-host $output
$computers = “c:tempcomputers.txt” $output = (import-csv $computers)[3] write-host $output
$computers = import-csv “C:\PS\list.cvs" –header NAME, IP, OS –delimiter :
ForEach ($computer in $computers)
	{
		$computername = $($computer.NAME)
		$ipaddress = $($computer.IP)
		$os = $($computer.OS)
		Write-host $computername $ipaddress $os
	}

Return to Top

Out-file

  • [-FilePath] <String>
  • [[-Encoding] <String>]
    • Unicode - is the default.
    • UTF - old format no longer really used.
    • UTF8 - also allows for Cyrillic, Armenia, Hebrew, Arabic, Syriac, Alatin, Runic, etc
    • UTF32 - fixed-length encoding that uses exactly 32 bits. Four times the size of UTF-8
    • ASCII - straight ASCII, 128 characters
    • BigEndianUnicode - stores the most significant byte in the smallest address
    • Default
    • OEM - uses the current original equipment manufacturer code page identifier for the operating system.
  • [-Append]
    • Add the data to the end of existing entries
  • [-Force]
    • Allows the cmdlet to overwrite an existing read-only file.
  • [-InputObject <PSObject>]
    • Specifies the objects to be written to the file.
  • [-NoClobber]
    • After the first use, causes PowerShell to generate an error message and thus protects the original file from being replaced.
  • [-Width <Int32>]
    • Specifies the number of characters in each line of output. Any additional characters are truncated, not wrapped. Default is 80.
  • [-Confirm]
    • Prompts you for confirmation before running the cmdlet.
  • [-WhatIf]
    • Shows what would happen if the cmdlet runs. The cmdlet is not run.
  • [<CommonParameters>]

Examples

Out-File C:\aliases.txt
$a = get-process
out-file -filepath C:\Test1\process.txt -inputobject $a -encoding ASCII -width 50

Return to Top

HTML

  • To convert to HTML:
    • ConvertTo-HTML
  • To add in formating:
  • -head
  • -body
<ConvertTo-HTML -head $a
<ConvertTo-HTML -body "<H2>Level 2 Headline</H2>"
  • change these CSS styles to whatever you want:
$a = "<style>"
$a = $a + "BODY{background-color:peachpuff;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
$a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
$a = $a + "</style>"
  • then use a script like this:
Get-Service | Select-Object Status, Name, DisplayName | ConvertTo-HTML -head $a -body "<H2>Service Information</H2>" | Out-File C:\Scripts\Test.htm
  • Invoke-Expression: you can use this to "invoke" a file
Invoke-Expression C:\Scripts\Test.htm
  • This will open up Test.htm out of C:\Scripts\

Return to Top

Selecting

  • To get only specific objects:
select VALUE, VALUE
    • In powerShell 1.0 or 2.0, you must use select-object instead.
  • if your return has {} around it, use expand:
select -Expand Lease

Filter specific values

Where-Object {$_.OBJECT -COMPARISON 'value'}
  • you can also use:
where OBJECT -COMPARISON 'value'

comparisons available

    • -eq (equal to)
    • -ne (not equal to)
    • -lt (less than)
    • -le (less than or equal to)
    • -gt (greater than)
    • -ge (greater than or equal to)
    • -like (like—a wildcard comparison)
    • -notlike (not like—a wildcard comparison)
    • -contains (contains the specified value)
    • -notcontains (doesn't contain the specified value)
  • join multiple Where-Objects with: (must use both { and ( then ) } on first and last expression respectively)
    • -and (The script block evaluates to True if the expressions on both sides of the logical operator evaluate to True.)
    • -or (The script block evaluates to True when one of the expressions on either side of the logical operator evaluates to True.)
    • -xor (The script block evaluates to True when one of the expressions on either side of the logical operator evaluates to True and the other expression evaluates to False.)
    • -not or ! (Negates, or reverses, the script element that follows it.)

Example

Where-Object {$_.Name -eq 'Lease'}
Where Name -eq 'Lease'
Where-Object {($_.Router -eq '10.0.0.0') -and ($_.Name -eq 'DNS Domain Name')}
  • PAY ATTENTION ON ABOVE: Where {(condition) -and (condition)}
  • To find an empty or blank value:
Where Name -eq $null
  • To find an entry that is NOT null or empty:
Where Name -ne $null
  • FULL EXAMPLE:
Get-DhcpServerv4OptionValue -ComputerName realm.tpfnd.cat -scopeid 10.0.0.0 | Where-Object {$_.Name -eq 'DNS Servers'} | select -Expand value

will return:

10.0.0.59
8.8.8.8
172.13.47.109

References

Dates and times

  • To display a date:
$a = Get-Date
"Date: " + $a.ToShortDateString()
  • To display the time:
$a = Get-Date
"Time: " + $a.ToShortTimeString()
  • To display the what day of the week it is:
$a = Get-Date
"Day of Week: " + $a.DayOfWeek
  • To display the what day of the year it is:
$a = Get-Date
"Day of Year: " + $a.DayOfYear
  • To determine if it's currently daylight Savings Time:
$a = Get-Date
"Daylight Saving Time: " + $a.IsDaylightSavingTime()
  • To add / subtract new time units:
$a = Get-Date
$a.AddDays(90)
$a.AddDays(-90)
    • Avalible units:
      • AddDays
      • AddHours
      • AddMilliseconds
      • AddMinutes
      • AddMonths
      • AddSeconds
      • AddTicks
      • AddYears

Examples

Get-Alias -Definition | Format-Table -Property * -AutoSize | Out-String -Width 4096 | Out-File C:\aliases.txt
Get-Alias -Definition | Format-Table -Property * -AutoSize | Out-String -Width 4096 | ConvertTo-HTML | Out-File C:\aliases.htm
Get-DhcpServerv4OptionValue -ComputerName realm.tpfnd.cat -scopeid 10.0.0.0 | select Name, OptionID, value

returns:

Name                                                                   OptionID value
----                                                                   -------- -----
Lease                                                                        51 {691200}
Router                                                                        3 {10.0.0.1}
DNS Domain Name                                                              15 {tpfnd.cat}
DNS Servers                                                                   6 {10.0.0.59, 8.8.8.8, 172.13.47.109}
Boot Server Host Name                                                        66 {10.0.0.59}
Cisco IPT                                                                   150 {10.0.0.59}

Return to Top

References

Return to Top