Wednesday, June 17, 2020

Useful PowerShell command-lines #2

The 185 commands below are a random list of PowerShell one-liners I've taken note of over the years. Some of these commands are approaching 10 years old, so while all of them probably still work there are most likely better ways of achieving the same outcome with current versions of PowerShell and the underlying Operating System.

Each command-line can be copied and pasted at a PowerShell command prompt, or you can use the commands as part of a PS1 script file if you prefer.

Split a string on spaces, removing empty entries
$line.Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries)

Measure how long a commands takes to execute
measure-command -expression {}

List the processes running on a remote machine
$process = [System.Diagnostics.Process]; $process::GetProcesses($server)

Get a process by ID running on a remote machine
$process = [System.Diagnostics.Process]; $proc = $process::GetProcessById(5716,$server)

Set the priority of a process to above normal

Create a new profile with the default profile variable
new-item -type file -force $profile

Create an empty object with the specified properties
$test = "" | Select-Object Name,Speed

Convert a SID to NT account name
$trustee = new-object System.Security.Principal.SecurityIdentifier("S-1-5-21-1234530602-3734247491-3823728601-63426"); $trustee.Translate([System.Security.Principal.NTAccount])

Delete the master account SID attribute from an AD object
$user = [ADSI]$ADsPath ; $user.putex(1,"msExchMasterAccountSid",$null)

Set the execution policy to allow local scripts to run unsigned
Set-ExecutionPolicy RemoteSigned

Set process affinity
$calcSet = Get-Process -ProcessName "calc" ; foreach ($calc in $calcSet) {$calc.ProcessorAffinity=0x1}

List the values of an enumeration

Use the WinNT provider to check administrative membership for a remote computer
[ADSI]"WinNT://" + $computerName + "/Administrators,group"; $members = $adminGroup.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} | sort-object

Export the key/value pairs of a hash table to csv
$test.GetEnumerator() | export-csv -path c:\temp\hashtable.csv

Return the date format using the get-date cmdlet
Get-Date -format "dd/MM/yyyy HH:mm:ss"

Create an associative array / hash table /
$test = @{a=1; b=2}

Sort a hashtable associative array by name or value
$results = @{a=1; b=2;c=0}; $results.GetEnumerator() | sort-object -property Name

Sleep or pause for 10 seconds
Start-Sleep -seconds 10

Find the last win32 exit code (errorlevel)

Find the name of the currently running script

Convert a string into datetime type using the current culture
$test = "17/03/2010 10:00:00 AM"; [datetime]::Parse($test, [System.Threading.Thread]::CurrentThread.CurrentCulture)

Run an infinite loop
for (;;) {write-output "loop"}

Process a list of files, extracting the first group of a repeating set of data
$files = get-item -path .\*; foreach ($file in $files) {$sandata = get-content -path $file; $count=0; foreach ($line in $sandata) {$csv = $line.split(","); if ($csv[0] -like '*textfilter*') {$count+=1}; if ($count -le 1) {if ($csv[0] -notlike '*Object*') {$line | out-file -file c:\temp\DailySANExport.csv -encoding ascii -append}}}}

Query Citrix XenApp server session information
Get-Wmiobject -namespace root\Citrix -class MetaFrame_Session -computer server01 | format-table -wrap -autosize

Query Citrix XenApp server load information
Get-Wmiobject -namespace root\Citrix -class MetaFrame_Server_LoadLevel -computer server01,server02,server03| format-table -wrap -autosize -prop ServerName,LoadLevel

Find the size of a folder and contents (including subdirectories)
Get-ChildItem $dirPath -recurse | Measure-Object -property length -sum

Round a number down

Find the last bootup time of a Windows OS
$lastBootTime = Get-WmiObject win32_operatingsystem -computer server01 -prop LastBootUpTime

Find the uptime of a machine from WMI, converted from CIM datetime to timespan
$computer = 'server01'; $lastBootTime = Get-WmiObject win32_operatingsystem -computer $computer -prop LastBootUpTime; $wbemDateTime = New-Object -ComObject WbemScripting.SWbemDateTime; $wbemDateTime.value = $lastboottime.LastBootUpTime; $lastBoot = $wbemDateTime.GetVarDate(); $now = Get-Date; $uptime = $now - $lastBoot; $uptime

