The author of a Github Powershell script I'm often using for scanning media files for errors has uploaded a new file to the same repo called "Commands_JD.ps1" and this is it's content:
function FktWriteToLog {
write-host args[0])
}
FktWriteToLog "Some text"
Getting more details of last error
$Error[0] | Format-List -Force
Assistant
(
#PsExec Alternative in PowerShell (Invoke-PsExec)
#For true PsExec-like functionality, there’s an open-source PowerShell module called Invoke-PsExec, which uses PsExec under the hood and communicates over port 445.
#To install the module and use it:
Install-Module -Name Invoke-PsExec -Scope CurrentUser
Invoke-PsExec -ComputerName "RemoteComputerName" -Credential (Get-Credential) -Command "notepad.exe"
#This approach closely mirrors PsExec's functionality and connects over port 445.
#Create a CIM session to multiple computers
New-CimSession -ComputerName Server01, Server02, Server03
#Create a CIM session with a friendly name
New-CimSession -ComputerName Server01, Server02 -Name FileServers
Get-CimSession -Name File*
#Create a CIM session using DCOM
SessionOption=New−CimSessionOption−ProtocolDCOMNew−CimSession−ComputerNameServer1−SessionOptionSessionOption
Update Windows Defender definitions
Update-MpSignature
#netstat alternative:
Get-NetTCPConnection | select Local*, Remote*, State, @{n = "ProcessName"; e = { (Get-Process -Id $_.OwningProcess).ProcessName } },
@{n = "ProcessPath"; e = { (Get-Process -Id $_.OwningProcess).Path } } | ft -Auto
#Linux commands:
du -sk * | sort -n
du -sh * | sort -h
#check port in Linux : nc -zv
Get-WmiObject -Class Win32_Product -ComputerName ComputerName−Filter"Namelike′Java.Version }
Get-WmiObject -Class Win32_Product -Filter "Name like 'Java%'" | Foreach-Object { "$.Version" }
#Uptime
Get-CimInstance -ClassName Win32_OperatingSystem | Select LastBootUpTime
#Commenting in PS script
<#
Any text here
#>
#To find out the version and build number of your Windows. Use the following PowerShell command:
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer, OsArchitectur
#Example 7: Get all computers with a name starting with a string AND password last set before 30 days
Date=[DateTime]::Today.AddDays(−30)Get−ADComputer−Filter′Name−like"Computer01∗"−andPasswordLastSet−geDate' -Properties IPv4Address | FT Name, DNSHostName, IPv4Address -A
name dnshostname ipv4address
#Example 5: Get all computer accounts using a filter
Get-ADComputer -Filter *
#CanonicalName
Get-ADComputer -Filter * -Properties IPv4Address | FT Name, DNSHostName, IPv4Address, CanonicalName -A
#Export all AD Computers to CSV file
Get-ADComputer -Filter * -Properties * |
Select -Property Name, DNSHostName, IPv4Address, CanonicalName, Enabled, LastLogonDate |
Export-CSV "C:\AllComputers.csv" -NoTypeInformation -Encoding UTF8
#Windows product key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform , find value of BackupProductKeyDefault
#Command to add MSL group to local admin
powershell -command "& { ([adsi]'WinNT://./administrators,group').Add('WinNT://shell/fSys-HNS-SCv2-MigrationServiceLine-GS,group'); }"
powershell -command "& { ([adsi]'WinNT://./administrators,group').Add('WinNT://shell/APS-GRNP-SCV2-DCBS_TST_OS_SUPPORT_TEAM-LS,group'); }"
Can you explain to me in simple terms what the script does?
Certainly! The Commands_JD.ps1 file you've come across isn't a traditional script that performs a specific task when executed. Instead, it's more like a collection of PowerShell command snippets, examples, and notes that a system administrator might use as a personal reference or cheat sheet.
This file appears to be the author's compilation of useful commands for various system administration tasks. Here's a summary of what the script includes:
Event Log Management:
Retrieving Event Logs: Commands to list and filter event logs based on specific criteria, such as recent log entries or particular event IDs.
Formatting Output: Uses Format-Table and custom expressions to display event log information in a readable format.
Function Definitions and Error Handling:
Simple Function Example: Defines a function FktWriteToLog that writes text to the console, demonstrating how to work with functions and arguments.
Error Details: Shows how to retrieve detailed information about the last error using $Error[0].
Remote Command Execution:
PsExec Alternative: Instructions on installing and using the Invoke-PsExec module, which allows you to execute commands on remote computers similarly to PsExec.
File Content Search:
Finding Strings in Files: Uses Get-ChildItem and Select-String to search for specific text within files across directories.
User Profile Management:
Querying and Deleting User Profiles: Commands to list and remove user profiles on local or remote computers using CIM and WMI classes.
File Details and Formatting:
Retrieving File Information: Commands that get file properties like name, size, and timestamps, and format them neatly for display or export.
Windows Package Management:
Installing CAB Files: Shows how to install Windows update packages from CAB files using Add-WindowsPackage and dism.
Network Configuration and Testing:
TLS Settings: Commands to set and retrieve the TLS versions used in network communications.
Network Connections: Retrieves active TCP connections along with the owning process names.
Ping and Connectivity Tests: Uses Test-Connection to check connectivity to remote hosts.
Windows Activation and Licensing:
Checking Activation Status: Queries the SoftwareLicensingProduct class to retrieve licensing information, including license status and product keys.
KMS Server Information: Retrieves details about the Key Management Service used for activation.
Windows Update Management:
Triggering Updates: Commands to initiate Windows Update detection and view update history.
Registry Checks: Retrieves Windows Update-related settings from the registry.
Firewall Configuration:
Viewing and Setting Firewall Profiles: Commands to check the status of Windows Firewall profiles and enable or disable them as needed.
Domain Management:
Joining Computers to a Domain: Commands that demonstrate how to add a computer to a domain, specifying organizational units (OUs) and credentials.
File Operations with Robocopy:
Copying Files with Size Limitations: Examples of using robocopy with parameters to copy files while enforcing maximum file size limits.
Process and Service Management:
Getting Process Details: Retrieves processes' command lines, executable paths, and associated usernames.
Managing Services: Commands to disable or restart services on local or remote computers.
Disk and File System Information:
Disk Usage: Retrieves information about disk capacity and free space.
Deleting Files Recursively: Commands to delete specific files (like desktop.ini) from a directory tree.
Event Log Monitoring:
Filtering Event Logs: Commands to retrieve specific events from logs, such as recent errors or events with particular IDs.
Active Directory Queries:
Retrieving Computer Accounts: Uses Get-ADComputer to list computer accounts and export details to CSV.
System Information Retrieval:
OS and Hardware Details: Commands to get operating system versions, hardware abstraction layers, and architecture.
Miscellaneous Utilities:
Network Tracing: Starts and stops network traces using netsh.
PowerShell Formatting: Tips on formatting code in PowerShell and comments.
Working with the Registry: Commands to search and manipulate registry keys and values.
Linux Commands:
Disk Usage: Includes Linux commands like du -sh * | sort -h for checking disk usage.
PowerCLI Commands:
VMware Management: Commands related to managing virtual machines and network adapters using VMware's PowerCLI.
Scripting Practices:
Commenting in PowerShell: Demonstrates how to include multi-line comments in scripts.
Creating Files: Uses New-Item to create new files programmatically.
In Simple Terms:
The Commands_JD.ps1 file is more like a toolkit or a reference guide for a system administrator. It doesn't perform any actions on its own when you run it. Instead, you can look through it to find commands that help with:
Managing and querying system logs.
Handling files and directories.
Managing user profiles and processes.
Configuring system settings like Windows Updates, firewall, and network protocols.
Automating administrative tasks like joining a domain or installing updates.
Interacting with Active Directory to retrieve computer or user information.
Gathering system information and hardware details.
Managing services and processes on local or remote machines.
Using VMware PowerCLI for virtual machine management.
What Should You Do with This Script?
If you're interested in any of the tasks mentioned above, you can:
Learn: Read through the commands to understand how they work. It could be a valuable learning resource if you're looking to expand your PowerShell knowledge.
Use Specific Commands: Copy and paste individual commands you find useful into your PowerShell console or scripts to perform specific tasks.
Customize: Modify the commands to suit your environment or to automate tasks specific to your needs.
Important Note:
Caution with Execution: Since some commands modify system settings, delete files, or remove user profiles, be cautious if you plan to run any of them. Always ensure you understand what a command does before executing it, especially on production systems.
Testing: If you decide to use any of the commands, test them in a safe environment first (like a virtual machine) to observe their effects.
If You Need Further Explanation:
Feel free to ask about any specific command or section in the script that you'd like to understand in more detail. I can help break down how individual commands work and what they do.