mode con:cols=150 lines=50
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Undefined
wuauclt /showwuautoscan
footzilla comments on ITT:Handy Commands You Might Not Know
Install-Module -Name "PSWindowsUpdate"
Get-Childitem -Path Env:* | Sort-Object Name
Restart-Computer
Enable-PSRemoting -Force
Enter-PSSession -ComputerName dc-corp-1203 -Credential corp\lstephens
Enable PSRemoting How To Enable Powershell Remoting via Group Policy How to Run PowerShell Commands on Remote Computers
ls * -r | sls 'ramesh’
Grep, the PowerShell way – Communary
New-PSDrive -Name "Z" -PSProvider FileSystem -Root "\\file-corp-1202\IT Apps" -Credential CORP\lstephens -Persist
| Export-CSV "$home\Downloads\filename_$(get-date -f MMddyyyy_hhmmss).csv"
XYZ command -FilterHashtable
get-wmiobject -class "win32_account" -namespace "root\cimv2" | sort caption | format-table caption, __CLASS, FullName
Get-ADUser -Identity $env:USERNAME -Properties *
Get-ADUser -Identity ldapreader -Properties *
Import-Module activedirectory
Search-ADAccount -LockedOut | Unlock-ADAccount
Get-ADUser -Identity etan
Get-WinEvent -ComputerName dc-corp-1203 -FilterHashtable @{logname='security';id=4740;data='S-1-5-21-985829038-2064205030-564823159-2069'}
OR
Get-WinEvent -ComputerName dc-corp-1203 -FilterHashtable @{logname='security';id=4740;data=‘etan’} |
Select-Object -Property timecreated,
@{label='username';expression={$_.properties[0].value}},
@{label='computername';expression={$_.properties[1].value}}
OUTPUT
TimeCreated username computername
----------- -------- ------------
3/21/2017 9:16:25 AM etan
3/21/2017 8:30:14 AM etan
3/20/2017 3:09:50 PM etan
3/20/2017 2:00:21 PM etan \\SEA2-ACS-01
3/20/2017 11:13:01 AM etan \\SEA1-ACS-01
3/20/2017 10:07:26 AM etan \\SEA2-ACS-01
3/20/2017 6:09:17 AM etan \\SEA2-ACS-01
3/16/2017 1:12:49 PM etan \\SEA1-ACS-01
3/16/2017 12:48:03 PM etan
3/16/2017 11:50:25 AM etan
OUTPUT AS CSV
Get-WinEvent -ComputerName dc-corp-1203 -FilterHashtable @{logname='security';id=4740;data=‘etan’} |
Select-Object -Property timecreated,
@{label='username';expression={$_.properties[0].value}},
@{label='computername';expression={$_.properties[1].value}} |
Export-Csv "$home\Downloads\ad_lockout_user_$(get-date -f MMddyyyy_hhmmss).csv" –NoTypeInformation
Install-Module -Name PSCredentialManager
Get-CachedCredential -ComputerName dc-corp-1203
OUTPUT AS TABLE
.\Get-MS17010.ps1 1.1.1.1 | ft -Wrap
query user /server:dc-corp-1203
- Use session ID to remotely logoff a user
logoff 2 /server:dc-corp-1203
https://stackoverflow.com/a/18193461
Get-WinEvent -ComputerName erpts-corp-1201 -FilterHashtable @{logname='system';id=1131} -MaxEvents 50 | FL *
- LogNames:
- Application
- System
- Security
- Setup
- …
Get-WinEvent - PowerShell - SS64.com Get-WinEvent
NOTE: Get-EventLog
deprecated in favor of Get-WinEvent
Get-EventLog -List
Get-EventLog -LogName "System" -EntryType Error -Newest 10
Get-EventLog -LogName "System" -EntryType Error | where {$_.eventID -eq 10010}
Get-WinEvent -LogName System -MaxEvents 10 | FL *
OR
Get-WinEvent -FilterHashTable @{LogName="Microsoft-Windows-TerminalServices-Printers/Admin"} -maxevents 25 | FL *
Get-WinEvent -ComputerName $env:computername -FilterHashtable @{LogName="Application","Security","System";Level=1, 2, 3;StartTime=(get-date).AddDays(-1); EndTime=(get-date).AddHours(-1)}
Get-WinEvent -ComputerName $env:computername -FilterHashtable @{LogName="Application","Security","System";Level=1, 2, 3;StartTime=(get-date).AddDays(-7); EndTime=(get-date).AddHours(-1)}
Get-WinEvent -ComputerName $env:computername -FilterHashtable @{LogName="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";StartTime=(get-date).AddDays(-7); EndTime=(get-date).AddHours(-1)}
Note
* May need to remove -ComputerName $env:computername
to run command on Windows 7
* Ditto on –NoTypeInformation
flag for CSV output
gpresult /Scope User /v
gpresult /Scope Computer /v
gpresult /h $home\Downloads\gpresult_$(get-date -f MMddyyyy_hhmmss).html /f
PSv2.0
iex (New-Object Net.WebClient).DownloadString('https://git.io/v9rJg’)
PSv3.0+
iwr https://gallery.technet.microsoft.com/scriptcenter/Get-LoggedOnUser-Gathers-7cbe93ea/file/85728/5/Get-LoggedOnUser.ps1 -OutFile Get-LoggedOnUser.ps1
3 ways to download files with PowerShell
Invoke-Command -ComputerName "erp-corp-1201" -ScriptBlock {ipconfig /all} -Credential CORP\lstephens
OR
Enter-PSSession -ComputerName "erp-corp-1201" -Credential CORP\lstephens
Test-NetConnection erp-corp-1201 -Port 3389 -InformationLevel Quiet
netstat -ano
Import-Module PSWindowsUpdate
Get-WUServiceManager
Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false
Get-WUInstall -MicrosoftUpdate -IgnoreUserInput -AcceptAll -IgnoreReboot -Verbose
Powershell for automatize windows update and program installation | WindowsBBS
Get-WUList
PsExec.exe @MyListFile.txt -d wuauclt /reportnow
Get-ADComputer -Filter * -SearchBase "OU=Domain Controllers,DC=corp,DC=rhapsody,DC=com"
Get-ADComputer -Filter * -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion -Wrap –Auto
Get-ADComputer -Filter * | Select-Object -Property Name
&& Export as TXT
| Out-File $home\Downloads\domainPCs.txt
OR
| Out-File -FilePath "$ScriptPath\$(get-date -f "yyyy.MM.dd-HH.mm.ss").txt"
(gc C:\Users\lstephens\Downloads\domainPCs.txt)| % {$_.trim()} | sc C:\Users\lstephens\Downloads\domainPCs.txt
How to trim all the lines in a file in powershell - Stack Overflow Get-Content Set-Content
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} |
sls Stephens
One-Liner: Get a List of AD Users Password Expiry Dates – PoSh Chap
Get-ADOrganizationalUnit -Filter * -Properties CanonicalName | Select-Object -Property CanonicalName
Get-ADUser -SearchBase "OU=Users_and_Groups,DC=corp,DC=rhapsody,DC=com" -Filter * -Properties DisplayName, EmailAddress, Title | select DisplayName, EmailAddress, Title | Export-CSV "$home\Downloads\ad_users_$(get-date -f MMddyyyy_hhmmss).csv"
Get-ADUser -Filter {(Name -like "*")} -SearchBase "OU=TermedOU,DC=corp,DC=rhapsody,DC=com"
Get-ADUser -Filter {(Name -like "*")} -SearchBase "OU=TermedOU,DC=corp,DC=rhapsody,DC=com" | Disable-ADAccount
Get-ADUser -Filter {(Enabled -eq $true)} -SearchBase "OU=TermedOU,DC=corp,DC=rhapsody,DC=com"
Get-ADObject -Filter {Name -Like "*"} -Searchbase "OU=ProductionMicrosoftServers,DC=corp,DC=rhapsody,DC=com" | Select-Object Name
Get-ADObject -Filter { OperatingSystemVersion -like "*5.2*" } -Searchbase "OU=ProductionMicrosoftServers,DC=corp,DC=rhapsody,DC=com" | Select-Object Name
w32tm /query /source
Local CMOS Clock >> Should be MS or NIST
w32tm /config /manualpeerlist:"time.nist.gov" /syncfromflags:manual /reliable:yes /update
net stop W32Time
net start W32Time
w32tm /resync
w32tm /query /status
Leap Indicator: 0(no warning)
Stratum: 2 (secondary reference - syncd by (S)NTP)
Precision: -23 (119.209ns per tick)
Root Delay: 0.0302976s
Root Dispersion: 7.7754862s
ReferenceId: 0x808A8C2C (source IP: 128.138.140.44)
Last Successful Sync Time: 11/22/2017 2:19:41 PM
Source: time.nist.gov
Poll Interval: 10 (1024s)
w32tm /query /source
time.nist.gov
How do I force sync the time on Windows Workstation or Server? - Server Fault how to sync windows time from a ntp time server in command - Stack Overflow
Get-SmbConnection
get-service | foreach {Write-Host NT Service\$($_.Name)}
Get-WindowsFeature | ? Installed
$workingDir= (Get-Item -Path ".\" -Verbose).FullName
OR
$workingDir = (Get-Location).path
Get-WebConfiguration system.applicationHost/applicationPools/* /* | where {$_.ProcessModel.identitytype -eq 'ApplicationPoolIdentity'} | foreach {Write-Host IIS APPPOOL\$($_.Name)}
get-vm | foreach {Write-Host NT VIRTUAL MACHINE\$($_.Id) - $($_.VMName)}
Filter by KB
Get-WmiObject -Class "win32_quickfixengineering" | sls KB3159706
Export as CSV
Get-WmiObject -Class "win32_quickfixengineering" | Export-Csv -Path $home\Downloads\updates.csv –NoTypeInformation
logman import -n "CPU Utilization" -xml perfmon_cpu.xml
repadmin /showrepl * /csv | ConvertFrom-Csv | Out-GridView
Active Directory Replication Cmdlets vs. Repadmin – PoSh Chap
function which($name)
{
Get-Command $name | Select-Object -ExpandProperty Definition
}
some-command | Measure-Object -line -word -character
Windows Powershell: Unix Equivalents in Powershell
netsh nps show client
dsquery * forestroot -gc -attr distinguishedName -scope subtree -filter "(|(cn=*\0ACNF:*)(ou=*OACNF:*))"
Directory Admin: Find CNF objects in Active Directory
Install RSAT to Import and Install Modules
Install-Module -Name DSCEA
Generate MOF file
Discover SMB1 in your environment with DSCEA – Microsoft Datacenter blog by Ralph Kyttle
Start-DSCEAscan -MofFile .\localhost.mof -InputFile C:\Users\lstephens\Downloads\domainPCs.txt
Get-EventLog System | Where-Object {$_.EventID -eq "1074" -or $_.EventID -eq "6008" -or $_.EventID -eq "1076"} | ft Machinename, TimeWritten, UserName, EventID, Message -AutoSize -Wrap
- Export
Get-EventLog System | Where-Object {$_.EventID -eq "1074" -or $_.EventID -eq "6008" -or $_.EventID -eq "1076"} | Select-Object -Property Machinename, TimeWritten, UserName, EventID, Message | Export-Csv "$home\Downloads\shutdown_events_$(Get-Date -f MMddyyyy_hhmmss).csv" -NoTypeInformation
Get-WMIObject Win32_Logicaldisk -filter "deviceid='C:'" -ComputerName dc-corp-1102 |
Select PSComputername,DeviceID,
@{Name="SizeGB";Expression={$_.Size/1GB -as [int]}},
@{Name="FreeGB";Expression={[math]::Round($_.Freespace/1GB,2)}}
Get-GPO -Name 'User Workstation Standards GPO' -Domain corp.rhapsody.com
Get-GPO -guid 894AD25C-78CC-40F9-8D53-A079704AC384 -Domain corp.rhapsody.com
OUTPUT:
DisplayName : WSUS
DomainName : corp.rhapsody.com
Owner : CORP\Domain Admins
Id : 894ad25c-78cc-40f9-8d53-a079704ac384
GpoStatus : AllSettingsEnabled
Description :
CreationTime : 11/30/2016 2:07:00 PM
ModificationTime : 11/15/2017 10:59:34 AM
UserVersion : AD Version: 0, SysVol Version: 0
ComputerVersion : AD Version: 10, SysVol Version: 10
WmiFilter :
ps | clip
bluesoul comments on ITT:Handy Commands You Might Not Know
Test-ComputerSecureChannel [-Repair]
mjwinger1 comments on ITT:Handy Commands You Might Not Know
netstat -ano 1 | findstr 443
Trying to track down what process on your windows machine is trying to get out to the internet in your firewall logs? Replace 443 with whatever you like, source/destination port or IP, or process ID if you just want to see all the network connections that a certain process has. the 1 in there keeps netstat refreshing every 1 second
sysadmin__ comments on ITT:Handy Commands You Might Not Know
echo n | gpupdate /force && shutdown -r -t 0
NtGuru comments on ITT:Handy Commands You Might Not Know
Get-ADComputer -Filter * -SearchBase "OU=Clients,OU=NorthAmerica,DC=Contoso,DC=Com" | For-Each { Invoke-GPUpdate -Computer $_.Name -Force }
Lets you force an update against an OU remotely. We use it when rolling new policies office by office. For example something like LAPS; Add the LAPS policy to office's computer OU, run the above. If you're doing it after hours it even has the -Boot option that gpupdate has.
omers comments on ITT:Handy Commands You Might Not Know
Get-WmiObject win32_operatingsystem -ComputerName the_name_of_the_remote_computer | select csname, @{label='LastBootupTime' ;EXPRESSION={$_.ConvertToDateTime($_.lastbootuptime)}}
Garetht comments on ITT:Handy Commands You Might Not Know
whoami
whoami /claims
whoami /user
whoami /groups
OR
whoami /all
Gary_Chan1 comments on ITT:Handy Commands You Might Not Know
Set-DnsClientServerAddress -ServerAddresses x.x.x.x,y.y.y.y
Set-DNSClientServerAddress –interfaceIndex $_.ifIndex –ServerAddresses ("10.0.0.1","10.0.0.2") -Verbose
openfiles /query /s \\dc-corp-1203 /v
OUTPUT
Hostname ID Accessed By Type #Locks Open Mode Open File (Path\executable)
=============== ======== ==================== ========== ========== =============== ================================================================================
dc-corp-1203.co 67126374 lstephens Windows 0 Write + Read \srvsvc
dc-corp-1203.co 53697025 adsvc Windows 0 Read C:\Windows\Netwrix Auditor\Event Collection\226eae05-e03d-43a0-81fe-daacf1730261
dc-corp-1203.co 12081848 adsvc Windows 0 Read C:\Windows\NETWRIX AUDITOR\EVENT COLLECTION
dc-corp-1203.co 46977537 adsvc Windows 0 Read C:\Windows\NETWRIX AUDITOR\EVENT COLLECTION
dc-corp-1203.co 67115419 adsvc Windows 0 Write + Read \EVENTLOG
dc-corp-1203.co 28858409 adsvc Windows 0 Write + Read \EVENTLOG
dc-corp-1203.co 28185724 RHAP-WMRM-PROD-$ Windows 0 Write + Read \samr
dc-corp-1203.co 46976285 WMRM-PROD-1205$ Windows 0 Write + Read \samr
$Computername = read-host "Enter computername"
Invoke-Command -ComputerName $Computername -ScriptBlock {Get-SmbOpenFile | Select ClientUserName,@{N="Source";E={(Resolve-DnsName $_.ClientComputerName).NameHost}}}
OR w/hard-coded computer name:
Invoke-Command -ComputerName dc-prod-1201 -ScriptBlock {Get-SmbOpenFile | Select ClientUserName,@{N="Source";E={(Resolve-DnsName $_.ClientComputerName).NameHost}}}
Need some help in modifying Powershell script to show open files in File server