Power Shell/CLI Study and Self Learning
Script Self Learning
Grammar
Variable
1. Start with $, such as $a
Method 1:
$a = "This is a string"
$b = 123
$c = 0.125
Method 2
Set-Variable var 100
Set-Variable var1 ”test“
Set-Variable va2 800
2.get variable
get-variable var #Single variable
get-variable var* #Mutiple variable
3.clear variable
clear-variable var
4.Delete variable
remove-variable var
5.More variable
$a = "This is the 1st string"
$b = "This is the 2nd string"
$c = $a + " and " + $b
$c
Result: This is the 1st string and This is the 2nd string
6. variable with commands
$date = Get-Date #Current Date
$date.AddDays(3) #Adding 3 days on current date
7. special variable
$^
$$
$_
$?
$Args
$Error
$Foreach
$Home
$Host
$Input
$LastExitCode
$Matches
$PSHome
$profile
$StackTrace
$Switch
constant
Updating soon
array
Updating soon
function
Updating soon
Common Commands
Get-
1.Get-Command
2.Get-Process
3.Get-Help
4.Get-History
5.Get-Job
6.Get-FormatData
7.Get-Event
8.Get-Alias
9.Get-Culture
10. Get-Date
11. Get-Host
12.Get-Member13.Get-Random
14.Get-UICulture
15.Get-Unique
16.Get-Variable
17.Get-EventLog
18.Get-ChildItem
19.Get-Content
20.Get-ItemProperty
21.Get-WmiObject
22.Get-Location
23.Get-PSDrive
24.Get-Item
25.Get-Process
26.Get-Service
27.Get-Transaction
28.Get-ExecutionPolicy
Set-
1.Set-Alias2.Set-PSDebug
3.Set-StrictMode
4.Set-Date
5.Set-Variable
6.Set-PSBreakpoint
7.Set-Location
8.Set-Item
9.Set-Service
10.Set-Content
11.Set-ItemProperty
12.Set-WmiInstance
13.Set-ExecutionPolicy
Write-
1.Write-Host
2.Write-Progres
3.Write-Debug
4.Write-Verbose
5.Write-Warning
6.Write-Error
7.Write-Output
8.Write-EventLog
Day to Day Power Shell Commands
Push AD update
Start-ADSyncSyncCycle -PolicyType Initial
#To initiate a full sync cycle, used in most situations
Start-ADSyncSyncCycle -PolicyType Delta
#Manually run a sync cycle, rarely used
Import the ADSync module: Import-Module ADSync
#https://docs.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-sync-feature-schedule
GPO push update
Invoke-GPUpdate -Computer PMNT-WS-IT-03 -RandomDelayinMinutes 0
Get ADUser/ADComputer/Disabled user and export
Get-ADUser -SearchBase 'OU=Enercare,OU=Montreal,OU=Quebec,OU=North America,OU=CP360 Users,DC=CP-360,DC=com' -Filter *|ft Name, DistinguishedName -Autosize
Get-ADUser -SearchBase 'OU=CP360 Users,DC=CP-360,DC=com' -Filter *|select-object -property Name,Distingushename|Export-CSV "C:\Temp\Users.csv" –NoTypeInformation
Search-ADAccount –AccountDisabled –UsersOnly |ft Name, DistinguishedName -Autosize | Export-CSV “C:\Temp\DisabledUsers.txt” –NoTypeInformation
Get-ADComputer -Filter * -Property *|Select-Object Name|Export-CSV “C:\Temp\Computers.CSV” -NoTypeInformation
#OU=Enercare,OU=Montreal,OU=Quebec,OU=North
America,OU=CP360 Users,DC=CP-360,DC=com
Add ADUser to ADGroupMember
Get-ADUser -SearchBase 'OU=Enercare,OU=Montreal,OU=Quebec,OU=North America,OU=CP360 Users,DC=CP-360,DC=com' -Filter *|ForEach-Object {Add-ADGroupMember -Identity ‘FG_SSL_Agent_AmWater’ -Members $_}
Set-ADAccountPassword/other attribute in OU
Get-ADUser -SearchBase 'OU=Enercare,OU=Montreal,OU=Quebec,OU=North America,OU=CP360 Users,DC=CP-360,DC=com' -Filter *|Set-ADAccountPassword -Reset -NewPassword "Montreal123$
set-aduser -identity susan -Replace @{c="CN";co="China";countrycode=156}
Set-ADAccountPassword individually or mutiple user from files
Get-Content C:\users.txt|Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "Montreal123$" -Force)
#C:\users.txt
CN=test2 test2,OU=Enercare,OU=Montreal,OU=Quebec,OU=North America,OU=CP360 Users,DC=CP-360,DC=com
Search all inactive users within 180 days and move to certain OU then disable
Get-ADUser -Filter '(PasswordLastSet -lt $d) -or (LastLogonTimestamp -lt $d)' -Properties PasswordLastSet,LastLogonTimestamp|ForEach-Object {Move-ADObject -Identity $_ -TargetPath 'OU=Disabled Users,OU=CP360 Users,DC=CP-360,DC=com'}
Find Unused ADUser Accounts
$curDate = Get-Date
$maxDate = $curDate.AddYears(-1)
Get-ADUser -Filter * -Properties * | ? { $_.LastLogonDate -lt $maxDate } | Select-Object Name, Created, LastLogonDate | Sort-Object LastLogonDate
Get InstalledApps
$appFolder = "C:\Info\"
If (!(Test-Path $appFolder))
{
New-Item -ItemType Directory -Force -Path $appFolder
}
Get-WMIObject Win32_Product -ComputerName localhost | `
Select -ExpandProperty Caption | `
Sort-Object | `
Out-File "$($appFolder)\installed-apps.txt"
Move UserProfile To Share
# 1) Run once if replacement is planned (may take a while)
# 2) Run again just before making the replacement (will be very fast, because it will only update modified files)
$computerName = "ABC-HelpDesk"
$userName = "ABCsupport"
$shareLocation = "localhost\fs1\swap"
# sec : copy NTFS permissions
# mir : in addition to copying, it will also delete whatever that isn't in source directory as to 'mirror' the structure
# w: wait seconds
# r: retry count
Robocopy \\$computerName\C$\users\$userName\Desktop \\$shareLocation\$userName\Desktop /mir /w:0 /r:0
# Robocopy \\$computerName\C$\users\$userName\Favorites \\$shareLocation\$userName\Favorites /mir /w:0 /r:0
# Robocopy \\$computerName\C$\users\$userName\Documents \\$shareLocation\$userName\Documents /mir /w:0 /r:0
# Robocopy \\$computerName\C$\users\$userName\Pictures \\$shareLocation\$userName\Pictures /mir /w:0 /r:0
# Robocopy \\$computerName\C$\users\$userName\Music \\$shareLocation\$userName\Music /mir /w:0 /r:0
# Robocopy \\$computerName\C$\users\$userName\AppData\Local\Microsoft\Outlook \\$shareLocation\$userName\AppData\Local\Microsoft\Outlook /mir /w:0 /r:0
# It is not recommended to put .pst files on shares, because disconnections to the share while .pst file is open will likely cause corruption
# And disconnections can happen frequently for whatever reasons
# Script for moving user profile onto share for redirection
# https://www.reddit.com/r/PowerShell/comments/4qnwvv/simple_helpdesk_scripts/
Enable Active Directory Recycle Bin
Get-ADOptionalFeature “Recycle Bin Feature” | select-object name, EnabledScopes
Exchange Shell
Installing Exchange Online
Set-ExecutionPolicy RemoteSigned
Install-Module -Name ExchangeOnlineManagement
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName admin@domain.com
Enable Search-Mailbox in Exchange Online
#https://www.exchangeonline.in/search-mailbox-in-exchange-online/
Get Distro's Owner
Enable Exchange Online
Get-distributiongroup -resultsize unlimited | Select name, grouptype, managedby | Export-CSV c:\test.csv
Trace number of message been sent to all Distors in certain days
Enable Exchange Online
Get-MessageTrace -StartDate 09/23/2021 -EndDate 10/03/2021 -Status Expanded | Group-Object -Property RecipientAddress | Select name,count | Sort count -desc
#-StartDate (Get-Date).Adddays(-10) -EndDate (Get-Date)
#Expanded: When E-mail message is sent to a Distribution Group
Enable Specific Mobile Device
Install Exchange Online
Get-MobileDevice -Mailbox "Email Address" | fl FriendlyName, Identity, DeviceAccessState, DeviceID
Option: Remove-MobileDevice -Identity "Identity"
Set-CASMailbox -Identity "Email Address" -ActiveSyncAllowedDeviceIDs @{add='DeviceID'}
Removing: Set-CASMailbox -Identity "Email Address" -ActiveSyncBlockedDeviceIDs @{remove='DeviceID'}
Some CLI Commands
Add ADUser
dsadd user “cn=John Smith,OU=Enercare,OU=Montreal,OU=Quebec,OU=North America,OU=CP360 Users,DC=CP-360,DC=com” -disabled no –pwd Montreal123! -mustchpwd No -memberof cn=group,ou=SouthEmployees,dc=northwindtraders,dc=com -acctexpires never
RDP session termination
Get session ID: qwinsta /server:wowhvdev1
Kill session" rwinsta /server:wowhvdev1 ID
Check/Modify all delegation control permission
Dsacls "DC=Contoso,DC=com"
Create Local Use
net user "Rohan Plummer" "Jamaica123!" /add
WMIC USERACCOUNT WHERE Name='Rohan Plummer' SET PasswordExpires=FALSE
net user "Syreka Lewis" "Jamaica123!" /add
WMIC USERACCOUNT WHERE Name='Syreka Lewis' SET PasswordExpires=FALSE
Reset individually password in domain from WS with DC premission
net user test1.test1 Montreal123! /domain -actiive: yes
Delete shared credential
net use * /del
Comments