Select a calculated property using a friendly name
Get-WmiObject -class win32_process | Select-Object -prop Name, @{Name="Owner";Expression ={($_.getowner().domain + "\" + $_.getowner().user)}} | format-table -wrap -autosize

List Processes and their owner
Get-WmiObject -class win32_process | Select-Object -prop Name, @{Name="Owner";Expression ={($_.getowner().domain + "\" + $_.getowner().user)}} | format-table -wrap -autosize

Create a PSObject to store name/value note pairs
$output = new-object PSObject; add-member -membertype NoteProperty -inputObject $output -name "Test" -value "value"

Start a command shell with elevated (UAC) privileges
$psi = new-object System.Diagnostics.ProcessStartInfo "cmd.exe"; $psi.Verb = "runas"; [System.Diagnostics.Process]::Start($psi)

Mail-enable an AD contact in an Exchange 2007 environment
get-mailcontact "CN=user1,DC=domain,DC=local" | set-mailcontact

Query the amount of free space available for 2008 R2 disk shrinking
diskpart shrink querymax

Find the local PowerShell version

Read a file, sort it and then return only unique entries
gc $filename | sort | get-unique > $newfileName

Find unique strings filtered from an input file
find /i '"driverName"' PrinterDrivers_20110708.txt | sort | get-unique > c:\temp\PrinterDrivers.txt

Create a security identifier for a well-known security principal
$self = new-object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::SelfSid, $null)

Convert the Exchange 2007 string into readable format (EXCHANGE12ROCKS)
$out = ""; foreach ($char in ([char[]]"FYDIBOHF23SPDLT")) {$out += ([char]([int]$char-1))}; $out

WMI query to find properties is or is not NULL
Get-Wmiobject -namespace root\MicrosoftExchangeV2 -computer "server01" -Query "SELECT MailboxDisplayName,TotalItems,Size from Exchange_Mailbox WHERE MailboxDisplayName='Cartelier, Robbie' AND DateDiscoveredAbsentInDS is null"

Query disk information from a remote server using WMI
$disks = Get-WmiObject -Namespace root\cimv2 -ComputerName server01 -Query "SELECT * from Win32_LogicalDisk WHERE FileSystem='NTFS'"

Find services filtered by string that are running and stop them
get-service | where {$_.displayName -like '*time*' -and $_.status -eq 'Running'} | stop-service -force

Find and delete a local profile from a remote computer
$user = "domain\account"; $computer = "server01"; $trustee = new-object System.Security.Principal.NTAccount($user); $sid = $trustee.Translate([System.Security.Principal.SecurityIdentifier]).value; get-wmiobject -computer $computer -Query "SELECT * from Win32_UserProfile Where SID = '$sid'"; $profile.delete()

Create an array with a single member
$SingleArray = ,1

Store the results of an expression in an array
$test = @(get-service )

Find disk drive statistics from a number of remote computers
$servers = get-content -path servers.txt; $diskStats = $null; foreach ($server in $servers) { $diskStats += Get-Wmiobject -namespace root\cimv2 -computer $server -Query "SELECT SystemName,Name,Size,FreeSpace,VolumeName FROM Win32_LogicalDisk WHERE Size > 0 AND FileSystem='NTFS'" -ErrorAction SilentlyContinue}; $diskstats | select-object SystemName,Name,Size,FreeSpace,@{N="Used";E={$_.Size-$_.FreeSpace}},VolumeName,@{N="SizeGB";E={[math]::round($_.Size/1024/1024/1024)}},@{N="FreeGB";E={[math]::round($_.FreeSpace/1024/1024/1024)}},@{N="UsedGB";E={[math]::round(($_.Size-$_.FreeSpace)/1024/1024/1024)}} | sort -prop SystemName,Name | export-csv -path servers_diskstats.csv

Find USB devices attached to a number of remote computers
$servers = get-content -path servers.txt; foreach ($server in $servers) {[System.Object[]]$USBDevices += Get-Wmiobject -namespace root\cimv2 -computer $server -Query "SELECT * FROM Win32_DiskDrive WHERE InterfaceType = 'USB'" -ErrorAction SilentlyContinue}; $USBDevices| select __server, Caption, @{N="Size (GB)";E={[math]::round($_.Size/1000/1000/1000)}} | ft -wrap -autosize

Use the split operator to split on multiple characters
$user.proxyAddresses -split ";;"

Find the CA eTrust signature version from the agent.xml file
$ver = select-xml -path c:\temp\agent.xml -xpath '//thisProduct[@Name="eTrust Integrated Threat Manager"]/*/*[@Name="Anti-Malware Signatures"]'; $ver.node.version

Test a host connection with ping
if (test-connection -computer "server01" -count 1 -quiet) {write-host "test"}

Read and process an XML file on a list of servers, returning some attributes
$servers = get-content -path servers.txt; foreach ($server in $servers) {  if (test-connection -computer $server -count 1 -quiet) {    $path = '\\' + $server + '\c$\Program Files\CA\SharedComponents\Agent\Agent.xml';     if (test-path -path $path) {      $ver = select-xml -path $path -xpath '//thisProduct[@Name="eTrust Integrated Threat Manager"]/*/*[@Name="Anti-Malware Signatures"]';      if ($ver) {write-output ($server + "," + $ver.node.version.major + '.' + $ver.node.version.minor + '.' + $ + '.' + $ver.node.version.revision + "," + $ver.node.LastUpdateTime)}     } else {      Write-Output ($server + "," + "agent.xml not found")    }  }}

Find the uptime from one or more remote machines
$servers = get-content -path servers.txt; foreach ($computer in $servers) {   if (test-connection -computer $computer -count 1 -quiet) {     $lastBootTime = Get-WmiObject win32_operatingsystem -computer $computer -prop LastBootUpTime;     $wbemDateTime = New-Object -ComObject WbemScripting.SWbemDateTime;     $wbemDateTime.value = $lastboottime.LastBootUpTime;     $lastBoot = $wbemDateTime.GetVarDate();     $now = Get-Date; $uptime = $now - $lastBoot;     Write-Host ($computer + "," + $uptime.days + "," + $lastBoot.ToString("dd/MM/yyyy"));   } }

Set the window title of a PowerShell window
$host.UI.rawui.windowtitle = "test"

Kill a remote process with WMI

Convert a SWBEM datetime yyyymmhhdd time to standard datetime
$datetime = [System.Management.ManagementDateTimeConverter]::ToDateTime($installDate)

Find DNS scavenging events from a 2008 R2 server
$DNS = Get-Wmiobject -namespace root\cimv2 -computer "server01" -Query "SELECT * FROM Win32_NTLogEvent WHERE SourceName='Microsoft-Windows-DNS-Server-Service' AND LogFile='DNS Server' AND EventCode=2501" -ErrorAction SilentlyContinue; Write-Host "Time Generated,Visited Zones,Visited Nodes,Scavenged Nodes,Scavenged Records,Elapsed Seconds,Run again in hours" ; foreach ($scavenge in $dns) {write-output ([System.Management.ManagementDateTimeConverter]::ToDateTime($scavenge.timeGenerated).tostring() + "," + [string]::join(",",$scavenge.insertionstrings))}

Check whether the windows Search Service file services role is installed
wmic /node:server01 path Win32_ServerFeature where "ID=107"

Query remote event logs for DFS initial sync replication log entries
get-eventlog -logname 'DFS Replication' -computer server01 -after "15/01/2012 8:00:00" | where {$_.eventID -eq 4104}

Query local network connections (netstat)

Find when a number of machines had their NIC disconnected
$vms = get-content -path servers.txt; $events = foreach ($server in $vms) {get-eventlog -logname 'System' -computer $server -after "31/01/2012 17:00:00" | where {$_.eventID -eq 4201 -or $_.eventID -eq 4202}}; $events | select MachineName,EventID,TimeGenerated,Source,{$_.ReplacementStrings} | export-csv -path c:\temp\VM_NetworkDisconnectedEvents.csv

Enumerate arrays and output their contents to CSV
$events | select MachineName,EventID,TimeGenerated,Source,{$_.ReplacementStrings} | export-csv -path c:\temp\VM_NetworkDisconnectedEvents.csv

Search through text logs looking for a string
select-string -pattern -path .\ExchangeLogs\*.* -SimpleMatch

Compare two sets of objects to identify differences
compare-object -referenceobject $processes_before -differenceobject $processes_after

Find the default domain password policy

Find the available PowerShell modules
get-module -listAvailable

Find the PowerShell modules that are installed in the current session

Find the commands available in a specific PowerShell module
get-command -module GroupPolicy

Find IPMI WMI recent SEL event information from a number of servers
$servers = get-content -path servers.txt; $IPMIStats = $null ;foreach ($server in $servers) {  $IPMIStats += Get-Wmiobject -namespace root\hardware -computer $server -Query "SELECT __server,MessageTimestamp,Description FROM LogRecord WHERE MessageTimestamp > '20120201000000.000000+600'" -ErrorAction SilentlyContinue}; $IPMIstats | select-object __server,MessageTimestamp,Description | sort -prop __server | export-csv -path c:\temp\SEL_20120225.csv

Read and decode the DACL stored in a REG_BINARY object in the registry
$reg = get-itemproperty "HKLM:\System\CurrentControlSet\Services\LanmanServer\DefaultSecurity"; $acl = New-Object Security.AccessControl.RawSecurityDescriptor($($reg.SrvsvcSharePrintInfo), 0); $acl.DiscretionaryAcl; # see for access mask

Convert REG_BINARY filetime stored in reversed byte/word format to date/time
[datetime]::FromFileTime([Convert]::ToInt64("01CD098EBB74AE65", 16))

List the PowerShell profile script path properties
$profile | select *

Read from remote event logs with PowerShell 2.0 or later

Get the event log provider names for the specified log
$log = get-winevent -listlog Security | select providernames; $log.providernames

Find the EventID and descriptions from the specified event log provider
(get-winevent -listprovider 'Microsoft-Windows-Security-Auditing').events | ft ID,Description -autosize

Reverse an array

Join an array and output as a string with the specified delimiter
("test1", "test2") -join ";"

Add a UPN suffix to the local forest
get-adforest -current localcomputer | set-adforest -upnsuffixes @{Add=""}

Modify the UPN for a user
get-aduser -id user01 | set-aduser -UserPrincipalName

Extract error information
$error[0].Exception | select * ; $error[0].Exception.InnerException | select *

Export a single property from multiple objects to file
$objects | select -prop prop01 | export-csv -notype -path c:\temp\output.txt -encoding ascii

Export server shares to a csv file
$outputfile = "c:\temp\server01_shares_" + [DateTime]::Now.ToString("yyyyMMddhhmmss") + ".csv"; Get-WmiObject win32_share -computer server01 | select Name,Path,Description,Caption | export-csv -path $outputFile; $outputFile

Check each line of one file for a match in a second file
$inputLines = get-content -path c:\temp\File01.txt; foreach ($line in $inputLines) {$match = select-string -pattern $line -path File02.txt -SimpleMatch; if (!($match)) {$member}}

Join a file in blocks of two lines
$text = get-content -path File.txt; $results = for($i=0; $i -le $text.length; $i = $i+2){Write-Output ($text[$i] + "; " + $text[$i+1])}

Convert a unicode hex-string to human readable string
$converted = for ($i=0; $i -le $string.length-1; $i = $i+4) {write-output ([CHAR][BYTE]([CONVERT]::toint16($string.substring($i, 2),16)))}; [string]::join("",$converted)

Find the snap-ins currently registered
get-PSsnapin -registered

Run FIM 2010 R2 Microsoft Best-practices Configuration Analyser
Import-module "C:\Program Files\Microsoft Baseline Configuration Analyzer 2\Modules\BaselineConfigurationAnalyzer\BaselineConfigurationAnalyzer"; Invoke-MBCAModel -ModelId FIMBPA -SubModel FIMService -computer fimservice

Binary OR of useraccountcontrol to see if an account is enabled/disabled
(514 -bor 2) -eq 514

Convert a date to filetime (64-bit 100-nanosecond since midnight, 01/01/1601)
$date = [datetime]"24 December 2012"; $date.tofiletime()

Regular expression for numbers with spaces or brackets
'^[\d() -]+$'

Remove brackets and spaces from a string
$test -replace('\(|\)|\s','')

Use the Modulus operator as a way of reporting status in a loop every x
$progress = $count % 1000; if ($progress -eq 0) { Write-Output $count}          # Report every 1000

Find the current running username in domain\user format

Find the current running username

Break a loop if keyboard input is detected
if($host.UI.RawUI.KeyAvailable) {break;}

Loop infintely until the 'Q' key is pressed
$Qkey = 81; for (;;) {  start-sleep 5; if($host.UI.RawUI.KeyAvailable) { $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp")  ; if ($key.VirtualKeyCode -eq $Qkey) ;  { break; } }  Write-Output "$(get-date)" }

Install IIS on 2008 onwards
Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature

Find installed hotfixes and installation date
$hotfixes = Get-WmiObject -Namespace root\cimv2 -computer Computer -Query "Select HotfixID,ServicePackInEffect,InstallDate,InstalledBy,InstalledOn from win32_quickfixengineering"

Write a System.Byte[] array to a binary file
set-content -value $byteArray -encoding byte -path c:\temp\image.bmp

Convert decimal to hex
'{0:x}' -f 15

Rename an Active Directory object (caters for naming attribute renames)
rename-adobject -id "CN=User1,OU=Users,DC=domain,DC=local" -newname user2 -server

Convert yyyymmdd to [datetime]
[datetime]::ParseExact("20130913", "yyyymmdd",  [Globalization.CultureInfo]::InvariantCulture)

Match an array of objects against a string using regular expressions
$mailbox = $mailboxes -match "MARTIN Wayne"

Create a generic log file name based on the script name and today's date
$logFile = ".\" + ($MyInvocation.MyCommand.Name.split("."))[0] + "_" + [DateTime]::Now.ToString("yyyyMMdd") + ".log"

Split a string (eg distinguishedName) containing escaped commas
$dn -split "(?<![\\]),"

List the event log providers on a remote computer
get-winevent -computer server01 -listprovider *

Append to the System path environment variable
$path = [environment]::GetEnvironmentVariable("Path","Machine"); [Environment]::SetEnvironmentVariable("Path", "$path;c:\util", "Machine")

Use AD cmdlets to change the samaccountname of a security group
get-group -id oldsamid | set-group -name newsamid -displayName "newdisplayName" -whatif

Connect with remote powershell to a Lync server
$lync = "lync01"; $session = New-PSSession -ConnectionUri "https://$lync/OcsPowershell" -Authentication Negotiate; Import-PsSession $session

Update the SIP address of a Lync user
Set-CsUser -Identity "user01" -SipAddress "sip:user01@domain.local" -whatif; get-csuser -id user01 | select SipAddress

Find Server 2012 firewall profiles

Set Server 2012 firewall profiles to lock dropped traffic
Get-NetFirewallProfile  | Set-NetFirewallProfile -logBlocked "True"

Find the last known SCM message for the specified service starting
get-winevent  -computername fim01 -FilterHashTable @{ logname = "System"; providername="Service Control Manager"; ID = 7036; data = "Forefront Identity Manager Synchronization Service","Running"} -MaxEvents 1

Find the process creation date of a remote process
(Get-WmiObject -ComputerName fim01 -Query "Select * from win32_process where name ='miiserver.exe'") | select Name,@{N='Date';E={$_.ConvertToDateTime($_.creationdate)}} | ft -wrap -auto

Find if an AD account is locked out or not
get-aduser -id user01 -server dc01 -prop LockedOut

Start and then stop a network capture trace on server 2012
netsh Trace start capture = yes & pause & Netsh Trace stop

List the classes in a WMI namespace
Get-WmiObject -list -Namespace root\rsop\computer

Query the highest precedence logon as a service right GPO
Get-WmiObject -computer server01 -namespace root\rsop\computer -class RSOP_UserPrivilegeRight | where {$_.UserRight -eq 'SeServiceLogonRight' -and $_.Precedence -eq 1} | select-object -expand AccountList

Show the last 15 errors in the application event log
get-winevent  -computername server01 -FilterHashTable @{logname = "Application"; level=2} -MaxEvents 15

Query Server 2012 for scheduled task information
Get-WMIObject -computer server01 -Namespace "root\Microsoft\Windows\TaskScheduler" -Query "SELECT * from MSFT_ScheduledTask"

Query the security descriptor of shares on a server
$shares = Get-WMIObject -Computer "server01" -Namespace root\cimv2 -Query "SELECT * from  Win32_LogicalShareSecuritySetting"

Generate a new GUID

Generate a new GUID and return with braces

Get an empty GUID (all zeroes)

List browser URLs and document titles for IE browser (not edge)
$urls = (New-Object -ComObject Shell.Application).Windows() | Where-Object {$_.LocationUrl -match "(^https?://.+)|(^ftp://)"}; $urls | select locationName,locationUrl | ft -wrap -auto

View ADFS tracing from the debug event log
get-winevent  -computername adfs01 -FilterHashTable @{ logname = "AD FS Tracing/Debug"} -oldest

View ADFS auditing for claim information
get-winevent  -computername adfs01 -FilterHashTable @{ logname = "Security"; providername="AD FS Auditing"; ID = 500,501} -MaxEvents 10 | select id,machineName,TimeCreated,Message | ft -wrap -auto

View the AD site name associated with the specified computer
dfsutil /sitename:server01

Find the .Net framework version the current PowerShell instance is using

Store an encrypted password reversable only by the encrypting user
ConvertTo-SecureString -string "password" -asplaintext -force | ConvertFrom-SecureString | out-file -file c:\temp\password.txt

Encode a string to base64

Decode a base64 string to text string

Install the ActiveDirectory module for PowerShell
Install-WindowsFeature -Name RSAT-AD-PowerShell

Export a certificate to binary format
Export-Certificate -FilePath c:\windows\temp\cert.crt -cert cert:localmachine\ca\9A26AAB090E0CD1F39B96731A4B49AAC65E7BEEA -type cert

Convert an octet stored byte array (eg. GUID) to hex string
[System.String]::Join('',( (get-adobject -id "uid=user01,OU=Users,DC=domain,DC=local" -server dc01 -prop objectguid).objectguid | ForEach-Object { $_.ToString('x2') }))

Check if a string is null or empty
if ([string]::IsNullOrEmpty($string) -eq $true){"True"}

List the UPN suffixes from a remote forest
(get-adforest -identity domain.local).upnsuffixes

List the PowerShell remoting endpoints

Read a certificate from file
Get-PfxCertificate -FilePath c:\temp\test.cer | fl *

Prevent PowerShell progress bars from displaying
$ProgressPreference = "SilentlyContinue"

Convert the number of seconds to a timespan to show hours/minutes etc

Find a remote PowerShell session using WinRM
Get-WSManInstance -ConnectionURI http://server01:5985/wsman shell -Enumerate

Remove a remote PowerShell session using WinRM
Remove-WSManInstance -ConnectionURI http://localhost:5985/wsman shell @{ShellID="6CF3C5C6-1954-430F-98B7-2D99E8AADCE3"}

Start an elevated process with PowerShell
start-process -verb RunAs cmd

Find the verbs available for a particular file
$startExe = New-Object System.Diagnostics.ProcessStartInfo -Args PowerShell.exe; $startExe.verbs

Check if a specified time of day has passed
((get-date) -lt ([datetime]::ParseExact("23:00:00", "HH:mm:ss", [System.Globalization.CultureInfo]"en-AU")))

Start an elevated runas process as alternate credentials
Start-Process powershell -Credential $cred -ArgumentList '-noprofile -command &{Start-Process cmd -verb runas}'

Find service terminated unexpectedly (multiple event IDs)
get-winevent  -computername server01 -FilterHashTable @{ logname = "System"; startTime = $date; id=7031,7034}

Decrypt a securestring password to text
(New-object System.Net.NetworkCredential("",$Password)).Password

Convert to a nicely formatted JSON message
ConvertFrom-Json $message | ConvertTo-Json

Find hotfixes installed

URL encode a string

Check remote Hyper-V VM migration status
Get-WmiObject -computer server01 -Namespace root\virtualization\v2 -Class Msvm_MigrationJob | ft Name, JobStatus, PercentComplete, VirtualSystemName

Make it so doskey macros and shortcuts work in PS5+
Remove-Module PSReadLine

Find the digital signature of a file
(get-AuthenticodeSignature c:\util\procexp.exe).SignerCertificate | fl *

Convert Unix epoch time in milliseconds to datetime
(Get-Date "1970-01-01 00:00:00.000Z") + ([TimeSpan]::FromMilliSeconds(1539045767455))

Convert a number to binary

Convert from win32 filetime
"{0:hh:mm:ss.fff tt dd/MM/yyyy}" -f [datetime]::FromFileTime(131864751713547989)

Find the effective applocker policy
Get-AppLockerPolicy -Effective | Test-AppLockerPolicy -Path "C:\Windows\System32\cscript.EXE"

Determine whether the AD recycle bin is enabled or not (EnabledScopes)
Get-ADOptionalFeature -Filter 'name -like "Recycle Bin Feature"'

Find the Active Directory schema version
Get-ADObject (Get-ADRootDSE).schemaNamingContext -Property objectVersion

Query SCCM for a computer resource
$server = "sccm01";$site = "s01"; $resourceName = "server01"; $resource = Get-WmiObject -ComputerName $server -Namespace "root\sms\site_$site" -Class "SMS_R_System" -Filter "Name = '$resourceName'"

Query SCCM for a the collection membership of a computer resource
$ids = (Get-WmiObject -ComputerName $server -Namespace "root\sms\site_$site" -Class SMS_FullCollectionMembership -filter "ResourceID=`"$($Resource.ResourceId)`"").collectionID

Export DNS zone information from a 2016 DC
Get-DnsServerZone | export-csv -path c:\windows\temp\DNSZones_20190304.csv -encoding ascii -notype

Find Active Directory replication conflict objects
$conflicts = Get-ADObject -LDAPFilter "(|(cn=*\0ACNF:*)(ou=*CNF:*))"

Install RSAT on Windows 10 1809
Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability -Online

Find Office 365 Group mailbox folder information
get-mailboxfolderstatistics -id user01@domain.local | select FolderPath

Find events containing the specified string
$filter =  @{logname='Security'; starttime=[datetime]::today; data='/adfs/services/trust/2005/windowstransport' }; $events = get-winevent -computername adfs01 -FilterHashTable $filter

Decode a dnsrecord entry in an AD DNSRecord object
$dnsrecord = (get-adobject -id "DC=10.10,,CN=MicrosoftDNS,DC=ForestDnsZones,DC=domain,DC=local" -prop *).dnsrecord; [System.Text.Encoding]::ASCII.GetString($dnsrecord[0])

Report when a TCP connection was created
Get-NetTCPConnection | Sort-Object LocalPort | Format-Table Local*, Remote*, State, CreationTime

Find any alternate data streams in a file
get-item c:\temp\test.txt -Stream *

View the content of an alternate data stream
get-content c:\temp\test.txt -Stream Stream1

Remove an alternate data stream
Remove-Item -path c:\temp\test.txt -Stream Zone.Identifier

Find the direct reports from the AD manager backlink
(get-aduser -id user01 -prop directreports).directreports

Find the day of week

Find the number of the current day of the week
[int](get-date).DayOfWeek | (get-date).DayOfWeek.value__

Find the number of the the specified day

Format a string as hex
"05bb80f4-5d0b-4358-b173-7a206a924734" | format-hex

Export DNS SRV records
Get-DNSServerResourceRecord -ZoneName domain.local -ComputerName dc01 -RRType SRV | Export-CSV -path c:\temp\srv-export.csv -notypeinformation

Query Domain Controllers in one or more sites
Get-ADDomainController -filter "site -eq 'site1' -or site -eq 'site2' -or site -eq 'site3'" |select name

Show datetime on command prompt
function prompt { "PS $((Get-Date).ToString("hh:mm:ss")) $(get-location)>"}

Find DCs running 2016 OS
Get-ADDomainController -filter "OperatingSystem -eq 'Windows Server 2016 Standard'" | select name

Unblock a file downloaded from the Internet
Unblock-File C:\temp\downloaded.ps1

Find the 5 most recent files from the specific path
Get-ChildItem -Recurse -path c:\admin\scripts\powershell\*.ps1 | sort -prop LastWriteTime -desc | select -first 5 FullName,LastWriteTime

Find the registered event log sources for the specified log
Get-WMIObject -Computer "server01" -Authentication PacketPrivacy -Query "SELECT FileName, Sources from Win32_NTEventLogFile where FileName = 'CustomEventLog'" | select -expand sources

Wayne's World of IT (WWoIT). 

No comments:

All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 20 years, and I know just about enough to realise that I don’t know very much.