Skip to content

Commit

Permalink
code highlighting and cert validation skip
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyPhipps committed Nov 13, 2024
1 parent 9058be1 commit 1907dcb
Showing 1 changed file with 43 additions and 25 deletions.
68 changes: 43 additions & 25 deletions Products/powershell.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Ways to Stop a Script or Contents

Store Output Streams to Variable
- Add $ to InfoFar and ErrorVar if you want the Information and Errors to NOT be sent down the pipeline.
```
```ps
$InfoVar
$ErrorVar
$FullOutput
Expand All @@ -24,7 +24,7 @@ if ($ErrorsVar.Count -ne 0) {

Timeout a Command
Use this to effectively assign a timeout to any command or command block.
```
```ps
Start-Job {
hostname
} | Wait-Job -Timeout 3 | Receive-Job
Expand All @@ -33,24 +33,24 @@ Start-Job {

# Arrays
Add a property to each item in arrray
```
```ps
foreach ($Item in $Array) {
$Item | Add-Member -MemberType NoteProperty -Name "ANewProperty" -Value $AVariable
}
```

Deduplicate An Array of Objects By Selecting Only the Latest Date
```
```ps
$UniqueList = $completelist | Group-Object -Property ID | ForEach-Object{$_.Group | Sort-Object -Property StartTime -Descending | Select-Object -First 1}
```

Merge Two Arrays
```
```ps
$MergedArray = $Array1 + $Array2
```

Group On Multiple Fields, then Restore Those Field Values
```
```ps
$GroupedStuff = $Things | Group-Object Host,DateScanned,UserName
ForEach ($Result in $GroupedStuff) {
$fields = $Result.name -split ', '
Expand All @@ -61,21 +61,21 @@ ForEach ($Result in $GroupedStuff) {
```

Compare two arrays to determine if equal
```
```ps
[Collections.Generic.SortedSet[String]]::CreateSetComparer().Equals($FirstArray,$SecondArray)
```

# Hashtables
Sort A Hashtable by Key Name
```
```ps
$myHashtable.GetEnumerator() | Sort-Object Key
```



# Files and Directories
Remove Empty Directories Recursively
```
```ps
Get-ChildItem $Destination -Directory -Recurse |
Foreach-Object { $_.FullName} |
Sort-Object -Descending |
Expand All @@ -84,19 +84,19 @@ Get-ChildItem $Destination -Directory -Recurse |
```

Force Get-Childitem to NOT pull Windows directory or Program Files directories.
```
```ps
Get-ChildItem c:\ -Depth 0 -Directory | Where-Object {$_.Name -notmatch "windows|Program Files|Program Files \(x86\)"} | Get-Childitem -Recurse
```

Merge CSV files
```
```ps
Get-ChildItem *.csv | Select-Object name -ExpandProperty name | Import-Csv | export-csv -NoTypeInformation merged.csv
```

# Script Meta
## Parameters
Validate the provided path
```
```ps
...
[Parameter()]
[ValidateScript({Test-Path $_})]
Expand All @@ -105,7 +105,7 @@ Validate the provided path
```

A nicer, fuller version
```
```ps
...
[ValidateScript({
try {
Expand All @@ -124,7 +124,7 @@ A nicer, fuller version


Make a parameter mandatory
```
```ps
...
[Parameter(mandatory=$true)]
[ValidateScript({Test-Path $_})]
Expand All @@ -135,7 +135,7 @@ Make a parameter mandatory

# Misc
Convert .json file to PowerShell objects
```
```ps
$file = "file.json"
$json = Get-Content $file | ConvertFrom-Json
$json
Expand All @@ -145,28 +145,28 @@ $records
```

Run an encoded command
```
```ps
$Command = 'Get-Service BITS'
$Encoded = [convert]::ToBase64String([System.Text.encoding]::Unicode.GetBytes($command))
powershell.exe -encoded $Encoded
```

Convert plain text to base64
```
```ps
$Text = 'This is a secret and should be hidden'
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)
$EncodedText = [Convert]::ToBase64String($Bytes)
$EncodedText
```

Convert base64 to plain text
```
```ps
$base64_string = "VABoAGkAcwAgAGkAcwAgAGEAIABzAGUAYwByAGUAdAAgAGEAbgBkACAAcwBoAG8AdQBsAGQAIABiAGUAIABoAGkAZABkAGUAbgA="
[System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String($base64_string))
```

Fix $ScriptRoot so its the same whether in ISE or regular Powershell console.
```
```ps
if ($psISE) {
$ScriptRoot = Split-Path -Path $psISE.CurrentFile.FullPath -Parent
} else {
Expand All @@ -177,14 +177,14 @@ if ($psISE) {

Opens Powershell ISE as administrator under alternate credentials.
*Window will show Administrator:, but with alternate administrative credentials. Often necessary where least privilege is desired, like logging in as user, then elevating to an administrator with Runas.*
```
```ps
$Account = "domain\service_account"
$Credential = Get-Credential $Account
Start-Process $PsHome\powershell.exe -Credential $Credential -ArgumentList "-Command Start-Process $PSHOME\powershell_ise.exe -Verb Runas" -Wait
```

Grant access to specific files in a privileged user profile relatively safely.
```
```ps
$path = "C:\Users\Administrator\Desktop"
$path = "C:\Users\Administrator\Downloads"
$path = "C:\Users\Administrator\Documents"
Expand All @@ -200,7 +200,7 @@ Try Catch Errors Template
- When debugging, you can use ```$Error[-1] | Select-Object *``` to see the details of the last error thrown.
- Use the value of ```$Error[0].Exception.GetType().FullName``` in the catch square brackets [] as shown below.
- Use the value of ```$Error[0].Exception.Message``` to match on the first line of the error presented.
```
```ps
try {
yourcode
}
Expand All @@ -223,7 +223,7 @@ catch { # catch all remaining errors and provide info to capture them specifical


Assign a Variable via Switch
```
```ps
$day = 3
$result = switch ( $day )
Expand All @@ -242,7 +242,7 @@ $result.GetType()
```

Assign a Variable an Array or String via Switch
```
```ps
$day = "Friday"
$result = switch ( $day )
Expand All @@ -261,7 +261,7 @@ $result.GetType()


Add a Hashtable as Properties to an Existing Object
```
```ps
# Create a hashtable of properties
$newProperties = @{
City = "New York"
Expand All @@ -272,4 +272,22 @@ $newProperties = @{
foreach ($key in $newProperties.Keys) {
$myObject | Add-Member -MemberType NoteProperty -Name $key -Value $newProperties[$key]
}
```


Skip certificate validation checks (use only for known-good self-signed certs)
```ps
# Trust all certificates (use if self-signed cert is being used
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
```

0 comments on commit 1907dcb

Please sign in to comment.