INDEX
########################################################### 2024-01-15 17:42 ########################################################### Powershell Engineer... Learn Powershell in less than 2 hours https://www.youtube.com/watch?v=ZOoCaWyifmI Powershell is a command line and scripting language built on .NET common language runtime It can do everything command line can do except run batch files # R-CLICK, Properties - can chane font settings etc. $PSVersionTable.PSVersion # Get the powershell version ping google.com # Ping websites, as in CLI cd C:\Scripts # Move directories clear # Clear screen # Need execution policy to be set correctly to run anything Get-ExecutionPolicy # Must be "RemoteSigned" - default to "Restricted" Set-ExecutionPolicy Restricted # Can change mode (only possible in admin mode) Open Powershell ISE - a powershell scripting program Commandlets (cmdlets) are "Verb-Noun" formatted (e.g. "Write-Host") # Powershell saves files as .ps1 - save in C:\Scripts - comments also use # Write-Host "Hello World!" # Just prints to console Write-Host "Hello World!" -NoNewLine # Does not end in \n by default Get-Command -CommandTyper Cmdlet # Lists all possible cmdlets Get-Help # Lists all help articles in command shell Get-Help Write-Host -Full # Gives syntax and info for a given command Can use pipes in powershell the same as bash "This is some text" | Out-File outputfile.txt # Saves that text to the file cat outputfile.txt # Shows contents is as expected $FavCharacter = "John" # Set variables with $Item $FavCharacter # Run by iteself to get value $FavCharacter | Out-File outputfile.txt # Output variable directly to a file There are other data types like strings, integers and booleans $FavCharacter.GetType() # Shows it is a string $FavCharacter = 5 # Converts it to a number - no fixed types $FavCharacter = $true # Set to boolean 3+5 # Can do arithmetic inline Everything in powershell is an object - has properties and classification $FavCharacter.Length # Gives length of a string $FavCharacter | Select-Object -Property * # Get all properties of this object Get-Member -InputObject $FavCharacter # Gets all the methods for an object $MyArray = @('Name1', 'Person 2', 'Test') # Create a "System.Array" object with 3 elements $MyArray # Prints out plain list of elements $MyArray[0] # Get first item - exactly as in Python it returns a string object $MyArray += "New item" # Extend array # Can make "Hashtables" (dictionaries) - use {} not () $MyHashtable = @{key1 = "item1"; "key2" = "item2"} # Can use quotes or not for keys $MyHashtable # Prints out a table of key-value pairs $MyHashtable."key2" # Get an element - or use $MyHashtable["key2"] $MyHashtable.Add("key3", "item3") # Similarly .Set_Item to change and .Remove to delete Can also get user input with Read-Host and do standard process controls $FavSystem = Read-Host -Prompt "What is your favourite Nintendo system? " $FavSystem # Outputs the user input value If ($FavSystem -eq 2) { Write-Host "Your option is NES" } # Test variables If (...) { ... } Else { ... } # Can similarly use Elseif If ($FavSystem -qt 3 -or $FavSystem -le 2) { ... } # Do combined checks Switch($FavSystem) { "Someword" { Write-Host "Wow"; break } # Has fall-through unless you break } $People = @("Person1", "Person2", "Person3", "Person4") For($counter=0; $counter -le 3; $counter++) { Write-Host "Item:" $People[$counter] } For($counter=0; $counter -le ($People.Length-1); $counter++) { ... } Foreach($person in $People) { ... } $counter = 0; While($counter -lt 6) { Write-Host $counter++ } # Similarly "Do {} While ()" Now you can define functions and group commands together function Test-SpaceX { param( $PingCount ) Test-Connection spacex.com -Count $PingCount # Effectively a table/object version of ping } Test-SpaceX -PingCount 10 # Call a function and pass an argument # Can define a more complex version function Test-SpaceX { [CmdletBiding()] # Turns this into an advanced function param( [Parameter(Mandatory)] # Will prompt user for the value if not given [int32]$PingCount # Set typing of variable ) Test-Connection spacex.com -Count $PingCount # Effectively a table/object version of ping } Can do error handling with exceptions Throw "This is a runtime error" # Throws a basic fatal error Write-Error -Message "This is a runtime error" -ErrorAction Stop # Same as "throw" # Try to run a function, catch the error, print on error and print output try{ ... -ErrorAction Stop } catch { Write-Output "Launch problem" Write-Output $_ } Can use New-Item to make generic files, folders etc. New-Item -path C:\Scripts\test.txt -type "file" -value "This is the contents" # New file New-Item -path C:\Scripts -name "newfolder" -type directory Copy-Item -path ".\test.txt" -destination ".\newfolder" # Same as Move-Item Rename-Item -path ".\test.txt" -newname ".\test2.txt" Remove-Item ".\test2.txt" # Similarly Test-Path returns a boolean Active directory is a server manager - useful to interact with powershell Use backticks (`) to do newlines similar to \ in shell Import-Module ActiveDirectory # Load all modules for running AD commands Get-ADUser frodo # Gets a user and all their basic info $user = Get-ADUser frodo; $user.Enabled # Set user info to a variable - pull specific value Set-ADUser -Identity frodo -SurName Tyler # Change properties of a user Add-ADGroupMember -Identity mygroup -Members frodo # Similarly Remove-ADGroupMember New-ADUser -Name "John Smith" -GivenName "John" -Surname "Smith" ` -SamAccountName "jsmith" -UserPrincipalName "jsmith@email.com" ` -Path "OU=Administration,OU=Staff,DC=org" \ -AccountPassword(ConverTo-SecureString "changeme" -AsPlainText -force) -Enabled $true Set-ADAccountPassword -Identity jsmith -Reset ` -NewPassword(ConvertTo-SecureString -AsPlainText "newchangeme" -force)
########################################################### 2024-01-16 13:15 ########################################################### Powershell Engineer... Learn Powershell Automation https://www.youtube.com/watch?v=ssS3dd6oQTU You can make a scheduled task - set for a specific time $trigger = New-ScheduleTaskTrigger -At 3pm -Daily $action = New-ScheduledTaskAction -Execute "powershell.exe" ` -Argument "-File" "C:\Scripts\Test.ps2" $settins = NewScheduledTaskSettingsSet Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Test" ` -Description "Test connections to a website" -Settings $settings # Now open task scheduler - Library - At end of list Get-ScheduledTask # Lists table of tasks Get-ScheduledTask -TaskName "Test" | Get-ScheduledTaskInfo Unregister-ScheduledTask -TaskName "Test" -Confirm:$false # Delete a scheduled task Scheduled jobs are more like cronjobs (run at intervals, even if system suspended) They are the same as tasks but just for running powershell code - tasks are "Windows" related $trigger = New-JobTrigger -Daily -At 3pm $scriptblock = { C:\Script\Test.ps1 } Register-ScheduledJob -Name "Test" -ScriptBlock $scriptblock -Trigger $trigger Get-ScheduledJob -Name "Te*" | select Name, State # Get only specific values from wildcard Get-ScheduledJob -Name "Test" | Get-JobTrigger # Shows when this is run Unregister-ScheduledJob -Name "Test" Can use windows forms to create GUIs - make a Windows.Forms element Use something like PoshGUI to make UIs and export as powershell Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.Application]::EnableVisualStyles() $DiskSlimmerForm = New-Object system.Windwos.Forms.Form $DiskSlimmerForm.ClientSize = New-Object System.Drawing.Point(447,335) $DiskSlimmerForm.text = $FormTitleText $DiskSlimmerForm.TopMost = $false ... # Define labels, boxes, buttons etc. # Can also set buttons to react to clicks and change data $Button1.Add_Click({ $FirstName = $FirstNameTextBox.Text $Label1.text = "Hello, $FirstName" # Change label to contents of user input }) Can convert powershell to exe files - need ps2exe Install-Module -Name ps2exe Invoke-PS2EXE .\Script.ps1 .\Script.exe # Any shared files need to be kept with the exe Use chatgpt to generate powershell scripts for misc tasks
Powershell Engineer... Learn Powershell with AD https://www.youtube.com/watch?v=9oiEOYFe6PI Can run windows server inside VirtualBox - get Windows Server 2022 (register trial) Open Virtual box, New and edit settings to mount windows server ISO as CD Install with Desktop Experience - reboot and remove CD Input - Keyboard - CTRL-ALT-DELETE to login Manage - Add roles or features - Get "Active Directory Domain Services" - promote system Search for "Active Direcotry Users and Computers" - useful for managing users Now AD is installed you can manage it from command line Import-Module ActiveDirectory Get-Command -Module ActiveDirectory # List AD commands Make an organisational unit so you can group your objects (say DC="MyAD" New-ADOrganizationalUnit -Name "MyOrg" -Path "DC=MyAD,DC=org" # Refresh the "users and computers" page and this org unit should appear # Make a SubUnit by setting OU=MyOrg - do for Engineer, Staff, Students and StudentGroupA-D New-ADOrganizationalUnit -Name "Staff" -Path "OU=MyOrg,DC=MyAD,DC=org" Now you want to make new users Get-Help New-ADUser # May have to update help New-ADUser -Name "John Smith" -SamAccountName "jsmith" -UserPrincipalName "jsmith@email.com" ` -Path "OU=StudentGroupA,OU=Students,OU=MyOrg,DC=MyAD,DC=org ` -AccountPassword (ConvertTo-SecureString "mypassword" -AsPlainText -force) -Enabled $true # Change to "view - advanced features" to see "attribute editor" for users Get-ADUser -Identity "jsmith" Get-ADUser -Filter 'Enabled -eq $true' # Get all enabled users $ADUser = Get-ADUser -Identity "jsmith" # Now that user is saved to a variable $ADUser.UserPrincipalName Get-ADUser -Identity "jsmith" | Select-Object Name,SamAccountName,UserPrincipalName Set-ADUser -Identity "jsmith" -Email ... -OfficePhone ... -Enabled:$false Can reset passwords by setting to a new value Set-ADAccountPassword -Identity "jsmith" -Reset ` -Newassword (ConvertTo-SecureString "newpassword" -AsPlainText -Force) Set-ADUser -Identity "jsmith" -ChangePasswordAtLogon $true Unlock-ADAccount -Identity "jsmith" Can make groups in powershell - Also note "path" means literally a tree of objects -> org If you don't add a path it just adds it to the "users" group New-ADGroup -Name "Team" -Path "OU=Students,OU=MyOrg,DC=MyAD,DC=org" -GroupScope Global Add-ADGroupMember -Identity "Team" -Members "jsmith" $Group = Get-ADGroup -Identity "Team" Can use commands like ".ToLower()" and ".Substring(0,1)" to edit text
Powershell Engineer... Networking with Powershell https://www.youtube.com/watch?v=LRdwjfIzaSY Powershell is very useful for managing networking Test-Connection udemy.com # Get object return of "ping" Test-Connection -ComputerName 8.8.8.8, 8.8.4.4 # Test multiple targets ... -Delay 5 -Count 2 # Add 5 second delay between - and do 2 tests Test-NetConnection udemy.com # Returns cleaner output (with stored data in object) ... -InformationLevel "Detailed" # Get more details $test = Test-NetConnection ... $test.PingReplyDetails.Buffer # Get more granular info on connection replies # Can do traceroutes tracert udemy.com # Basic traceroute $test = Test-NetConnection udemy.com -traceRoute # Traceroute as an object $test.TraceRoute[0] # Get first hop on the path ... -CommonTCPPort "http" # Test a specific port's connection $ports = 22,80 $ports | ForEach-Object { $port = $PSItem if(Test-NetConnection udemy.com -Port $port) { Write-Host "This port $port is open!" } else { Write-Host "This port $port is closed!" } } Get IP information and config with NetAdapter Get-NetAdapter | Format-List Get-NetAdapter[0].MacAddress # Get MAC address of 1st interface $ipinfo = Get-NetIPConfiguration # Show network info $ipinfo[0].DNSServer # Get DNS server of the 1st interface ipconfig # Give basic overview of everything Resolve-DnsName udemy.com | Format-List # See all DNS records for a server Get-DnsClientServerAddress -InterfaceAlias Ethernet # Get DNS servers for ethernet interface Clear-DnsClientCache -Confirm # Clear DNS cache
Powershell Engineer... Powershell System Management https://www.youtube.com/watch?v=46K4SxQdPIo Powershell can be used to get info about the system $serverInfo = Get-ComputerInfo # Shows a long list of system properties $serverInfo.OsVersion # Print e.g. 10.0.20348 Get-ComputerInfo | Select-Object -Property 'TimeZone' # Extract object property Manage processes and services: $procs = Get-Process # List processes (-Name = name filter, -Id = ID filter) $procs | Format-Table -Property Name, Id # Filter a table for only certain columns Start-Process -FilePath "C:\Windows\system32\notepad.exe" Stop-Process -Name "notepad" -Force # Kill process Get-Service # List all services Get-Service -Name "Print Spooler" # Get print spooler service Set-Service | Where-Object { $_.Status -eq "Running" } # Get all running services Stop-Service -Name "Print Spooler" # Open "services" and it's no longer running in there Start-Service -Name spooler # Can also do Restart-Service Manage storage: $CDrive = Get-Volume -DriveLetter C | Format-List # List info about the C storage drive $CDrive.SizeRemaining/1GB # Get storage remaining in GB Clear-RecycleBin -Drive C # Clear recycle bin
Powershell Engineer... File Management in Powershell https://www.youtube.com/watch?v=iGb-e_6uL98 Manage file systems: Get-ChildItem # Output contents of folder as object $acl = Get-Acl "C:\FILENAME" # Get all access permissions for a file $acl.Access | Format-List # Show SYSTEM, Admin and User access to a file # Change permissions of a file $permission = $Administrator","FullControl","Allow" $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission $acl.SetAccessRule($accessRule) # Change the acl object to apply new rules Set-Acl "C:\FILENAME" $acl # Apply new acl changes to the file # Get file sizes Get-ChildItem -Path "FILE_PATH" -Recurse -Force | Measure-Object -Property Length -Sum # Environment variables $env:SystemRoot # Get variable stored under $env - "C:\Windows" Useful to test strings by comparison $string = "Hellow world" if($string -match "Hello") { Write-Output "Match found" } # Compare strings $newstring = $string -replace "Hello", "Hi" # Replace substrings Set-Content -Path "FILENAME" -Value "CONTENT" # Can do "Add-Content" to append $Fileinfo = Get-Content -Path "FILENAME"; $Fileinfo.Length # Get content and size of a file $FileInfo[0] # Gets the first line of the file $csvFile = Import-CSV -Path "FILENAME" # Can now access csv as an object Get-ComputerInfo | Export-CSV -Path "FILENAME" -NoTypeInformation # Save an object as csv $json = Get-Content -Path "FILENAME" -Raw $jsondata = ConvertFrom-Json -InputObject $json # Converts to object/table Get-NetAdapter | ConvertTo-Json | Out-Fle "FILENAME" # Can cast an object to a type like xml [xml]$xml_file = Get-Content FILENAME # Can now address it through child properties $xml_file.character.comedian[0] # Get subitems $xml_file.save(FILENAME) # Reexport to xml
########################################################### 2024-02-09 22:00 ########################################################### Norcal_posh... Automating Group Policy Management with Powershell https://www.youtube.com/watch?v=0pU992a9sio Group policy is mostly routed in point-and-click - recent movements to powershell Desired state config ideal route for configuring servers - need automation tools for this First official Powershell interface for group prolicy was Invoke-GPUpdate (refresh policy) When doing high level powershell commands you need to manually find the registries of data # e.g. HKLM\Software\Policies\Microsoft\Internet Explorer\Restrictions [Ended early - OK but not very value detailed]
Norcal_posh... The Future of Windows Server https://www.youtube.com/watch?v=9ySz_Xxe-08 Nano server is a headless 64-bit deployment for windows server - cloud based Remote management/automation with core powershell and WMI - powershell web access Core powershell is a smaller version of powershell with less tools - minimal system Set-Item WSMan:\localhost\Client\TrustedHosts" "IPADDR" # Add a trusted IP host Enter-PSSession -ComputerName HOSTNAME # Connect to remote server Get-Command -CommandType Cmdlet # List commands available (minimal core powershell) # Basic language constructs like loops and piping still works Import-Module NetTCPIP -Verbose # install NetTCP packages Get-NetIPAddress -AddressFamily IPv4 | Format-Table InterfaceIndex, AddressFamily, ` IPAddress, InterfaceAlias # Show IP info Get-PSProvider # Works as expected - all essentials are installed Get-PSDrive # Show drives on system Exit-PSSession # Disconnect [Again little value - skipped through and nothing of significance]