Skip to content

Instantly share code, notes, and snippets.

@mtboren
mtboren / snippets_GetPDFContentsAndPipeThem.ps1
Last active March 14, 2024 20:49
Examples of getting PDF text contents for subsequent use
## use PowerShell and the PSWritePDF module
Install-Module -Name PSWritePDF -Scope CurrentUser
Convert-PDFToText -FilePath $strSomePdf | fabric --pattern analyze_threat_report
## or, use Python, pypdf module, and some local PDF; these Python examples can be from most any shell (including PS)
pip install pypdf --user ## however you like to install Python modules
python -c 'strSomePdf = "/tmp/2024-cyber-threat-report.pdf"; from pypdf import PdfReader; from sys import stdout; [stdout.writelines(page.extract_text()) for page in (PdfReader(strSomePdf)).pages]' | fabric --pattern analyze_threat_report
## or, use Python, pypdf module, and some PDF from URL
python -c 'strSomePdfUri = "https://www.sonicwall.com/medialibrary/en/white-paper/2024-cyber-threat-report.pdf"; from urllib.request import urlopen; from pypdf import PdfReader; import io; from sys import stdout; reader = PdfReader(io.BytesIO(urlopen(strSomePdfUri).read())); [stdout.writelines(page.extract_text()) for page in reader.pages]' | fabric --pattern an
@mtboren
mtboren / snippets_createAndRegisterScheduledTask.ps1
Last active April 8, 2022 13:43
Register Scheduled Task to use PowerShell 7 to run ps1
## some things for making and registering a scheduled task via PowerShell, with the task Action running via PowerShell 7 at run time
## creds for the new scheduled task
$credForSchedTask = Get-Credential coolguy@domain.com
## params for making a new scheduled task object in the PowerShell session
$hshParamForNewScheduledTask = @{
Action = New-ScheduledTaskAction -Execute "C:\Program Files\PowerShell\7\pwsh.exe" -Argument "-File E:\scripts\scheduled\Invoke-MyCoolThing.ps1" -WorkingDirectory "C:\temp"
Description = "My important task to do all the things"
## additional settings
@mtboren
mtboren / snippets_PipelineAndForEach-Object_vs_foreach.ps1
Last active May 11, 2021 21:14
Example of pipeline difference between ForEach-Object cmdlet and foreach() statement in PowerShell
<#
While we can iterate over objects with both ForEach-Object and the foreach() statement, only ForEach-Object emits objects
to the pipeline. The foreach() statement does _not_, which prevents us from doing any further cool things with objects
that might be created in the foreach() statement's scriptblock
Some examples:
#>
## no objects returned to pipeline, so we are done with the interesting things immediately
PS C:\> foreach ($intI in 1..10) {New-Object -Type PSObject -Property @{SomeCoolProperty = $intI}} | Measure-Object -Sum -Property SomeCoolProperty
@mtboren
mtboren / snippets_RenameGitHubRepository.ps1
Last active January 24, 2020 15:08
Rename a GitHub repository using the PowerShellForGitHub PowerShell module
## some PowerShell snippets to illustrating the forking- and subsequent renaming of a GitHub repository
# uses Invoke-GHRestMethod for the rename operation, as there is not yet a higher level cmdlet for dealing with repo renames
## import the module, of course
Import-Module PowerShellForGitHub
## fork some source repo; forks under current GitHub user configured via Set-GitHubAuthentication
New-GitHubRepositoryFork -Uri https://github.com/aws-quickstart/quickstart-dotnet-serverless-cicd -OutVariable oNewRepo
## rename the forked repo in user's GH account, prefixing "fork_" so the world clearly knows that its was forked from elsewhere just by glancing at name
@mtboren
mtboren / SomeDaterConsumptionManip.ps1
Created September 5, 2019 01:08
Some Examples of Data Manipulation and Password Generation
## import the ImportExcel PowerShell module, for dealing with an Excel file from PowerShell (install first if not already there)
Find-Module ImportExcel | Install-Module
Import-Module ImportExcel
## for reals: export, per user, a new XLSX file with just their info in it
Import-Excel C:\temp\XlsxAndAutomation\userinfo.xlsx | Foreach-Object {Export-Excel -Path "C:\temp\XlsxAndAutomation\daterForUsers\$($_.user).xlsx" -InputObject $_ -Password ($_.xlsxFilePassword) -AutoSize}
## can we open one? What's in it?
Invoke-Item C:\temp\XlsxAndAutomation\daterForUsers\user19118.xlsx
@mtboren
mtboren / SnippetsAndNugglets.ps1
Created August 8, 2019 23:19
General snippets and nugglets for various things
## various things that I find useful on ocassion
## For RSAT types of things already available on Windows 10 at/newer than October 2018 Update, "RSAT is included as a set of "Features on Demand" right from Windows 10". One does not download the RSAT package from microsoft.com, just add the Windows capability
## see following for more info: https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/features-on-demand-non-language-fod#remote-server-administration-tools-rsat
## get the available capabilities
Get-WindowsCapability -Online
## get the RSAT ActiveDirectory capability
Get-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS*
Mars Rovers:
https://api.nasa.gov/api.html#MarsPhotos, https://github.com/chrisccerami/mars-photo-api
(irm "https://api.nasa.gov/mars-photos/api/v1/rovers?api_key=DEMO_KEY").rovers
- what are the rovers, when were they launched, when did they land, how long was their journey, how many pictures have they taken?
https://images.nasa.gov/docs/images.nasa.gov_api_docs.pdf
Apollo 11 moon landing pictures
irm "https://images-api.nasa.gov/search?q=apollo%2011&description=moon%20landing&media_type=image&year_end=1970"
@mtboren
mtboren / ExampleSnippetForGettingADUserInfoWithPasswordExpiration.ps1
Last active May 17, 2019 14:56
Get AD User info, to include PasswordExpiration datetime
## example of getting, for one user, some choice properties, to include PasswordExpiration datetime (using the ActiveDirectory PowerShell module from Microsoft)
## where there might be some AD property that gives that password expiration info in proper datetime format already, my quick search found no such property; so, we can use the given .NET method to convert from filetime to a proper datetime -- yay!
#Requires ActiveDirectory
Get-ADUser rickyscroter -Properties *, msDS-UserPasswordExpiryTimeComputed | Select-Object -Property displayname, *passw*, @{n="PasswordExpiration"; e={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
## credit for reporting of said somewhat cryptic AD property 'msDS-UserPasswordExpiryTimeComputed': https://activedirectorypro.com/how-to-get-ad-users-password-expiration-date/
@mtboren
mtboren / ExampleSnippetsForGettingAPITypeDefs.ps1
Created March 3, 2017 14:43
Getting EMC Unity array API types' definitions from API itself
## URI is to just get the "types" info
$tmpUri = "https://someunity.dom.com/api/types"
## this example uses the websession and headers from already having established connection to Unity API (as perfomed by Connect-Unity cmdlet from "Unity-PowerShell" PS module)
$oWebResponse = Invoke-WebRequest -Uri $tmpURI -ContentType "application/json" -Websession $Session.Websession -Headers $session.headers -Method GET
## the ".entries" property has the collection of types data
## there are about 422 objects returned in ".entries" property on this 600F (about half of which are Enum types)
($oWebResponse.content | ConvertFrom-Json).entries
# @base updated links
# ----- ------- -----
@mtboren
mtboren / New-vSphereLab.ps1
Last active February 15, 2017 22:37
Use parameters for PowerShell, and accept them from pipeline by property name, for ease of script consumption by user (including getting help on the script -- no need to open the script in an editor -- use Get-Help!). The .ps1 file shows an example of what a parameterized-version of @lamw's vSphere-lab-deployment PowerShell script might look lik…
<# .Description
Code to do super awesome things, and in a hurry!
This is an example snippet of parameterizing the .PS1 file at https://github.com/lamw/vghetto-vsphere-automated-lab-deployment/blob/master/vsphere-6.5-vghetto-standard-lab-deployment.ps1
And, these are just light example of some of the über-powerful Validation/flexibility available for parameters. Soo much more can be done to perform the validation up front
.Example
(Get-Content -Raw C:\Temp\myParamsForNewVsphereLab.json) | ConvertFrom-Json | New-vSphereLab.ps1
Take all parameters specified in the JSON file and use them in calling New-vSphereLab.ps1
This takes the JSON, converts it to an object with properties and values, and since the property names match the parameter names and the parameters take value from pipeline by property name, it's a match! The parameter is specified!
.Example
New-vSphereLab.ps1 -VMCluster someDifferentCluster