You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#list powershell version and installed modules Get-Host|Select-Object Version
$PSVersionTable.PSVersionGet-InstalledModule#bypass execution policy to run scriptpowershell.exe-executionpolicy bypass .\script.ps1
Get-Content .\script.ps1 |powershell.exe-noprofile -#create credential object$cred=Get-Credential#aliases to avoid when scripting and what to use instead
cd =Set-Location
ls =Get-ChildItem
gci =Get-ChildItem
mv =Move-Item
rm =Remove-Item#grep output
command | findstr -i "string"#new-alias grep findstr#command | grep "string"#check variable type$var.GetType()
#create array$array=@()
#append to array (actually creates new array with value added at end)$array+="value"#search array$array-contains"value"#sort array$array=$array|Sort-Object#remove items from array - create new one$no_dcu_workstations=@()
foreach ($rowin$no_dcu_list) {
if ($row-notlike"ORG*") {
$no_dcu_workstations+=$row
}
}
#generate current timestampGet-Date-Format yyyyMMddHHmm
$timestamp=Get-Date-Format yyyyMMddHHmmss
$date=Get-Date-Format yyyyMMdd
Environment Variables
#list all environment variables
ls env:
dir env:
gci env:
Get-ChildItem env:
#update environment variable just for session#https://stackoverflow.com/questions/714877/setting-windows-powershell-environment-variables$env:Path+=";C:\Program Files\GnuWin32\bin"#set environment variable persistently
[System.Environment]::SetEnvironmentVariable('ResourceGroup','AZ_Resource_Group')
$new_path=$env:Path+=";C:\Program Files (x86)\Vim\vim82"
[System.Environment]::SetEnvironmentVariable('Path',$new_path)
#split path environment variable into human readable lines$env:path-split';'#update environment variable persistently (across reboots)
[Environment]::SetEnvironmentVariable("Path",$env:Path+";C:\Program Files\7-zip\", [System.EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("Path",$env:Path+";C:\utils","Machine")
[Environment]::SetEnvironmentVariable("INCLUDE",$env:INCLUDE, [System.EnvironmentVariableTarget]::User)
[Environment]::SetEnvironmentVariable("Path",$env:Path+";%userprofile%\.local\bin","User")
#split string into an array based on specific character$str=Get-Content .\anaconda_users_shared_folder.csv |findstr -i "aawet"$arr=$str.split('\\')
#get filename after last backslash$filename.Split('\')[-1]
#remove / replace character in string$str-replace'"',''
Computer and Operating System Info
#check last boot time on a serverGet-CimInstance-ClassName win32_operatingsystem -ComputerName $pc| select csname, lastbootuptime
#get os version of remote computerGet-WmiObject Win32_OperatingSystem -ComputerName "comp_name"|Select-Object PSComputerName, Caption, OSArchitecture, Version, BuildNumber
#get serial number of PCGet-CimInstance-ComputerName pc_name win32_bios |Select-Object SerialNumber
Get-WmiObject win32_bios | select Serialnumber
#windows server initial security checklistGet-WindowsFeature|Where-Object {$_.Installed-eq"True"}
Get-SmbShare#check for non-essentialGet-SmbShare|Get-SmbShareAccess#check for non-essential Full rightsGet-LocalUser#check for non-essentialGet-LocalGroupMember Administrators #check for non-essentialGet-NetTCPConnection#or "netstat -an" or "netstat -ban"Get-CimInstance Win32_StartupCommand |Select-Object Name, command, Location, User
Get-Item-Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run'Get-Item-Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce'Get-Item-Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'Get-Item-Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce'Get-WmiObject-Class Win32_Product |Select-Object Vendor, Name, Version |ft
Get-WmiObject-Class Win32_Product |Where-Object {$_.Vendor|Select-String-notmatch"Microsoft Corporation","Intel Corporation"} |Select-Object Vendor, Name, Version |ft
Admin Tools
#list installed admin toolsGet-WindowsCapability-Name RSAT*-Online |Select-Object-Property State, Name, DisplayName
#install admin toolsAdd-WindowsCapability-Name "Rsat.ActiveDirectory*"-Online
Get-WindowsCapability-Name RSAT*-Online |Add-WindowsCapability-Online
#list Windows Optional FeaturesGet-WindowsOptionalFeature-Online |Select-Object FeatureName, State
#install windows featureEnable-WindowsOptionalFeature-Online -FeatureName Microsoft-Hyper-V -All -NoRestart
#check disk used space of a folder (du -s ./)$target_folder='c:\utils'"{0:N2} GB"-f ((Get-ChildItem$target_folder-Recurse |Measure-Object-Property Length -Sum -ErrorAction Stop).Sum /1GB)
#check disk space and last modified details for subfolders$target_folder='c:\utils'$data_coll=@()
Get-ChildItem-force $target_folder-ErrorAction SilentlyContinue |? { $_-is [io.directoryinfo] } |% {
$len=0Get-ChildItem-recurse -force $_.fullname-ErrorAction SilentlyContinue |% { $len+=$_.length }
$folder_name=$_.fullname$folder_size='{0:N2}'-f ($len/1Gb)
$creation_time=$_.CreationTime$last_access_time=$_.LastAccessTime$last_write_time=$_.LastWriteTime$data_object=New-Object PSObject
Add-Member-inputObject $data_object-memberType NoteProperty -name "folder_name"-value $folder_nameAdd-Member-inputObject $data_object-memberType NoteProperty -name "folder_size_Gb"-value $folder_sizeAdd-Member-inputObject $data_object-memberType NoteProperty -name "creation_time"-value $creation_timeAdd-Member-inputObject $data_object-memberType NoteProperty -name "last_access_time"-value $last_access_timeAdd-Member-inputObject $data_object-memberType NoteProperty -name "last_write_time"-value $last_write_time$data_coll+=$data_object
}
$data_coll|Out-GridView-Title "Folder Details"$data_coll|Export-Csv-NoTypeInformation .\20210805-folder-details.csv
#get disk space details in GB on a server# Get-WmiObject -Class Win32_LogicalDisk | ? {$_. DriveType -eq 3} | select DeviceID, {$_.Size /1GB}, @{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}, @{n="UsedSpace";e={[math]::Round(($_.Size - $_.FreeSpace)/1GB,2)}}}Get-WmiObject-Class Win32_LogicalDisk |? {$_. DriveType -eq3} | select DeviceID, {$_.Size/1GB},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,0)}},@{n="UsedSpace";e={[math]::Round(($_.Size-$_.FreeSpace)/1GB,0)}}
Invoke-Command-ComputerName $server_list-ScriptBlock {
Get-WmiObject-Class Win32_LogicalDisk |? {$_. DriveType -eq3} | select DeviceID, {$_.Size/1GB},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,0)}},@{n="UsedSpace";e={[math]::Round(($_.Size-$_.FreeSpace)/1GB,0)}}
}
foreach ($serverin$server_list) {
Get-WmiObject-Class Win32_LogicalDisk -ComputerName $server|? {$_. DriveType -eq3} |Where-Object {$_.DeviceID-like"C*"} |Select-Object@{Name="Name"; Expression={$server}}, DeviceID, {$_.Size/1GB}, {$_.FreeSpace/1GB}
}
Get-VolumeGet-Volume|Where-Object {$_.DriveLetter-eq"C"} |Select-Object {$_.SizeRemaining/1GB}
#get total disk space - capacity and amount used on a machineInvoke-Command-ComputerName $server_list-ScriptBlock {
$disks=Get-WmiObject-Class Win32_LogicalDisk |? {$_. DriveType -eq3} | select DeviceID,@{n="disk_size";e={[math]::Round($_.Size/1GB,0)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,0)}},@{n="UsedSpace";e={[math]::Round(($_.Size-$_.FreeSpace)/1GB,0)}}
foreach ($din$disks) {
$total_disk_used+=$d.UsedSpace$total_disk_capacity+=$d.disk_size
}
$obj_properties=@{ total_disk_capacity="$total_disk_capacity"; total_disk_used="$total_disk_used"}
New-Object PsObject -Property $obj_properties
}
Files
#if path existsif (Test-Path-Path $Folder) {
"Path exists!"
} else {
"Path doesn't exist."
}
#download file from URL (wget)Invoke-WebRequest [-UseBasicParsing] -Uri <source>-OutFile <destination>#unblock file downloaded from InternetUnblock-File-Path .\file -Confirm:$false#unzip filesGet-Command-Module Microsoft.PowerShell.Archive
ExpandArchive -Path 'c:\utils\tmp\MobaXterm_Portable_v21.2.zip'-DestinationPath 'c:\utils\'Expand-Archive file.zip
#recursively delete folderRemove-Item-Recurse -Force .\tmp
#get last modified date of folder$(Get-ChildItem c:\temp).LastWriteTime
#copy fileCopy-Item source destination
#create shortcut (requires powershell 5+)#https://stackoverflow.com/questions/9701840/how-to-create-a-shortcut-using-powershell$WshShell=New-Object-comObject WScript.Shell
$Shortcut=$WshShell.CreateShortcut("$env:appdata\Microsoft\Windows\Start Menu\Programs\Windows Terminal.lnk")
$Shortcut.TargetPath="C:\utils\WindowsTerminal\WindowsTerminal.exe"$Shortcut.Save()
#create run as admin shortcut$WshShell=New-Object-comObject WScript.Shell
$Shortcut=$WshShell.CreateShortcut("$env:appdata\Microsoft\Windows\Start Menu\Programs\Windows Terminal (Admin).lnk")
$Shortcut.TargetPath="C:\utils\WindowsTerminal\WindowsTerminal.exe"$Shortcut.Save()
$file="$env:appdata\Microsoft\Windows\Start Menu\Programs\Windows Terminal (Admin).lnk"$bytes= [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] =$bytes[0x15] -bor0x20#set byte 21 (0x15) bit 6 (0x20) ON (Use -bor to set RunAsAdministrator option and -bxor to unset)
[System.IO.File]::WriteAllBytes($file,$bytes)
#create symbolic linkNew-Item-ItemType SymbolicLink -Path "C:\temp"-Name "calc.lnk"-Value "c:\windows\system32\calc.exe"#create multiple 2GB random files$out=new-object byte[] 2048000000; (New-Object System.Random).NextBytes($out);
for ($i=1; $i-le$var_count; $i++) {[IO.File]::WriteAllBytes("C:\utils\tmp\jmtestfile$i.txt",$out)}
#get detailed file properties including DLL version$pc="pc_name"
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("\\${pc}\c$\windows\system32\ntoskrnl.exe") |fl
Registry
#REGISTRY - https://blog.netwrix.com/2018/09/11/how-to-get-edit-create-and-delete-registry-keys-with-powershell/#WARNING - registry is loaded into memory when powershell session starts and I don't know how to update it without starting a new powershell window#get registry keyGet-Item-Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem"#get registry dword valueGet-ItemProperty-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\'-Name EnableLUA |Select-Object EnableLUA
#search registryGet-ChildItem-Path hkcu:\ -recurse -ErrorAction SilentlyContinue |Where-Object {$_.Name-like"*Netwrix*"}
#set registry valueSet-ItemProperty-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power'-Name 'HiberbootEnabled'-value '0'Set-ItemProperty-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem'-Name 'LongPathsEnabled'-Value '1'#new registry keyNew-Item-Path "HKCU:\dummy"-Name NetwrixKey
#new registry parameterNew-ItemProperty-Path "HKCU:\dummy\NetwrixKey"-Name "NetwrixParam"-Value "NetwrixValue"-PropertyType "String"#delete registry keyRemove-Item-Path "HKCU:\dummy\NetwrixKey"-Recurse
#delete registry parameterRemove-ItemProperty-Path "HKCU:\dummy\NetwrixKey"-Name "NetwrixParam"
Services
#show computers with specific service disabled# $service_name = "winrm" #-StartupType Automatic$service_name="remoteregistry"foreach ($compin$computers) {
if (Test-Connection-BufferSize 32-Count 1-ComputerName $comp.Name-Quiet) {
try {
#Write-Output($comp.Name)$svc=Get-Service$service_name-ComputerName $comp.Nameif ($svc.StartType-eq'Disabled') {
Set-Service-Name $service_name-ComputerName $comp.Name-StartupType Manual
$svc=Get-Service$service_name-ComputerName $comp.NameWrite-Output("UPDATED - $($comp.Name)$($svc.Name) set StartType to $($svc.StartType) - current status: $($svc.Status)")
}
} catch {
Write-Output("$comp - $($Error[0].Exception)")
}
} else {
Write-Output("DOWN - $($comp.Name)")
}
}
$ou_path="dc=corp,dc=example,dc=com"$computers=@()
$computer_objects=Get-ADComputer-Filter *-SearchBase $ou_pathforeach ($pcin$computers) {
$computers+=$pc.Name
}
$computers=Get-Content pclist.txt
foreach ($compin$computers) {
if (Test-Connection-BufferSize 32-Count 1-ComputerName $comp-Quiet) {
try {
#Write-Output($comp.Name)$svc=Get-Service$service_name-ComputerName $compif ($svc.StartType-eq'Disabled') {
Set-Service-Name $service_name-ComputerName $comp-StartupType Manual
$svc=Get-Service$service_name-ComputerName $compWrite-Output("UPDATED - $($comp)$($svc.Name) set StartType to $($svc.StartType) - current status: $($svc.Status)")
}
} catch {
Write-Output("$comp - $($Error[0].Exception)")
}
} else {
Write-Output("DOWN - $($comp)")
}
}
#how to start a remote service (https://devblogs.microsoft.com/scripting/powertip-use-poweshell-to-start-service-on-remote-machine/)#Get-Service -Name bits -ComputerName RSLAPTOP01 | Start-service will try starting on local machine; must use | Set-Service -Status Running$service_name="winrm"foreach ($compin$computers) {
Write-Output($comp)
$svc=Get-Service$service_name-ComputerName $compSet-Service-Name $service_name-ComputerName $comp-StartupType Automatic
Get-Service$service_name-ComputerName $comp|Set-Service-Status Running
$svc=Get-Service$service_name-ComputerName $compWrite-Output("UPDATED - $($comp)$($svc.Name) set StartType to $($svc.StartType) - current status: $($svc.Status)")
}
#how to check service account configured for a service
(Get-WmiObject Win32_Service -ComputerName $env:COMPUTERNAME-Filter "Name='$serviceName'").StartName
#how to find service accounts across multiple computers that aren't LocalSystem or "NT Authority\*"Invoke-Command-ComputerName $workstations-ScriptBlock {
$svcs= (Get-WmiObject Win32_Service)
foreach ($svcin$svcs) {
if (($svc.StartName-NotContains"LocalSystem") -And ($svc.StartName-NotLike"*NT AUTHORITY\*") -And ($svc.StartName-NotLike"")) {
$svc_details=$env:COMPUTERNAME+","+$svc.Name+","+$svc.Caption+","+$svc.StartNameWrite-Output$svc_details
}
}
}
Shared Folders
#get shared folder list on computerget-WmiObject-class Win32_Share -computer computername
#list non-admin, non-printer, shared folder list on computerGet-WmiObject Win32_Share -ComputerName $server|Where-Object {(@('Remote Admin','Default share','Remote IPC') -notcontains$_.Description)}
foreach ($sin$server_list) {
$val=Get-WmiObject Win32_Share -ComputerName $s|Where-Object {(@('Remote Admin','Default share','Remote IPC','Printer Drivers') -notcontains$_.Description) -and ($_.Path-NotLike"*LocalsplOnly")}
$shares_hash.Add($s,$val)
}
#search shared folder contents for valueGet-Childitem-Path C:\ -Include *file_name*-Recurse -ErrorAction SilentlyContinue
#get list of folders on a remote shareGet-ChildItem \\server\share -Recurse -Name -Directory
Active Directory
#get os version of computers from active directory# non-servers #Get-ADComputer -Filter 'operatingsystem -notlike "*server*" -and enabled -eq "true"' `# domain controllers #Get-ADComputer -Filter 'primarygroupid -eq "516"' `# servers that are not DCs #Get-ADComputer -Filter 'operatingsystem -like "*server*" -and enabled -eq "true" -and primarygroupid -ne "516"' `Get-ADComputer-Filter 'enabled -eq "true"'`-Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address,lastLogonDate,whenChanged |Sort-Object-Property OperatingsystemVersion |Select-Object-Property Name,Operatingsystem,OperatingSystemVersion,IPv4Address,lastLogonDate,whenChanged |ft
#get all computers in an OU$ou_path='ou=admins,dc=corp,dc=example,dc=com'Get-ADComputer-Filter *-SearchBase $ou_path#convert arry list of computers to just array of pc names$pcs=@()
#$pc_list = Get-ADComputer -Filter * -SearchBase $ou_path$pc_list=Get-ADComputer-Filter 'Name -like "orgws*"'foreach ($pcin$pc_list) {
$pcs+=$pc.Name
}
#get all users in an OU$ou_path='ou=admins,dc=corp,dc=example,dc=com'Get-ADUser-Filter *-SearchBase $ou_path#convert array list of users to just array of usernames$user_list=Get-ADUser-Filter *-SearchBase $ou_path|Select-Object sAMAccountName
foreach ($userin$user_list) {
$users+=$user.sAMAccountName
}
#function to return full name from AD given the username/sAMAccountNamefunctionget_ad_full_name {
param (
$sAMAccountName
)
$user=Get-ADUser$sAMAccountName|Select-Object Name
return$user.Name
}
#get lastLogonTimeStamp for All Active Users in A.D.Get-ADUser-Filter {enabled -eq$true} -Properties LastLogonTimeStamp |Select-Object@{Name="Username"; Expression={$_.sAMAccountName}}, Name,@{Name="LastLogonTimeStamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy-MM-dd_hh:mm:ss')}}
#get lastLogonTimeStamp for all users in A.D.Get-ADUser-Properties LastLogonTimeStamp |Select-Object@{Name="Username"; Expression={$_.sAMAccountName}}, Name,@{Name="LastLogonTimeStamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy-MM-dd_hh:mm:ss')}}
#get disabled users in A.D.Get-ADUser-Filter {enabled -eq$false}
#get list of all computers in active directory$computers=Get-ADComputer-Filter *-Property *$computers=$computers|Sort-Object#powershell copy group membership to new groupAdd-ADGroupMember-Identity 'New Group'-Members (Get-ADGroupMember-Identity 'Old Group'-Recursive)