├── .DS_Store
├── Add-LocalAdmin.ps1
├── Add-Zip.ps1
├── AlphaFS.dll
├── CSVFileView.exe
├── CSVed.exe
├── Check-Flags.ps1
├── Check-Header.ps1
├── ConvertFrom-Bytes.ps1
├── ConvertTo-Bytes.ps1
├── Copy-File.ps1
├── CopyTo-Image.ps1
├── Create Azure App Registration for use With MS Graph.ps1
├── Create-DesktopPin.ps1
├── Create-DummyFile.ps1
├── Create-LocalUser.ps1
├── Create-Shortcut.ps1
├── Create-ThisPcPin.ps1
├── DailyStatsReport.ps1
├── Decode-Text.ps1
├── DelTempFiles.ps1
├── Delete_Days_Back.ps1
├── Desktop_Management.ps1
├── DiskSpaceGUITool.ps1
├── Disk_Errors.ps1
├── EWSManagedAPI2.2.msi
├── Enable-PSRemoting.ps1
├── Encode-Text.ps1
├── Expand-OU.ps1
├── Expand-ZIPFile.ps1
├── Fix-Spaces.ps1
├── ForceInstallUpdatesRemote.ps1
├── Get-BitLockerInfo.ps1
├── Get-BitLockerKey.ps1
├── Get-BootConfigurationData.ps1
├── Get-ChromeExtension.ps1
├── Get-Clipboard.ps1
├── Get-ComputerShares.ps1
├── Get-FailingDrive.ps1
├── Get-FileSizeOnDisk.ps1
├── Get-Files.ps1
├── Get-Files.ps1 (Robocopy only version)
├── Get-Firewall.ps1
├── Get-FolderACL.ps1
├── Get-FolderAccess.ps1
├── Get-FolderSize.ps1
├── Get-Header.ps1
├── Get-IEVersion.ps1
├── Get-InstalledApps.ps1
├── Get-Lines.ps1
├── Get-LocalAdmin.ps1
├── Get-LoggedOnUser.ps1
├── Get-LogonHistory.ps1
├── Get-LogonStatus.ps1
├── Get-MAC.ps1
├── Get-MailboxContacts.ps1
├── Get-MailboxStats.ps1
├── Get-MappedDrives.ps1
├── Get-Monitor.ps1
├── Get-MyADObject.ps1
├── Get-NetworkShortcut.ps1
├── Get-OfficeVersion.ps1
├── Get-ParameterAliases.ps1
├── Get-PdfText.ps1
├── Get-Powercfg.ps1
├── Get-PrinterClients.ps1
├── Get-PrinterHosts.ps1
├── Get-ProductKey.ps1
├── Get-ProxyAddresses.ps1
├── Get-SKU.ps1
├── Get-SNMPData.ps1
├── Get-SNMPPrinterInfo.ps1
├── Get-ShaHash.ps1
├── Get-ShortPath.ps1
├── Get-Shortcut.ps1
├── Get-User.ps1
├── GithubRestApi.ps1
├── Greenshot.exe
├── How_to_Make_a_PowerShell_Script_Wait_for_a_Specific_Condition.ps1
├── Import-MailboxContacts.ps1
├── LICENSE
├── Logoff-User.ps1
├── MTFv2.ps1
├── New-NetworkShortcut.ps1
├── Out-Menu.ps1
├── PRobocopy.ps1
├── Pulseway_Desktop_Icon.ps1
├── README.md
├── Reboot.ps1
├── Remote-Registry.ps1
├── Remove-LocalAdmin.ps1
├── Remove-NetworkShortcut.ps1
├── SQL_Backup.ps1
├── Save-CSVasExcel.ps1
├── Save-ExcelasCSV.ps1
├── Search-BoardGameGeek.ps1
├── Send-Telegram.ps1
├── Set-Clipboard.ps1
├── Set-Wallpaper.ps1
├── SetDNS.ps1
├── Setup-Network.ps1
├── Show-WifiPasswords.ps1
├── Software_Inventory.ps1
├── Split-Join-Files.ps1
├── Store-Creds.ps1
├── SystemInformation.ps1
├── Take-Ownership.ps1
├── Test-Port.ps1
├── Test-RPC.ps1
├── Twelve_Tools.ps1
├── Write-Object.ps1
├── Write-Progress Example.ps1
├── add-import-export-wifi.ps1
├── beep songs.ps1
├── chromeapp.ps1
├── cht file editor.ps1
├── convert file to bits.ps1
├── copy files keep structure.ps1
├── create_win_admin.ps1
├── diskfree.ps1
├── faster array vs arraylist.ps1
├── faster gci vs robocopy.ps1
├── faster string vs stringbuilder.ps1
├── fastest event log.ps1
├── fastest foreach.ps1
├── fastest null.ps1
├── fastest where.ps1
├── fix_file_path_too_long_subst.ps1
├── fix_file_path_too_long_subst_v2.ps1
├── install fonts v2.ps1
├── install fonts.ps1
├── menu go back example.ps1
├── notnull.ps1
├── ping1.ps1
├── pingt.ps1
├── profile.ps1
├── propmatch.ps1
├── reddit powershell questions.ps1
├── set wallpaper from reddit.ps1
├── sortprop.ps1
├── split csv into multiple files.ps1
├── strikethrough.ps1
├── subinacl.exe
├── system-uptime.ps1
├── touch.ps1
├── upsidedown.ps1
└── youtube-dl.ps1
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangstanthony/PowerShell/df7e9de1bfc0149f6b900ec65679516c5ed7503a/.DS_Store
--------------------------------------------------------------------------------
/Add-LocalAdmin.ps1:
--------------------------------------------------------------------------------
1 | function Add-LocalAdmin {
2 | param (
3 | [string]$comp,
4 | [string]$sam,
5 | [string]$domain = $env:USERDOMAIN
6 | )
7 |
8 | if ($comp -match '^\s*$') {
9 | throw "Comp not found '$comp'"
10 | }
11 |
12 | if ($sam -match '^\s*$') {
13 | throw "Sam not acceptable '$sam'"
14 | }
15 |
16 | ([adsi]"WinNT://$comp/Administrators").add("WinNT://$domain/$sam")
17 | }
18 |
--------------------------------------------------------------------------------
/Add-Zip.ps1:
--------------------------------------------------------------------------------
1 | # http://stackoverflow.com/questions/11021879/creating-a-zipped-compressed-folder-in-windows-using-powershell-or-the-command-l
2 |
3 | # when using in foreach, must sleep -m 500 after every file
4 |
5 | # on conflict, popup will ask to copy and replace
6 |
7 | function Add-Zip {
8 | param (
9 | [string]$sourceFile,
10 | [string]$zipFile
11 | )
12 |
13 | begin {
14 | function Resolve-FullPath ([string]$Path) {
15 | if ( -not ([System.IO.Path]::IsPathRooted($Path)) ) {
16 | # $Path = Join-Path (Get-Location) $Path
17 | $Path = "$PWD\$Path"
18 | }
19 | [IO.Path]::GetFullPath($Path)
20 | }
21 | }
22 |
23 | process {
24 | $sourceFile = Resolve-FullPath $sourceFile
25 | $zipFile = Resolve-FullPath $zipFile
26 |
27 | if (-not (Test-Path $zipFile)) {
28 | Set-Content $zipFile ('PK' + [char]5 + [char]6 + ([string][char]0 * 18))
29 | (Get-Item $zipFile).IsReadOnly = $false
30 | }
31 |
32 | $shell = New-Object -ComObject shell.application
33 | $zipPackage = $shell.NameSpace($zipFile)
34 |
35 | $zipPackage.CopyHere($sourceFile)
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/AlphaFS.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangstanthony/PowerShell/df7e9de1bfc0149f6b900ec65679516c5ed7503a/AlphaFS.dll
--------------------------------------------------------------------------------
/CSVFileView.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangstanthony/PowerShell/df7e9de1bfc0149f6b900ec65679516c5ed7503a/CSVFileView.exe
--------------------------------------------------------------------------------
/CSVed.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangstanthony/PowerShell/df7e9de1bfc0149f6b900ec65679516c5ed7503a/CSVed.exe
--------------------------------------------------------------------------------
/Check-Flags.ps1:
--------------------------------------------------------------------------------
1 | # https://knowledge.zomers.eu/PowerShell/Pages/How-to-control-UserAccountControl-Active-Directory-flags-with-PowerShell.aspx
2 | # https://jackstromberg.com/2013/01/useraccountcontrol-attributeflag-values/
3 | # https://www.reddit.com/r/PowerShell/comments/aldehr/getaduser_filter_not_working/
4 |
5 | function Check-Flags ($sam = $env:USERNAME) {
6 | $uac = [int](([adsisearcher]"samaccountname=$sam").FindOne().Properties.useraccountcontrol | Out-String).Trim()
7 |
8 | if ($uac -eq 0) {
9 | throw 'UAC is 0'
10 | }
11 |
12 | $flags = @{
13 | SCRIPT = 1
14 | ACCOUNTDISABLE = 2
15 | HOMEDIR_REQUIRED = 8
16 | LOCKOUT = 16
17 | PASSWD_NOTREQD = 32
18 | # Note You cannot assign this permission by directly modifying the UserAccountControl attribute. For information about how to set the permission programmatically, see the "Property flag descriptions" section.
19 | PASSWD_CANT_CHANGE = 64
20 | ENCRYPTED_TEXT_PWD_ALLOWED = 128
21 | TEMP_DUPLICATE_ACCOUNT = 256
22 | NORMAL_ACCOUNT = 512
23 | INTERDOMAIN_TRUST_ACCOUNT = 2048
24 | WORKSTATION_TRUST_ACCOUNT = 4096
25 | SERVER_TRUST_ACCOUNT = 8192
26 | DONT_EXPIRE_PASSWORD = 65536
27 | MNS_LOGON_ACCOUNT = 131072
28 | SMARTCARD_REQUIRED = 262144
29 | TRUSTED_FOR_DELEGATION = 524288
30 | NOT_DELEGATED = 1048576
31 | USE_DES_KEY_ONLY = 2097152
32 | DONT_REQ_PREAUTH = 4194304
33 | PASSWORD_EXPIRED = 8388608
34 | TRUSTED_TO_AUTH_FOR_DELEGATION = 16777216
35 | PARTIAL_SECRETS_ACCOUNT = 67108864
36 | }
37 |
38 | $hash = New-Object System.Collections.Specialized.OrderedDictionary
39 | $hash.Add('SAM', $sam)
40 | $hash.Add('UAC', $uac)
41 |
42 | foreach ($key in $flags.Keys) {
43 | if (($uac -band $flags[$key]) -ne 0) {
44 | $hash.Add($key, $true)
45 | } else {
46 | $hash.Add($key, $false)
47 | }
48 | }
49 |
50 | New-Object psobject -Property $hash
51 | }
52 |
53 | # check-flags -sam user1
54 | # SAM : user1
55 | # UAC : 66048
56 | # INTERDOMAIN_TRUST_ACCOUNT : False
57 | # SERVER_TRUST_ACCOUNT : False
58 | # PASSWD_CANT_CHANGE : False
59 | # NORMAL_ACCOUNT : True
60 | # TEMP_DUPLICATE_ACCOUNT : False
61 | # HOMEDIR_REQUIRED : False
62 | # ENCRYPTED_TEXT_PWD_ALLOWED : False
63 | # PARTIAL_SECRETS_ACCOUNT : False
64 | # TRUSTED_FOR_DELEGATION : False
65 | # DONT_EXPIRE_PASSWORD : True
66 | # NOT_DELEGATED : False
67 | # WORKSTATION_TRUST_ACCOUNT : False
68 | # PASSWD_NOTREQD : False
69 | # USE_DES_KEY_ONLY : False
70 | # PASSWORD_EXPIRED : False
71 | # TRUSTED_TO_AUTH_FOR_DELEGATION : False
72 | # MNS_LOGON_ACCOUNT : False
73 | # DONT_REQ_PREAUTH : False
74 | # LOCKOUT : False
75 | # SCRIPT : False
76 | # SMARTCARD_REQUIRED : False
77 | # ACCOUNTDISABLE : False
78 |
--------------------------------------------------------------------------------
/Check-Header.ps1:
--------------------------------------------------------------------------------
1 | # http://learningpcs.blogspot.com/2012/07/powershell-v3-check-file-headers.html
2 | # https://en.wikipedia.org/wiki/List_of_file_signatures
3 | # http://www.garykessler.net/library/file_sigs.html
4 |
5 | function Check-Header {
6 | param (
7 | $path
8 | )
9 |
10 | $path = Resolve-FullPath $path
11 |
12 | # Hexidecimal signatures for expected files
13 | $known = @'
14 | "Extension","Header"
15 | "3gp","66 74 79 70 33 67"
16 | "7z","37 7A BC AF 27 1C"
17 | "8sv","38 53 56 58"
18 | "8svx","46 4F 52 4D nn nn nn nn"
19 | "acbm","46 4F 52 4D nn nn nn nn"
20 | "aif","41 49 46 46"
21 | "aiff","46 4F 52 4D nn nn nn nn"
22 | "anbm","46 4F 52 4D nn nn nn nn"
23 | "anim","46 4F 52 4D nn nn nn nn "
24 | "asf","30 26 B2 75 8E 66 CF 11"
25 | "avi","52 49 46 46 nn nn nn nn "
26 | "bac","42 41 43 4B 4D 49 4B 45"
27 | "bpg","42 50 47 FB"
28 | "cab","4D 53 43 46"
29 | "cin","80 2A 5F D7"
30 | "class","CA FE BA BE"
31 | "cmus","46 4F 52 4D nn nn nn nn"
32 | "cr2","49 49 2A 00 10 00 00 00"
33 | "crx","43 72 32 34"
34 | "cwk","05 07 00 00 42 4F 42 4F"
35 | "cwk","06 07 E1 00 42 4F 42 4F"
36 | "dat","50 4D 4F 43 43 4D 4F 43"
37 | "DBA","BE BA FE CA"
38 | "DBA","00 01 42 44"
39 | "dex","64 65 78 0A 30 33 35 00"
40 | "djvu","41 54 26 54 46 4F 52 4D nn nn nn nn 44 4A 56"
41 | "dmg","78 01 73 0D 62 62 60"
42 | "doc","D0 CF 11 E0 A1 B1 1A E1"
43 | "dpx","53 44 50 58"
44 | "exr","76 2F 31 01"
45 | "fax","46 41 58 58"
46 | "faxx","46 4F 52 4D nn nn nn nn"
47 | "fh8","41 47 44 33"
48 | "fits","53 49 4D 50 4C 45 20 20"
49 | "flac","66 4C 61 43"
50 | "flif","46 4C 49 46"
51 | "ftxt","46 4F 52 4D nn nn nn nn"
52 | "gif","47 49 46 38 37 61"
53 | "ico","00 00 01 00"
54 | "idx","49 4E 44 58"
55 | "iff","41 43 42 4D"
56 | "iff","41 4E 42 4D"
57 | "iff","41 4E 49 4D"
58 | "iff","46 4F 52 4D nn nn nn nn"
59 | "ilbm","46 4F 52 4D nn nn nn nn"
60 | "iso","43 44 30 30 31"
61 | "jpg","FF D8 FF DB"
62 | "lbm","49 4C 42 4D"
63 | "lz","4C 5A 49 50"
64 | "lz4","04 22 4D 18"
65 | "mid","4D 54 68 64"
66 | "mkv","1A 45 DF A3"
67 | "MLV","4D 4C 56 49"
68 | "mus","43 4D 55 53"
69 | "nes","4E 45 53 1A"
70 | "ods","50 4B 05 06"
71 | "ogg","4F 67 67 53"
72 | "PDB","00 00 00 00 00 00 00 00"
73 | "pdf","25 50 44 46"
74 | "png","89 50 4E 47 0D 0A 1A 0A"
75 | "ps","25 21 50 53"
76 | "psd","38 42 50 53"
77 | "rar","52 61 72 21 1A 07 00"
78 | "rar","52 61 72 21 1A 07 01 00"
79 | "smu","53 4D 55 53"
80 | "smus","46 4F 52 4D nn nn nn nn"
81 | "stg","4D 49 4C 20"
82 | "tar","75 73 74 61 72 00 30 30"
83 | "TDA","00 01 44 54"
84 | "tif","49 49 2A 00"
85 | "toast","45 52 02 00 00 00"
86 | "tox","74 6F 78 33"
87 | "txt","46 54 58 54"
88 | "vsdx","50 4B 07 08"
89 | "wav","52 49 46 46 nn nn nn nn"
90 | "wma","A6 D9 00 AA 00 62 CE 6C"
91 | "xar","78 61 72 21"
92 | "yuv","59 55 56 4E"
93 | "yuvn","46 4F 52 4D nn nn nn nn"
94 | "zip","50 4B 03 04"
95 | "epub","50 4B 03 04 0A 00 02 00"
96 | '@ | ConvertFrom-Csv | sort {$_.header.length} -Descending
97 |
98 | $known | % {$_.header = $_.header -replace '\s'}
99 |
100 | try {
101 | # Get content of each file (up to 4 bytes) for analysis
102 | $HeaderAsHexString = New-Object System.Text.StringBuilder
103 | [Byte[]](Get-Content -Path $path -TotalCount 4 -Encoding Byte -ea Stop) | % {
104 | if (("{0:X}" -f $_).length -eq 1) {
105 | $null = $HeaderAsHexString.Append('0{0:X}' -f $_)
106 | } else {
107 | $null = $HeaderAsHexString.Append('{0:X}' -f $_)
108 | }
109 | }
110 |
111 | # Validate file header
112 | # might change .startswith() to -match.
113 | # might remove 'select -f 1' to get all possible matching extensions, or just somehow make it a better match.
114 | $known | ? {$_.header.startswith($HeaderAsHexString.ToString())} | select -f 1 | % {$_.extension}
115 | } catch {}
116 | }
117 |
--------------------------------------------------------------------------------
/ConvertFrom-Bytes.ps1:
--------------------------------------------------------------------------------
1 | function ConvertFrom-Bytes {
2 | param (
3 | [string]$bytes,
4 | [string]$savepath
5 | )
6 |
7 | $dir = Split-Path $savepath
8 | if (!(Test-Path $dir)) {
9 | md $dir | Out-Null
10 | }
11 |
12 | [convert]::FromBase64String($bytes) | Set-Content $savepath -Encoding Byte
13 | }
14 |
--------------------------------------------------------------------------------
/ConvertTo-Bytes.ps1:
--------------------------------------------------------------------------------
1 | function ConvertTo-Bytes {
2 | param (
3 | [string]$file
4 | )
5 |
6 | if (!$file -or !(Test-Path $file)) {
7 | throw "file not found: '$file'"
8 | }
9 |
10 | [convert]::ToBase64String((Get-Content $file -Encoding Byte))
11 | }
12 |
--------------------------------------------------------------------------------
/CopyTo-Image.ps1:
--------------------------------------------------------------------------------
1 | # http://www.online-tech-tips.com/computer-tips/hide-file-in-picture/
2 | # recommend using png instead of jpg
3 |
4 | function CopyTo-Image {
5 | param (
6 | [string]$file,
7 | [string]$image
8 | )
9 |
10 | $date = date -f yyyyMMddHHmmss
11 |
12 | $fileext = $file.split('.')[-1]
13 |
14 | if ($fileext -eq 'zip') {
15 | $zip = $file
16 | } else {
17 | $zip = "c:\temp\$date.zip"
18 | Compress-Archive $file $zip
19 | }
20 |
21 | $path = Split-Path $image
22 | $imageext = $image.split('.')[-1]
23 | $newname = (Split-Path $file -Leaf).Split('.')[0] + '.' + $imageext
24 | $newpath = Join-Path $path $newname
25 |
26 | cmd "/c copy /b $image + $zip `"$newpath`""
27 |
28 | if ($fileext -ne 'zip') {
29 | del "c:\temp\$date.zip"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Create-DesktopPin.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .example
3 | Create-DesktopPin -name "google drive" -path "c:\users\name\google drive"
4 |
5 | .example
6 | Create-DesktopPin -name "google drive" -delete # -force
7 | #>
8 |
9 | function Create-DesktopPin {
10 | param (
11 | $name,
12 | $path,
13 | [switch]$delete,
14 | [switch]$force
15 | )
16 |
17 | if ($delete) {
18 | $item = dir "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\" | ? {(Get-ItemProperty $_.pspath).'(default)' -ceq $name}
19 | $guid = (Split-Path $item.name -Leaf).trim('{}')
20 | if (!$guid) {
21 | throw "Could not find: $name"
22 | } else {
23 | if (!$force) {
24 | $createdby = (Get-ItemProperty $item.PSPath).CreatedBy
25 | if ($createdby -ne 'Create-DesktopPin') {
26 | $answer = Read-Host 'Looks like this Pin was not created by Create-DesktopPin. Delete anyway? y/[N]'
27 | if ($answer -ne 'y') {
28 | return
29 | }
30 | }
31 | }
32 | }
33 |
34 | $null = reg delete "HKCU\Software\Classes\CLSID\{$guid}" /f
35 | $null = reg delete "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}" /f
36 | $null = reg delete "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\{$guid}" /f
37 | $null = reg delete "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" /v "{$guid}" /f
38 | } else {
39 | if (!(New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
40 | throw 'you are not admin'
41 | }
42 |
43 | [String] $GUID = [guid]::NewGuid().ToString()
44 | $guid
45 |
46 | $null = reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" /v "{$guid}" /t REG_DWORD /d "1" /f
47 | $null = reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\{$guid}" /ve /t REG_SZ /d $name /f
48 | $null = reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\{$guid}" /v "CreatedBy" /t REG_SZ /d "Create-DesktopPin" /f
49 |
50 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}" /ve /t REG_SZ /d $name /f
51 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}" /v "System.IsPinnedToNamespaceTree" /t REG_DWORD /d "1" /f
52 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}" /v "SortOrderIndex" /t REG_DWORD /d "66" /f
53 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}\InProcServer32" /ve /t REG_EXPAND_SZ /d "%%SYSTEMROOT%%\system32\shell32.dll" /f
54 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}\ShellFolder" /v "FolderValueFlags" /t REG_DWORD /d "40" /f
55 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}\ShellFolder" /v "Attributes" /t REG_DWORD /d "4034920525" /f
56 | #$null = reg add "HKCU\Software\Classes\CLSID\{$guid}\DefaultIcon" /ve /t REG_SZ /d "C:\Program Files (x86)\Google\Drive\googledrivesync.exe,0" /f
57 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}\DefaultIcon" /ve /t REG_SZ /d "%%SystemRoot%%\System32\shell32.dll,3" /f
58 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}\Instance" /v "CLSID" /t REG_SZ /d "{0E5AAE11-A475-4c5b-AB00-C66DE400274E}" /f
59 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}\Instance\InitPropertyBag" /v "Attributes" /t REG_DWORD /d "17" /f
60 | $null = reg add "HKCU\Software\Classes\CLSID\{$guid}\Instance\InitPropertyBag" /v "TargetFolderPath" /t REG_SZ /d $path /f
61 |
62 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}" /ve /t REG_SZ /d $name /f
63 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}" /v "System.IsPinnedToNamespaceTree" /t REG_DWORD /d "1" /f
64 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}" /v "SortOrderIndex" /t REG_DWORD /d "66" /f
65 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\InProcServer32" /ve /t REG_EXPAND_SZ /d "%%SYSTEMROOT%%\system32\shell32.dll" /f
66 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\ShellFolder" /v "FolderValueFlags" /t REG_DWORD /d "40" /f
67 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\ShellFolder" /v "Attributes" /t REG_DWORD /d "4034920525" /f
68 | #$null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\DefaultIcon" /ve /t REG_SZ /d "C:\Program Files (x86)\Google\Drive\googledrivesync.exe,0" /f
69 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\DefaultIcon" /ve /t REG_SZ /d "%%SystemRoot%%\System32\shell32.dll,3" /f
70 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\Instance" /v "CLSID" /t REG_SZ /d "{0E5AAE11-A475-4c5b-AB00-C66DE400274E}" /f
71 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\Instance\InitPropertyBag" /v "Attributes" /t REG_DWORD /d "17" /f
72 | $null = reg add "HKCU\Software\Classes\Wow6432Node\CLSID\{$guid}\Instance\InitPropertyBag" /v "TargetFolderPath" /t REG_SZ /d $path /f
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Create-DummyFile.ps1:
--------------------------------------------------------------------------------
1 | # https://www.tutorialspoint.com/how-to-create-a-dummy-file-of-any-size-with-powershell
2 |
3 | function Create-DummyFile {
4 | param (
5 | $path = 'c:\temp',
6 | $size = 15mb
7 | )
8 |
9 | $f = new-object System.IO.FileStream $path, Create, ReadWrite
10 | $f.SetLength($size)
11 | $f.Close()
12 | }
13 |
--------------------------------------------------------------------------------
/Create-LocalUser.ps1:
--------------------------------------------------------------------------------
1 |
2 | # http://www.selfadsi.org/ads-attributes/user-userAccountControl.htm
3 |
4 | function Create-LocalUser {
5 | param (
6 | [string]$computer = $env:computername,
7 | [string]$fullname,
8 | [string]$username,
9 | [string]$password,
10 | [switch]$passworddoesnotexpire,
11 | [string]$addtogroup = 'Administrators',
12 | [switch]$CheckFirst = $true
13 | )
14 |
15 | if (!$username -or !$password) {
16 | throw 'no username or password'
17 | }
18 |
19 | if ($checkfirst -and ([ADSI]"WinNT://$computer/$username").Name) {
20 | Write-Warning "$username already exists on $computer"
21 | return
22 | }
23 |
24 | $objOU = [ADSI]"WinNT://$computer"
25 | $objUser = $objOU.Create('user', $username)
26 | $objUser.SetPassword($password)
27 | $objUser.SetInfo()
28 | $objUser.FullName = $fullname
29 | $objUser.SetInfo()
30 | #$objUser.Description = 'Test user'
31 | #$objUser.SetInfo()
32 |
33 | if ($passworddoesnotexpire) {
34 | $objUser.UserFlags = 65536 # password does not expire
35 | $objUser.SetInfo()
36 | }
37 |
38 | if ($addtogroup) {
39 | ([ADSI]"WinNT://$computer/$addtogroup").Add("WinNT://$computer/$username")
40 | }
41 | }
42 |
43 | # Create-LocalUser -computer $env:COMPUTERNAME -fullname 'Test' -username 'test' -password 'Password1' -passworddoesnotexpire -addtogroup 'Administrators'
44 |
--------------------------------------------------------------------------------
/Create-Shortcut.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/7xa4sk/programmatically_create_shortcuts_w_run_as_admin/du6pro0/
2 |
3 | # Create-Shortcut
4 | #
5 | # Create-Shortcut -Source C:\temp\test.txt -DestinationLnk C:\temp\test.txt.lnk
6 | #
7 | # Arguments
8 | # Description
9 | # FullName
10 | # Hotkey
11 | # IconLocation = '%SystemRoot%\system32\SHELL32.dll,16' # printer
12 | # RelativePath
13 | # TargetPath
14 | # WindowStyle
15 | # WorkingDirectory
16 |
17 | function Create-Shortcut {
18 | param (
19 | [string]$Source,
20 | [string]$DestinationLnk,
21 | [string]$Arguments
22 | )
23 |
24 | begin {
25 | $WshShell = New-Object -ComObject WScript.Shell
26 | }
27 |
28 | process {
29 | if (!$Source) {Throw 'No Source'}
30 | if (!$DestinationLnk) {Throw 'No DestinationLnk'}
31 |
32 | $Shortcut = $WshShell.CreateShortcut($DestinationLnk)
33 | $Shortcut.TargetPath = $Source
34 | if ($Arguments) {
35 | $Shortcut.Arguments = $Arguments
36 | }
37 | $Shortcut.Save()
38 | }
39 |
40 | end {
41 | function Release-Ref ($ref) {
42 | ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
43 | [System.GC]::Collect()
44 | [System.GC]::WaitForPendingFinalizers()
45 | }
46 | $Shortcut, $WshShell | % {$null = Release-Ref $_}
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Decode-Text.ps1:
--------------------------------------------------------------------------------
1 | # http://www.powershelladmin.com/wiki/Powershell_prompt_for_password_convert_securestring_to_plain_text
2 |
3 | function Decode-Text {
4 | param (
5 | [string]$Text,
6 | [validateset('SecureString', 'SecureStringWithKey', 'Base64', 'ASCII')]
7 | [string]$Method = 'Base64'
8 | )
9 |
10 | process {
11 | if (!$Text) {
12 | $Text = $input
13 | }
14 | }
15 |
16 | end {
17 | switch ($method) {
18 | 'SecureString' {
19 | (New-Object pscredential ' ', (ConvertTo-SecureString $text)).GetNetworkCredential().Password
20 | #$marshal = [Runtime.InteropServices.Marshal]
21 | #$marshal::PtrToStringAuto( $marshal::SecureStringToBSTR(($text | convertto-securestring)) )
22 | }
23 |
24 | 'SecureStringWithKey' {
25 | (New-Object pscredential ' ', (ConvertTo-SecureString $text -Key (1..16))).GetNetworkCredential().Password
26 | }
27 |
28 | 'Base64' {
29 | [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($text))
30 | }
31 |
32 | 'ASCII' {
33 | $pwlength = $text.Length / 3 - 1
34 | -join(0..$pwlength | % {[char](32 + $text.Substring(($_*3), 3))})
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/DelTempFiles.ps1:
--------------------------------------------------------------------------------
1 | $folders = @('C:\Windows\Temp\*', 'C:\Documents and Settings\*\Local Settings\temp\*', 'C:\Users\*\Appdata\Local\Temp\*', 'C:\Users\*\Appdata\Local\Microsoft\Windows\Temporary Internet Files\*', 'C:\Windows\SoftwareDistribution\Download', 'C:\Windows\System32\FNTCACHE.DAT')
2 | foreach ($folder in $folders) {Remove-Item $folder -force -recurse}
--------------------------------------------------------------------------------
/Delete_Days_Back.ps1:
--------------------------------------------------------------------------------
1 | ## Variables
2 | $Dest = "C:\Support\SQLBac\"; # Backup path on server (optional).
3 | $Daysback = "0"; # Days to keep.
4 |
5 | $CurrentDate = Get-Date
6 | $DatetoDelete = $CurrentDate.AddDays($Daysback)
7 | Get-ChildItem $Dest | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
--------------------------------------------------------------------------------
/Desktop_Management.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | ==============================================================================
3 | DESKTOP MANAGEMENT
4 | ==============================================================================
5 | Created: [07/24/2014]
6 | Author: Ethan Bell
7 | Arguments: N/A
8 | ==============================================================================
9 | Modified:
10 | Modifications:
11 | ==============================================================================
12 | Purpose: Shortcuts for the Desktop
13 | Options: Desktop, Drives, Control Panel, Favorites, Printers, History, Recent
14 | Network Connections, Program Files, Local Apps, Start-up Folder
15 | ==============================================================================
16 | #>
17 |
18 |
19 | $ShellApp = new-Object -ComObject shell.application
20 | Add-Type -AssemblyName PresentationFramework
21 | #$ShellApp.Explore(0x21)
22 |
23 |
24 | [xml]$xaml = @"
25 |
26 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | "@
47 |
48 | $reader = (New-Object System.Xml.XmlNodeReader $xaml)
49 | $d = [Windows.Markup.XamlReader]::Load($reader)
50 |
51 | ## Desktop
52 | $desktop = $d.FindName("button1")
53 | $desktop.add_Click({ $ShellApp.Explore(0x00) })
54 |
55 | ## ALL Drives
56 | $drives = $d.FindName("button2")
57 | $drives.add_Click({ $ShellApp.Explore(0x11) })
58 |
59 | ## Control Panel
60 | $cPanel = $d.FindName("button3")
61 | $cpanel.add_Click({ $ShellApp.Explore(0x03) })
62 |
63 | ## Favorites
64 | $fav = $d.FindName("button4")
65 | $fav.add_Click({ $ShellApp.Explore(0x06) })
66 |
67 | ## Printers
68 | $printer = $d.FindName("button5")
69 | $printer.add_click({ $ShellApp.Explore(0x04) })
70 |
71 | # History
72 | $history = $d.FindName("button6")
73 | $history.add_click({ $ShellApp.Explore(0x22) })
74 |
75 | ## Network
76 | $network = $d.FindName("button7")
77 | $network.add_click({ ncpa.cpl })
78 |
79 | ## Recent
80 | $recent = $d.FindName("button8")
81 | $recent.add_click({ $ShellApp.Explore(0x08 ) })
82 |
83 | # pROGfILES
84 |
85 | $nethood = $d.FindName("button9")
86 | $nethood.add_click({ $ShellApp.Explore(0x26) })
87 |
88 | ## lOCAL aPP dATA
89 | $localapp = $d.FindName("button10")
90 | $localapp.add_click({ $ShellApp.Explore(0x1c) })
91 |
92 | ## Startup
93 | $startup = $d.FindName("button11")
94 | $startup.add_click({ $ShellApp.Explore(0x07) })
95 |
96 | $d.ShowDialog() | Out-Null
--------------------------------------------------------------------------------
/Disk_Errors.ps1:
--------------------------------------------------------------------------------
1 | if ((get-host).Version.Major -ge 4){
2 | $XmlQuery = [xml]@'
3 |
4 |
5 |
6 |
7 |
8 | '@
9 | $LogOutput = Get-WinEvent -FilterXml $XmlQuery -ErrorAction SilentlyContinue
10 | }
11 | else{
12 | $LogOutput = Get-EventLog -LogName system -Source disk -After (get-date).AddDays(-1) -ErrorAction SilentlyContinue
13 | }
14 |
15 | if ($LogOutput){
16 | Write-Host "---ERROR---"
17 | Write-Host "Disk messages in system log found"
18 | $LogOutput | fl TimeGenerated, Message
19 | exit 1010
20 | }
21 |
22 | else{
23 | Write-Host "---OK---"
24 | Write-Host "No disk messages in system log found"
25 | exit 0
26 | }
--------------------------------------------------------------------------------
/EWSManagedAPI2.2.msi:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangstanthony/PowerShell/df7e9de1bfc0149f6b900ec65679516c5ed7503a/EWSManagedAPI2.2.msi
--------------------------------------------------------------------------------
/Enable-PSRemoting.ps1:
--------------------------------------------------------------------------------
1 | # Requires the PSRemoteRegistry module
2 | # https://psremoteregistry.codeplex.com/
3 |
4 | # https://blogs.technet.microsoft.com/heyscriptingguy/2006/06/21/how-can-i-use-windows-powershell-to-start-a-service-on-a-remote-computer/
5 |
6 | # https://gallery.technet.microsoft.com/scriptcenter/Enable-PSRemoting-Remotely-6cedfcb0
7 |
8 | function Enable-PSRemoting {
9 | param (
10 | [string[]]$Computers = (Read-Host 'Enter computer name'),
11 | [switch]$ShowSkipped
12 | )
13 |
14 | if (!$Computers) {Throw 'No computer name entered.'}
15 |
16 | $services = 'WinRM', 'RasAuto', 'RpcLocator', 'RemoteRegistry', 'RemoteAccess'
17 | $skipped = @()
18 |
19 | Import-Module PSRemoteRegistry
20 | foreach ($computer in $Computers) {
21 | $live = Test-Connection -Quiet $computer -Count 1 -ea 0
22 | if (!$live) {
23 | $skipped += $computer
24 | } else {
25 | foreach ($service in $services) {
26 | Set-Service $service -startuptype Automatic -passthru -computername $computer
27 | Set-Service $service -status Running -passthru -computername $computer
28 | }
29 |
30 | $computer |
31 | New-RegKey -Key 'SOFTWARE\Microsoft\PowerShell\1\ShellIds' -Name ScriptedDiagnostics -PassThru |
32 | Set-RegString -Value 'ExecutionPolicy' -Data Unrestricted -Force -PassThru |
33 | Set-RegString -Key 'SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' -Value ExecutionPolicy -Data Unrestricted -Force
34 | }
35 | }
36 |
37 | if ($ShowSkipped -and $skipped) {
38 | Write-Host ''
39 | Write-Host 'Test-Connection failed for the following computers:'
40 | $skipped
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Encode-Text.ps1:
--------------------------------------------------------------------------------
1 | # http://www.powershelladmin.com/wiki/Powershell_prompt_for_password_convert_securestring_to_plain_text
2 | # http://poshcode.org/116
3 |
4 | # also see
5 | # https://www.reddit.com/r/PowerShell/comments/5zio13/looking_for_a_method_of_encrypting_a_command_not/deyempf/
6 |
7 | function Encode-Text {
8 | param (
9 | [string]$Text,
10 | [validateset('SecureString', 'SecureStringWithKey', 'Base64', 'ASCII')]
11 | [string]$Method = 'Base64'
12 | )
13 |
14 | process {
15 | if (!$Text) {
16 | $Text = $input
17 | }
18 | }
19 |
20 | end{
21 | switch ($method) {
22 | # only recoverable by same user on same computer
23 | 'SecureString' {
24 | Write-Warning "This can only be recovered by '$env:USERNAME' on computer '$env:COMPUTERNAME'"
25 | ConvertTo-SecureString $text -AsPlainText -Force | ConvertFrom-SecureString
26 | }
27 |
28 | 'SecureStringWithKey' {
29 | ConvertTo-SecureString $text -AsPlainText -Force | ConvertFrom-SecureString -Key (1..16)
30 | }
31 |
32 | 'Base64' {
33 | [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Text))
34 | }
35 |
36 | # only works with letters
37 | 'ASCII' {
38 | -join([char[]]$text | % {
39 | '{0:D3}' -f ([int]$_ - 32)
40 | })
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Expand-OU.ps1:
--------------------------------------------------------------------------------
1 | # usage:
2 | # Expand-OU domain.com/company/sales/users
3 | #
4 | # output:
5 | # OU=users,OU=sales,OU=company,DC=domain,DC=com
6 |
7 | function Expand-OU ($searchroot) {
8 | $searchrootarray = $searchroot.split('/') | ? {$_ -and $_ -notmatch '^(?:\s+)?$'}
9 |
10 | $dn = ([adsi]"LDAP://$($searchrootarray[0])").distinguishedname.ToString()
11 |
12 | $searchrootarray = $searchrootarray | select -Skip 1
13 |
14 | foreach ($obj in $searchrootarray) {
15 | $query = Get-ADObject -Filter * -SearchBase $dn -SearchScope OneLevel | select name, distinguishedname
16 | if ($obj -in $query.name) {
17 | $dn = ($query | ? name -eq $obj).distinguishedname
18 | } else {
19 | throw "could not find '$obj' in '$dn'"
20 | }
21 | }
22 |
23 | Write-Output $dn
24 | }
25 |
--------------------------------------------------------------------------------
/Expand-ZIPFile.ps1:
--------------------------------------------------------------------------------
1 | # http://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/
2 | # http://stackoverflow.com/questions/11021879/creating-a-zipped-compressed-folder-in-windows-using-powershell-or-the-command-l
3 | # https://blogs.msdn.microsoft.com/daiken/2007/02/12/compress-files-with-windows-powershell-then-package-a-windows-vista-sidebar-gadget/
4 |
5 | # destination dir must already exist
6 |
7 | <# alternative1
8 | [System.Reflection.Assembly]::Load('WindowsBase,Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
9 | $folder = 'c:\temp'
10 | $zipArchive = Join-Path $folder 'zip.zip'
11 | $ZipPackage = [System.IO.Packaging.ZipPackage]::Open($zipArchive, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite)
12 | # ???
13 | $ZipPackage.Close()
14 | #>
15 |
16 | <# alternative2
17 | [Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
18 | [System.IO.Compression.ZipFile]::CreateFromDirectory($src_folder, $destfile, $compressionLevel, $includebasedir)
19 | #>
20 |
21 | function Expand-ZIPFile {
22 | param (
23 | [string]$file,
24 | [string]$destination
25 | )
26 |
27 | if (!$destination) {
28 | $destination = [string](Resolve-Path $file)
29 | $destination = $destination.Substring(0, $destination.LastIndexOf('.'))
30 | mkdir $destination | Out-Null
31 | }
32 | $shell = New-Object -ComObject Shell.Application
33 | #$shell.NameSpace($destination).CopyHere($shell.NameSpace($file).Items(), 16);
34 | $zip = $shell.NameSpace($file)
35 | foreach ($item in $zip.items()) {
36 | $shell.Namespace($destination).CopyHere($item)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Fix-Spaces.ps1:
--------------------------------------------------------------------------------
1 | # EXAMPLE:
2 | # $a = @(
3 | # 'System File Checker Utility (Scan On Every Boot) = sfc /scanboot'
4 | # 'System File Checker Utility (Return Scan Setting To Default) = sfc /revert'
5 | # )
6 | #
7 | # PS C:\> Fix-Spaces '=' $a
8 | # System File Checker Utility (Scan On Every Boot) = sfc /scanboot
9 | # System File Checker Utility (Return Scan Setting To Default) = sfc /revert
10 |
11 | function Fix-Spaces {
12 | param (
13 | [string]$delim = $(Throw 'A delimiter must be supplied.'),
14 | [string[]]$array
15 | )
16 |
17 | $len = 0
18 | $array | % {
19 | if ($_.contains($delim) -and $_.indexof($delim) -gt $len) {
20 | $len = $_.indexof($delim)
21 | }
22 | }
23 |
24 | $array | % {
25 | if ($_.Contains($delim)) {
26 | $front = $_.substring(0, $_.indexof($delim))
27 | $back = $_.substring($_.indexof($delim) + $delim.Length)
28 | if ($front.length -lt $len) {
29 | $spaces = $len - $front.Length - 1
30 | 0..$spaces | % {$front += ' '}
31 | }
32 | $front + $delim + $back
33 | } else {
34 | $_
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/ForceInstallUpdatesRemote.ps1:
--------------------------------------------------------------------------------
1 | #
2 | . S y n o p s i s
3 | F o r c e I n s t a l l U p d a t e s o n R e m o t e C o m p u t e r
4 | . D E S C R I P T I O N
5 | F o r c e I n s t a l l U p d a t e s o n R e m o t e C o m p u t e r u s i n g a s c h e d u l e d t a s k
6 | . E X A M P L E
7 | I n s t a l l U p d a t e s - C o m p u t e r " s e r v e r 1 . c o n t o s o . c o m " - U s e r " C o n t o s o \ A d m i n i s t r a t o r " - P a s s w o r d " P a s s w o r d "
8 | . N O T E S
9 | V e r s i o n 1 . 0 - I n i t i a l S c r i p t
10 | W r i t t e n b y D a r r y l v a n d e r P e i j l
11 | D a t e : 3 0 . 0 5 . 2 0 1 4
12 |
13 | U s e a t o w n r i s k
14 | # >
15 |
16 | F u n c t i o n I n s t a l l U p d a t e s {
17 | p a r a m ( $ C o m p u t e r , $ U s e r , $ P a s s w o r d )
18 |
19 | $ S e c u r e P a s s w o r d = C o n v e r t T o - S e c u r e S t r i n g S t r i n g $ P a s s w o r d A s P l a i n T e x t - F o r c e
20 | $ C r e d e n t i a l = N e w - O b j e c t T y p e N a m e S y s t e m . M a n a g e m e n t . A u t o m a t i o n . P S C r e d e n t i a l A r g u m e n t L i s t $ U s e r , $ S e c u r e P a s s w o r d
21 |
22 | I n v o k e - C o m m a n d - C o m p u t e r N a m e $ C o m p u t e r - c r e d e n t i a l $ C r e d e n t i a l - S c r i p t B l o c k {
23 | # G e t D a t e
24 | $ D a t e A n d T i m e = ( G e t - D a t e - f o r m a t d d M M M y y y y - H H . m m )
25 | # R e g i s t e r S c h e d u l e d T a s k w i t h D a t e
26 | R e g i s t e r - S c h e d u l e d J o b - N a m e " I n s t a l l U p d a t e s $ D a t e A n d T i m e " - R u n N o w - S c r i p t B l o c k {
27 | # D e f i n e u p d a t e c r i t e r i a .
28 | $ C r i t e r i a = " I s I n s t a l l e d = 0 a n d T y p e = ' S o f t w a r e ' " ; `
29 | # S e a r c h f o r r e l e v a n t u p d a t e s .
30 | $ S e a r c h e r = N e w - O b j e c t - C o m O b j e c t M i c r o s o f t . U p d a t e . S e a r c h e r ; `
31 | $ S e a r c h R e s u l t = $ S e a r c h e r . S e a r c h ( $ C r i t e r i a ) . U p d a t e s ; `
32 | # D o w n l o a d u p d a t e s .
33 | $ S e s s i o n = N e w - O b j e c t - C o m O b j e c t M i c r o s o f t . U p d a t e . S e s s i o n ; `
34 | $ D o w n l o a d e r = $ S e s s i o n . C r e a t e U p d a t e D o w n l o a d e r ( ) ; `
35 | $ D o w n l o a d e r . U p d a t e s = $ S e a r c h R e s u l t ; `
36 | $ D o w n l o a d e r . D o w n l o a d ( ) ; `
37 | # I n s t a l l u p d a t e s .
38 | $ I n s t a l l e r = N e w - O b j e c t - C o m O b j e c t M i c r o s o f t . U p d a t e . I n s t a l l e r ; `
39 | $ I n s t a l l e r . U p d a t e s = $ S e a r c h R e s u l t ; `
40 | # R e s u l t - > 2 = S u c c e e d e d , 3 = S u c c e e d e d w i t h E r r o r s , 4 = F a i l e d , 5 = A b o r t e d
41 | $ R e s u l t = $ I n s t a l l e r . I n s t a l l ( ) ; `
42 |
43 | } # E n d s c h e d u l e d j o b s c r i p t b l o c k
44 | } # E n d I n v o k e S c r i p t l o c k
45 | } # E n d F u n c t i o n
46 |
47 |
48 |
--------------------------------------------------------------------------------
/Get-BitLockerInfo.ps1:
--------------------------------------------------------------------------------
1 | # requires psexec
2 |
3 | function Get-BitLockerInfo {
4 | param (
5 | [string]$ComputerName = $env:COMPUTERNAME,
6 | [string]$PsExecPath = 'C:\pstools\psexec.exe'
7 | )
8 |
9 | # Test connectivity before attempting to connect
10 | if (Test-Connection -ComputerName $ComputerName -Quiet -Count 2) {
11 | try{
12 | $user = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName ).UserName
13 | }
14 | catch {
15 | $user = 'UNKNOWN'
16 | }
17 |
18 | $hash = [ordered]@{
19 | 'ComputerName' = $ComputerName
20 | 'User' = $user
21 | }
22 |
23 | # manage-bde -status c: -computername $comp.name # can't use because of the context it says manage-bde not found
24 | # With this parsing of the output of 'manage-bde' we ensure it works on systems using languages other than English, and it's more robust and efficient in general
25 | $bitlockerinfo = (& $PsExecPath \\$ComputerName manage-bde -status c:) -replace ':','=' | Where-Object { $_ -match "^(\s{4})" } | ConvertFrom-StringData
26 |
27 | foreach ($key in $bitlockerinfo.Keys) {
28 | $hash.Add("$key", $bitlockerinfo."$key")
29 | }
30 |
31 | # return the created object
32 | [PSCustomObject]$hash
33 |
34 | } else {
35 | Write-Error "Could not reach target computer: '$ComputerName'."
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Get-BitLockerKey.ps1:
--------------------------------------------------------------------------------
1 | function Get-BitLockerKey {
2 | param (
3 | [string]$comp = $env:COMPUTERNAME
4 | #[string]$pwidmatch
5 | )
6 |
7 | if (!$comp.endswith('$')) {
8 | $comp += '$'
9 | }
10 |
11 | $compsearcher = [adsisearcher]"samaccountname=$comp"
12 | $compsearcher.PageSize = 200
13 | $compsearcher.PropertiesToLoad.Add('name') | Out-Null
14 | $compobj = $compsearcher.FindOne().Properties
15 |
16 | if (!$compobj) {
17 | throw "$comp not found"
18 | }
19 |
20 | $keysearcher = [adsisearcher]'objectclass=msFVE-RecoveryInformation'
21 | $keysearcher.SearchRoot = [string]$compobj.adspath.trim()
22 | $keysearcher.PageSize = 200
23 | $keysearcher.PropertiesToLoad.AddRange(('name', 'msFVE-RecoveryPassword'))
24 |
25 | $keys = $keysearcher.FindOne().Properties
26 | if ($keys) {
27 | $keys | % {
28 | try{ rv matches -ea stop }catch{}
29 | ('' + $_.name) -match '^([^\{]+)\{([^\}]+)' | Out-Null
30 |
31 | $date = $Matches[1]
32 | $pwid = $Matches[2]
33 |
34 | New-Object psobject -Property @{
35 | Name = [string]$compobj.name
36 | Date = $date
37 | PasswordID = $pwid
38 | BitLockerKey = [string]$_.'msfve-recoverypassword'
39 | } | select name, date, passwordid, bitlockerkey
40 | }
41 | } else {
42 | New-Object psobject -Property @{
43 | Name = [string]$compobj.name
44 | Date = ''
45 | PasswordID = ''
46 | BitLockerKey = ''
47 | } | select name, date, passwordid, bitlockerkey
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Get-BootConfigurationData.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/4fyfau/does_anyone_know_of_a_module_or_wrapper_for/
2 |
3 | # must be admin
4 |
5 | function Get-BootConfigurationData {
6 | param (
7 | $bcdeditpath = (Join-Path $env:SystemRoot 'system32\bcdedit.exe')
8 | )
9 |
10 | $bootconfigurationdata = iex $bcdeditpath
11 | $bootconfigurationdata += ''
12 |
13 | $hash = $null
14 | $result = foreach ($line in $bootconfigurationdata) {
15 | if ($line -eq '') {
16 | if ($hash) {
17 | [pscustomobject]$hash
18 | }
19 | $hash = @{}
20 | continue
21 | }
22 | if ($line.startswith('-----')) { continue }
23 | if ($line.startswith('Windows Boot')) {
24 | $hash.Add('Type', $line)
25 | } else {
26 | $name = $line.Substring(0, $line.IndexOf(' '))
27 | $value = $line.Substring($line.IndexOf(' ')).trim()
28 | $hash.Add($name, $value)
29 | }
30 | }
31 |
32 | $props = $result | % {gm -in $_ -ty *property} | % name | select -u | sort
33 |
34 | $result | select $props
35 | }
36 |
--------------------------------------------------------------------------------
/Get-ChromeExtension.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/5px71w/getting_chrome_extensions/
2 |
3 | function Get-ChromeExtension {
4 | param (
5 | [string]$ComputerName = $env:COMPUTERNAME
6 | )
7 |
8 | Get-ChildItem "\\$ComputerName\c$\users\*\appdata\local\Google\Chrome\User Data\Default\Extensions\*\*\manifest.json" -ErrorAction SilentlyContinue | % {
9 | $path = $_.FullName
10 | $_.FullName -match 'users\\(.*?)\\appdata' | Out-Null
11 | Get-Content $_.FullName -Raw | ConvertFrom-Json | select @{n='ComputerName';e={$ComputerName}}, @{n='User';e={$Matches[1]}}, Name, Version, @{n='Path';e={$path}}
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Get-Clipboard.ps1:
--------------------------------------------------------------------------------
1 |
2 | if (gcm Get-Clipboard -ea 0) {
3 | return
4 | }
5 |
6 | #https://www.reddit.com/r/PowerShell/comments/68jpzx/a_small_getclipboard_function_for_ps_before_v5/
7 |
8 | <# http://stackoverflow.com/questions/34700427/quickly-create-a-list-of-strings
9 | Add-Type -Assembly System.Windows.Forms | Out-Null
10 | $clp = [Windows.Forms.Clipboard]::GetText() -split "`r`n"
11 | #>
12 |
13 | # http://stackoverflow.com/questions/1567112/convert-keith-hills-powershell-get-clipboard-and-set-clipboard-to-a-psm1-script
14 | function Get-Clipboard {
15 | Add-Type -AssemblyName System.Windows.Forms
16 |
17 | $(if ([threading.thread]::CurrentThread.ApartmentState.ToString() -eq 'STA') {
18 | Write-Verbose 'STA mode: Using [Windows.Forms.Clipboard] directly.'
19 | # To be safe, we explicitly specify that Unicode (UTF-16) be used - older platforms may default to ANSI.
20 | [System.Windows.Forms.Clipboard]::GetText([System.Windows.Forms.TextDataFormat]::UnicodeText)
21 | } else {
22 | Write-Verbose 'MTA mode: Using a [System.Windows.Forms.TextBox] instance for clipboard access.'
23 | $tb = New-Object System.Windows.Forms.TextBox
24 | $tb.Multiline = $true
25 | $tb.Paste()
26 | $tb.Text
27 | }).Split("`n") | % {$_.Trim()}
28 | }
29 |
30 | <# http://poshcode.org/2150
31 | function Get-Clipboard {
32 | Set-StrictMode -Version Latest
33 | PowerShell -NoProfile -STA -Command {
34 | Add-Type -Assembly PresentationCore
35 | [Windows.Clipboard]::GetText()
36 | }
37 | }
38 | #>
39 |
40 | <# http://stackoverflow.com/questions/1567112/convert-keith-hills-powershell-get-clipboard-and-set-clipboard-to-a-psm1-script
41 | function Get-ClipBoard {
42 | Add-Type -AssemblyName System.Windows.Forms
43 | $tb = New-Object System.Windows.Forms.TextBox
44 | $tb.Multiline = $true
45 | $tb.Paste()
46 | $tb.Text
47 | }
48 | #>
49 |
--------------------------------------------------------------------------------
/Get-ComputerShares.ps1:
--------------------------------------------------------------------------------
1 | # http://stackoverflow.com/questions/15797198/powershell-get-a-list-of-network-machines
2 | # switch -regex (NET.EXE VIEW) { "^\\\\(?\S+)\s+" {$matches.Name}}
3 | # $shares = $(switch -regex (net view) { '^\\\\(?\S+)' {$matches.Name}}) | % {net view $_}
4 |
5 | # do NOT need admin rights
6 | # not reliable. tried once on ca-nor1-sb10, nothing, tried again, got results... :/
7 |
8 | # check all computers that show up on the network
9 | #''; net view | ? {$_ -match '^\\\\'} | % {$_.trim()} | % {if (ping1 $_.substring(2)) {net view $_}} | ? {$_ -and $_ -notmatch 'no entries|not found'} | % {if ($_ -match 'succ') {"`n"} else {$_}}
10 |
11 | # need admin rights for this option
12 | #gwmi win32_share -comp 'lt-40132' | select pscomputername, type, name, caption, description | ft -a
13 |
14 | function Get-ComputerShares {
15 | param (
16 | [string]$comp = $env:COMPUTERNAME
17 | )
18 |
19 | if (!$comp) { throw 'No comps.' }
20 |
21 | $ping = New-Object System.Net.NetworkInformation.Ping
22 | try {
23 | $result = $ping.Send($comp)
24 | } catch {
25 | $result = $null
26 | }
27 |
28 | $sharename = $type = $comment = $ip = '-'
29 | if ($result.Status -eq 'Success') {
30 | # get the ip address
31 | $ip = $result.Address.ToString()
32 |
33 | # THE MAIN COMMAND
34 | $netview = iex "cmd /c net view $comp 2>&1" | ? {$_}
35 |
36 | # if there are less than 5 lines, no shares found
37 | if ($netview.count -lt 5) {
38 | [pscustomobject]@{
39 | Computer = $comp
40 | IP = $ip
41 | ShareName = $sharename
42 | Type = $type
43 | Comment = $comment
44 | }
45 | return
46 | }
47 |
48 | $netview = $netview | ? {$_ -match '\s{2}'} | select -Skip 1
49 |
50 | foreach ($line in $netview) {
51 | $line = $line -split '\s{2,}'
52 |
53 | $sharename = $line[0]
54 | $type = $line[1]
55 | $comment = $line[2]
56 |
57 | [pscustomobject]@{
58 | Computer = $comp
59 | IP = $ip
60 | ShareName = $sharename
61 | Type = $type
62 | Comment = $comment
63 | }
64 | }
65 | } else {
66 | [pscustomobject]@{
67 | Computer = $comp
68 | IP = $ip
69 | ShareName = $sharename
70 | Type = $type
71 | Comment = $comment
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Get-FailingDrive.ps1:
--------------------------------------------------------------------------------
1 | Function Get-FailingDrive {
2 | <#
3 | .SYNOPSIS
4 | Checks for any potentially failing drives and reports back drive information.
5 |
6 | .DESCRIPTION
7 | Checks for any potentially failing drives and reports back drive information. This only works
8 | against local hard drives using SMART technology. Reason values and their meanings can be found
9 | here: http://en.wikipedia.org/wiki/S.M.A.R.T#Known_ATA_S.M.A.R.T._attributes
10 |
11 | .PARAMETER Computer
12 | Remote or local computer to check for possible failed hard drive.
13 |
14 | .PARAMETER Credential
15 | Provide alternate credential to perform query.
16 |
17 | .NOTES
18 | Author: Boe Prox
19 | Version: 1.0
20 |
21 | http://learn-powershell.net
22 |
23 | .EXAMPLE
24 | Get-FailingDrive
25 |
26 | WARNING: ST9320320AS ATA Device may fail!
27 |
28 |
29 | MediaType : Fixed hard disk media
30 | InterFace : IDE
31 | DriveName : ST9320320AS ATA Device
32 | Reason : 1
33 | SerialNumber : 202020202020202020202020533531584e5a4d50
34 | FailureImminent : True
35 |
36 | Description
37 | -----------
38 | Command ran against the local computer to check for potential failed hard drive.
39 | #>
40 | [cmdletbinding()]
41 | Param (
42 | [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
43 | [string[]]$Computername,
44 | [parameter()]
45 | [System.Management.Automation.PSCredential]$Credential
46 | )
47 | Begin {
48 | $queryhash = @{}
49 | $BadDriveHash = @{}
50 | }
51 | Process {
52 | ForEach ($Computer in $Computername) {
53 | If ($PSBoundParameters['Computer']) {
54 | $queryhash['Computername'] = $Computer
55 | $BadDriveHash['Computername'] = $Computer
56 | } Else {
57 | $queryhash['Computername'] = $Env:Computername
58 | $BadDriveHash['Computername'] = $Env:Computername
59 | }
60 | If ($PSBoundParameters['Credential']) {
61 | $queryhash['Credential'] = $Credential
62 | $BadDriveHash['Credential'] = $Credential
63 | }
64 | Write-Verbose "Creating SplatTable"
65 | $queryhash['NameSpace'] = 'root\wmi'
66 | $queryhash['Class'] = 'MSStorageDriver_FailurePredictStatus'
67 | $queryhash['Filter'] = "PredictFailure='False'"
68 | $queryhash['ErrorAction'] = 'Stop'
69 | $BadDriveHash['Class'] = 'win32_diskdrive'
70 | $BadDriveHash['ErrorAction'] = 'Stop'
71 | [regex]$regex = "(?\w+\\[A-Za-z0-9_]*)\w+"
72 | Try {
73 | Write-Verbose "Checking for failed drives"
74 | Get-WmiObject @queryhash | ForEach {
75 | $drive = $regex.Matches($_.InstanceName) | ForEach {$_.Groups['DriveName'].value}
76 | Write-Verbose "Gathering more information about failing drive"
77 | $BadDrive = gwmi @BadDriveHash | Where {$_.PNPDeviceID -like "$drive*"}
78 | If ($BadDrive) {
79 | Write-Warning "$($BadDriveHash['Computername']): $($BadDrive.Model) may fail!"
80 | New-Object PSObject -Property @{
81 | DriveName = $BadDrive.Model
82 | FailureImminent = $_.PredictFailure
83 | Reason = $_.Reason
84 | MediaType = $BadDrive.MediaType
85 | SerialNumber = $BadDrive.SerialNumber
86 | InterFace = $BadDrive.InterfaceType
87 | Partitions = $BadDrive.Partitions
88 | Size = $BadDrive.Size
89 | Computer = $BadDriveHash['Computername']
90 | }
91 | }
92 | }
93 | } Catch {
94 | Write-Warning "$($Error[0])"
95 | }
96 | }
97 | }
98 | }
--------------------------------------------------------------------------------
/Get-FileSizeOnDisk.ps1:
--------------------------------------------------------------------------------
1 | # https://www.opentechguides.com/how-to/article/powershell/133/size-on-disk-ps.html
2 |
3 | <#
4 |
5 | .SYNOPSIS
6 | Powershell script to get file size and size on disk of all files
7 | in a directory.
8 |
9 | .DESCRIPTION
10 | This PowerShell script gets file size and size on disk in bytes
11 | of all files in a directory.
12 |
13 | .PARAMETER
14 | Directory path of the files to check. If this parameter is not
15 | specified the default value is current directory.
16 |
17 | .NOTES
18 | Version: 1.0
19 | Author: Open Tech Guides
20 | Creation Date: 06-Feb-2017
21 |
22 | .LINK
23 | www.opentechguides.com
24 |
25 | .EXAMPLE
26 | Get-FileSizeOnDisk c:\myfolder
27 |
28 | #>
29 |
30 | function Get-FileSizeOnDisk {
31 | param (
32 | [string]$path = '.',
33 | [switch]$recurse
34 | )
35 |
36 |
37 | $source = '
38 | using System;
39 | using System.Runtime.InteropServices;
40 | using System.ComponentModel;
41 | using System.IO;
42 |
43 | namespace Win32
44 | {
45 |
46 | public class Disk {
47 |
48 | [DllImport("kernel32.dll")]
49 | static extern uint GetCompressedFileSizeW([In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
50 | [Out, MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh);
51 |
52 | public static ulong GetSizeOnDisk(string filename)
53 | {
54 | uint HighOrderSize;
55 | uint LowOrderSize;
56 | ulong size;
57 |
58 | FileInfo file = new FileInfo(filename);
59 | LowOrderSize = GetCompressedFileSizeW(file.FullName, out HighOrderSize);
60 |
61 | if (HighOrderSize == 0 && LowOrderSize == 0xffffffff)
62 | {
63 | throw new Win32Exception(Marshal.GetLastWin32Error());
64 | }
65 | else {
66 | size = ((ulong)HighOrderSize << 32) + LowOrderSize;
67 | return size;
68 | }
69 | }
70 | }
71 | }
72 | '
73 |
74 | Add-Type -TypeDefinition $source
75 |
76 | if ($recurse) {
77 | Get-ChildItem $path -Recurse | Where-Object { ! $_.PSIsContainer} | Foreach-Object {
78 | $_ | select fullname, name, length, extension, basename, @{n='SizeOnDisk';e={[Win32.Disk]::GetSizeOnDisk($_.FullName)}}
79 | }
80 | } else {
81 | Get-ChildItem $path | Where-Object { ! $_.PSIsContainer} | Foreach-Object {
82 | $_ | select fullname, name, length, extension, basename, @{n='SizeOnDisk';e={[Win32.Disk]::GetSizeOnDisk($_.FullName)}}
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/Get-Files.ps1 (Robocopy only version):
--------------------------------------------------------------------------------
1 |
2 | # this is just a trimmed-down, robocopy-only version of this:
3 | # https://github.com/gangstanthony/PowerShell/blob/master/Get-Files.ps1
4 |
5 | # a note about: $dir = '"' + $dir + ' "'
6 | # https://stackoverflow.com/a/30244061/4589490
7 |
8 | function Get-Files
9 | {
10 | [cmdletbinding()]
11 | param
12 | (
13 | [parameter(ValueFromPipeline=$true)]
14 | [string[]]$Path = $PWD,
15 | [string[]]$Include,
16 | [string[]]$ExcludeDirs,
17 | [string[]]$ExcludeFiles,
18 | [switch]$Recurse,
19 | [switch]$FullName,
20 | [switch]$Directory,
21 | [switch]$File
22 | )
23 |
24 | if ($Directory -and $File)
25 | {
26 | throw 'Cannot use both -Directory and -File at the same time.'
27 | }
28 |
29 | $Path = (Resolve-Path $Path).ProviderPath
30 |
31 | function CreateFolderObject
32 | {
33 | $name = ''
34 | $name += $(Split-Path $matches.FullName -Leaf)
35 | Write-Output $(New-Object psobject -Property @{
36 | FullName = $matches.FullName
37 | DirectoryName = $($matches.FullName.substring(0, $matches.fullname.lastindexof('\')))
38 | Name = $name.ToString()
39 | Size = $null
40 | Extension = '[Directory]'
41 | DateModified = $null
42 | })
43 | }
44 |
45 | $params = '/L', '/NJH', '/BYTES', '/FP', '/NC', '/TS', '/R:0', '/W:0'
46 | if ($Recurse) {$params += '/E'}
47 | if ($Include) {$params += $Include}
48 | if ($ExcludeDirs) {$params += '/XD', ('"' + ($ExcludeDirs -join '" "') + '"')}
49 | if ($ExcludeFiles) {$params += '/XF', ('"' + ($ExcludeFiles -join '" "') + '"')}
50 |
51 | foreach ($dir in $Path)
52 | {
53 | if ($dir.contains(' '))
54 | {
55 | $dir = '"' + $dir + ' "'
56 | }
57 |
58 | foreach ($line in $(robocopy $dir 'c:\tmep' $params))
59 | {
60 | # folder
61 | if (!$File -and $line -match '\s+\d+\s+(?.*\\)$')
62 | {
63 | if ($Include)
64 | {
65 | if ($matches.FullName -like "*$($include.replace('*',''))*")
66 | {
67 | if ($FullName)
68 | {
69 | Write-Output $( $matches.FullName )
70 | }
71 | else
72 | {
73 | Write-Output $( CreateFolderObject )
74 | }
75 | }
76 | }
77 | else
78 | {
79 | if ($FullName)
80 | {
81 | Write-Output $( $matches.FullName )
82 | }
83 | else
84 | {
85 | Write-Output $( CreateFolderObject )
86 | }
87 | }
88 | }
89 | # file
90 | elseif (!$Directory -and $line -match '(?\d+)\s(?\S+\s\S+)\s+(?.*[^\\])$')
91 | {
92 | if ($FullName)
93 | {
94 | Write-Output $( $matches.FullName )
95 | }
96 | else
97 | {
98 | $name = Split-Path $matches.FullName -Leaf
99 | Write-Output $(New-Object psobject -Property @{
100 | FullName = $matches.FullName
101 | DirectoryName = Split-Path $matches.FullName
102 | Name = $name
103 | Size = [int64]$matches.Size
104 | Extension = $(if ($name.IndexOf('.') -ne -1) {'.' + $name.split('.')[-1]} else {'[None]'})
105 | DateModified = $matches.Date
106 | })
107 | }
108 | }
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/Get-Firewall.ps1:
--------------------------------------------------------------------------------
1 | ## INFO
2 | # find firewall status of remote computer
3 |
4 | function Get-Firewall {
5 | param (
6 | [object]$comps = $env:COMPUTERNAME
7 | )
8 |
9 | foreach ($computer in $comps) {
10 | try {
11 | # $status = (gp 'HKLM:\SYSTEM\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile').EnableFirewall
12 | # reg query \\$computer\HKLM\SYSTEM\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile /v EnableFirewall
13 | $status = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer).OpenSubKey('SYSTEM\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile').GetValue('EnableFirewall')
14 |
15 | [bool]$status
16 | } catch [System.Exception] {
17 | return 'Error'
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Get-FolderSize.ps1:
--------------------------------------------------------------------------------
1 | # https://social.technet.microsoft.com/Forums/scriptcenter/en-US/333f63ca-a7e0-4d92-b18d-133fd4953af7/export-with-foreach-not-working-then-send?forum=ITCG
2 | # http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/05/weekend-scripter-sorting-folders-by-size.aspx
3 | # https://www.linkedin.com/pulse/technical-thursdays-get-directory-sizes-stupidly-fast-carlos-nunez?trk=sushi_topic_posts_guest
4 |
5 | function Get-FolderSize {
6 | [cmdletbinding()]
7 | param (
8 | $Path = $PWD,
9 | [validateset('GCI', 'Robocopy', 'FSO', 'All')]
10 | $Use = 'Robocopy'
11 | )
12 |
13 | begin {
14 | <# Commented out because if a file is given, FSO errors into GCI which can handle files.
15 | if ([System.IO.File]::Exists($Path)) {
16 | if (!(Test-Path $Path -PathType Container)) {
17 | Throw "$Path is not a directory."
18 | }
19 | }#>
20 |
21 | function Resolve-FullPath ($Path = $PWD) {
22 | if ( -not ([IO.Path]::IsPathRooted($Path)) ) {
23 | $Path = Join-Path (Get-Location) $Path
24 | }
25 | [IO.Path]::GetFullPath($Path)
26 | }
27 |
28 | function Get-FolderSizeFSO ($Path = $PWD) {
29 | begin {
30 | $fso = New-Object -ComObject scripting.filesystemobject
31 | }
32 |
33 | process {
34 | New-Object psobject -prop @{
35 | Path = $Path
36 | Count = $null
37 | Size = $fso.GetFolder($Path).size
38 | }
39 | }
40 |
41 | end {
42 | [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($fso)
43 | [gc]::Collect()
44 | }
45 | }
46 |
47 | function Get-FolderSizeGCI ($Path = $PWD) {
48 | $items = Get-ChildItem $Path -Recurse -Force | ? {!$_.psiscontainer}
49 |
50 | New-Object psobject -prop @{
51 | Path = $Path
52 | Count = $items.count
53 | Size = ($items | Measure-Object -sum length).sum
54 | }
55 | }
56 |
57 | function Get-FolderSizeRobocopy ($Path = $PWD) {
58 | $lines = robocopy $Path NULL * /L /S /NJH /NFL /NDL /BYTES | ? {$_ -match '(?:Files|Bytes) :'}
59 |
60 | $hash = @{
61 | Path = $Path
62 | Count = $null
63 | Size = $null
64 | }
65 | $lines | % {
66 | switch -Regex ($_) {
67 | 'Files :\s+(\d+)' {$hash['Count'] = $Matches[1]}
68 | 'Bytes :\s+(\d+)' {$hash['Size'] = $Matches[1]}
69 | }
70 | }
71 |
72 | New-Object psobject -prop $hash
73 | }
74 | }
75 |
76 | process {
77 | $Path = Resolve-FullPath $Path
78 |
79 | # remove trailing \
80 | $Path = $Path -replace '\\$'
81 |
82 | switch ($Use) {
83 | 'All' {
84 | try {
85 | $fso = Get-FolderSizeFSO $Path | select *, @{n='Use';e={'FSO'}}
86 | if ($fso.size) {
87 | $fso
88 | } else {
89 | 1/0 # force into Robocopy
90 | }
91 | } catch {
92 | try {
93 | $robo = Get-FolderSizeRobocopy $Path | select *, @{n='Use';e={'Robocopy'}}
94 | if ($robo.size) {
95 | $robo
96 | } else {
97 | 1/0 # force into GCI
98 | }
99 | } catch {
100 | try {
101 | Get-FolderSizeGCI $Path | select *, @{n='Use';e={'GCI'}}
102 | } catch {
103 | New-Object psobject -prop @{
104 | Path = $Path
105 | Count = $null
106 | Size = $null
107 | Use = 'Error'
108 | }
109 | }
110 | }
111 | }
112 | }
113 | 'FSO' {Get-FolderSizeFSO $Path}
114 | 'GCI' {Get-FolderSizeGCI $Path}
115 | 'Robocopy' {Get-FolderSizeRobocopy $Path}
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/Get-Header.ps1:
--------------------------------------------------------------------------------
1 | # http://learningpcs.blogspot.com/2012/07/powershell-v3-check-file-headers.html
2 | # https://en.wikipedia.org/wiki/List_of_file_signatures
3 | # http://www.garykessler.net/library/file_sigs.html
4 |
5 | function Get-Header {
6 | param (
7 | [string]$path,
8 | [int]$bits = 4
9 | )
10 |
11 | $path = Resolve-FullPath $path
12 |
13 | try {
14 | # Get content of each file (up to 4 bytes) for analysis
15 | $HeaderAsHexString = New-Object System.Text.StringBuilder
16 | [Byte[]](Get-Content -Path $path -TotalCount $bits -Encoding Byte -ea Stop) | % {
17 | if (("{0:X}" -f $_).length -eq 1) {
18 | $null = $HeaderAsHexString.Append('0{0:X}' -f $_)
19 | } else {
20 | $null = $HeaderAsHexString.Append('{0:X}' -f $_)
21 | }
22 | }
23 |
24 | $HeaderAsHexString.ToString()
25 | } catch {}
26 | }
27 |
--------------------------------------------------------------------------------
/Get-IEVersion.ps1:
--------------------------------------------------------------------------------
1 | # http://powershell.org/wp/forums/topic/creating-a-array-of-info-for-remote-computers/#post-37990
2 |
3 | function Get-IEVersion ($computer = $env:COMPUTERNAME) {
4 | $version = 0
5 |
6 | $keyname = 'SOFTWARE\Microsoft\Internet Explorer'
7 |
8 | $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
9 | $key = $reg.OpenSubkey($keyname)
10 |
11 | try {
12 | $version = $key.GetValue('Version')
13 | $svcUpdateVersion = $key.GetValue('svcUpdateVersion')
14 | #$svcKBNumber = $key.Getvalue('svcKBNumber')
15 | } catch {}
16 |
17 | if ($svcUpdateVersion) {
18 | $svcUpdateVersion
19 | } else {
20 | $version
21 | }
22 |
23 | #[pscustomobject]@{
24 | # ComputerName = $computer
25 | # IEVersion = $version
26 | # SvcUpdateVersion = $svcUpdateVersion
27 | # KB_Number = $svcKBNumber
28 | #}
29 | }
30 |
--------------------------------------------------------------------------------
/Get-InstalledApps.ps1:
--------------------------------------------------------------------------------
1 | # a more complete script can be found here:
2 | # https://gist.github.com/indented-automation/32efb05a5fb67ef9eed02bbb8fe90691
3 | # https://community.spiceworks.com/scripts/show_download/2170-get-a-list-of-installed-software-from-a-remote-computer-fast-as-lightning
4 |
5 | # note: might have to use enable-psremoting first if no results are returned
6 |
7 | <#
8 | friends don't let friends use win32_product to query for installed programs
9 | https://sdmsoftware.com/group-policy-blog/wmi/why-win32_product-is-bad-news/
10 | https://blogs.technet.microsoft.com/heyscriptingguy/2011/12/14/use-powershell-to-find-and-uninstall-software/
11 | https://blogs.technet.microsoft.com/heyscriptingguy/2011/11/13/use-powershell-to-quickly-find-installed-software/
12 | http://powershell.org/wp/forums/topic/alternatives-to-win32_product/
13 | this is what i use to get installed programs
14 | https://github.com/gangstanthony/PowerShell/blob/master/Get-InstalledApps.ps1
15 | example usage
16 | Get-InstalledApps -ComputerName $env:COMPUTERNAME -NameRegex '^java'
17 | you will get an uninstallstring returned from that as well. you can use one of the methods below to run the uninstaller on the remote computer
18 | https://www.reddit.com/r/PowerShell/comments/4l5kkm/what_are_all_or_at_least_the_most_common_ways_to/
19 | #>
20 |
21 | function Get-InstalledApps {
22 | param (
23 | [Parameter(ValueFromPipeline=$true)]
24 | [string[]]$ComputerName = $env:COMPUTERNAME,
25 | [string]$NameRegex = ''
26 | )
27 |
28 | foreach ($comp in $ComputerName) {
29 | $keys = '','\Wow6432Node'
30 | foreach ($key in $keys) {
31 | try {
32 | $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $comp)
33 | $apps = $reg.OpenSubKey("SOFTWARE$key\Microsoft\Windows\CurrentVersion\Uninstall").GetSubKeyNames()
34 | } catch {
35 | continue
36 | }
37 |
38 | foreach ($app in $apps) {
39 | $program = $reg.OpenSubKey("SOFTWARE$key\Microsoft\Windows\CurrentVersion\Uninstall\$app")
40 | $name = $program.GetValue('DisplayName')
41 | if ($name -and $name -match $NameRegex) {
42 | [pscustomobject]@{
43 | ComputerName = $comp
44 | DisplayName = $name
45 | DisplayVersion = $program.GetValue('DisplayVersion')
46 | Publisher = $program.GetValue('Publisher')
47 | InstallDate = $program.GetValue('InstallDate')
48 | UninstallString = $program.GetValue('UninstallString')
49 | Bits = $(if ($key -eq '\Wow6432Node') {'64'} else {'32'})
50 | Path = $program.name
51 | }
52 | }
53 | }
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Get-Lines.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/4payc9/confirm_file_length_and_format_before_loading/
2 |
3 | # this should work, but why not use get-content?
4 | # get-content -readlines 1000
5 | # see 'streamwriter example...'
6 |
7 | # !
8 | # this
9 | # $stream = New-Object System.IO.StreamReader -ArgumentList $file
10 | # is the same type as this!
11 | # $stream = [System.IO.File]::OpenText($file)
12 |
13 | function Get-Lines ([string]$file) {
14 | begin {
15 | $file = (Resolve-Path $file).ToString()
16 |
17 | if (!(Test-Path $file)) {
18 | Throw "File not found: $file"
19 | }
20 |
21 | try {
22 | #$stream = New-Object System.IO.StreamReader $file
23 | $stream = [System.IO.File]::OpenText($file)
24 | } catch {
25 | Throw $_
26 | }
27 | }
28 |
29 | process {
30 | while (!$stream.EndOfStream) {
31 | $stream.ReadLine()
32 | }
33 | $stream.Close()
34 | rv stream
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Get-LoggedOnUser.ps1:
--------------------------------------------------------------------------------
1 | # https://gallery.technet.microsoft.com/scriptcenter/0e43993a-895a-4afe-a2b2-045a5146048a
2 |
3 | function Get-LoggedOnUser ($computername = $env:COMPUTERNAME) {
4 | $regexa = '.+Domain="(.+)",Name="(.+)"$'
5 | $regexd = '.+LogonId="(\d+)"$'
6 |
7 | $logontype = @{
8 | 0 = 'Local System'
9 | 2 = 'Interactive' #(Local logon)
10 | 3 = 'Network' # (Remote logon)
11 | 4 = 'Batch' # (Scheduled task)
12 | 5 = 'Service' # (Service account logon)
13 | 7 = 'Unlock' #(Screen saver)
14 | 8 = 'NetworkCleartext' # (Cleartext network logon)
15 | 9 = 'NewCredentials' #(RunAs using alternate credentials)
16 | 10 = 'RemoteInteractive' #(RDP\TS\RemoteAssistance)
17 | 11 = 'CachedInteractive' #(Local w\cached credentials)
18 | }
19 |
20 | $logon_sessions = @(gwmi win32_logonsession -ComputerName $computername)
21 | $logon_users = @(gwmi win32_loggedonuser -ComputerName $computername)
22 |
23 | $session_user = @{}
24 |
25 | $logon_users | % {
26 | $_.antecedent -match $regexa > $nul
27 | $username = $matches[1] + "\" + $matches[2]
28 | $_.dependent -match $regexd > $nul
29 | $session = $matches[1]
30 | $session_user[$session] += $username
31 | }
32 |
33 |
34 | $logon_sessions | % {
35 | $starttime = [management.managementdatetimeconverter]::todatetime($_.starttime)
36 |
37 | New-Object psobject -Property @{
38 | Session = $_.logonid
39 | User = $session_user[$_.logonid]
40 | Type = $logontype[$_.logontype.tostring()]
41 | Auth = $_.authenticationpackage
42 | StartTime = $starttime
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Get-LogonHistory.ps1:
--------------------------------------------------------------------------------
1 | # https://social.technet.microsoft.com/Forums/office/en-US/4f6815f1-2998-484c-a423-fe6507f1548c/powershell-script-to-fetch-logonlogoff-user-on-particular-server-getwinevent-geteventlog?forum=winserverpowershell
2 |
3 | function Get-LogonHistory {
4 | param (
5 | [string]$Computer = $env:COMPUTERNAME,
6 | [int]$Days = 1
7 | )
8 |
9 | $filterXml = "
10 |
11 |
12 |
19 |
20 |
21 | "
22 | $ELogs = Get-WinEvent -FilterXml $filterXml -ComputerName $Computer
23 |
24 | # $ELogs = Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-$Days) -ComputerName $Computer
25 |
26 | if ($ELogs) {
27 | $(foreach ($Log in $ELogs) {
28 | switch ($Log.id) {
29 | 7001 {$ET = 'Logon'}
30 | 7002 {$ET = 'Logoff'}
31 | default {continue}
32 | }
33 |
34 | New-Object PSObject -Property @{
35 | Time = $Log.timecreated
36 | EventType = $ET
37 | User = (New-Object System.Security.Principal.SecurityIdentifier $Log.Properties.value.value).Translate([System.Security.Principal.NTAccount])
38 | }
39 | }) | sort time -Descending
40 | } else {
41 | Write-Host "Problem with $Computer."
42 | Write-Host "If you see a 'Network Path not found' error, try starting the Remote Registry service on that computer."
43 | Write-Host 'Or there are no logon/logoff events (XP requires auditing be turned on)'
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Get-LogonStatus.ps1:
--------------------------------------------------------------------------------
1 | # https://gallery.technet.microsoft.com/scriptcenter/Get-Remote-Logon-Status-d8c2318a
2 |
3 | function Get-LogonStatus ($computer = $env:COMPUTERNAME) {
4 | $hash = @{
5 | Computer = $computer
6 | Name = '-'
7 | User = '-'
8 | Status = '-'
9 | }
10 |
11 | $obj = gwmi win32_computersystem -ComputerName $computer -ea 0
12 | $hash.User = $obj.username
13 | $hash.Name = $obj.name
14 |
15 | try {
16 | epsr $computer
17 |
18 | if ($hash.User -notmatch '^(?:-|not logged on)$' -and (Get-Process logonui -ComputerName $computer -ErrorAction Stop)) {
19 | $hash.Status = 'Locked'
20 | }
21 | } catch {
22 | if ($hash.User -notmatch '^(?:-|not logged on)$') {
23 | $hash.Status = 'Logged on'
24 | } else {
25 | $hash.Status = 'Not logged on'
26 | }
27 | }
28 |
29 | New-Object psobject -Property $hash
30 | }
31 |
--------------------------------------------------------------------------------
/Get-MAC.ps1:
--------------------------------------------------------------------------------
1 | # http://myitpath.blogspot.com/2010/03/net-and-netbios-name-resolution.html
2 |
3 | # this gives an error if ip is IPv6 address
4 |
5 | function Get-MAC ($comp = $env:computername) {
6 | $ping = New-Object System.Net.NetworkInformation.Ping
7 | $result = $ping.Send($comp)
8 | if ($result.Status -eq 'Success') {
9 | $ip = $result.Address
10 | $port = 137
11 | $ipEP = New-Object System.Net.IPEndPoint ([ipaddress]::Parse($ip), $port)
12 | $udpconn = New-Object System.Net.Sockets.UdpClient
13 | [byte[]]$sendbytes = 0xf4,0x53,00,00,00,01,00,00,00,00,00,00,0x20,0x43,0x4b,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,00,00,0x21,00,01
14 | $udpconn.Client.ReceiveTimeout = 1000
15 | $bytesSent = $udpconn.Send($sendbytes, 50, $ipEP)
16 | $rcvbytes = $udpconn.Receive([ref]$ipEP)
17 |
18 | $mac = 0,0,0,0,0,0
19 | $j = 5
20 | for ($i = $rcvbytes.length - 1; $i -gt 0; $i--) {
21 | if ($rcvbytes[$i] -ne 0x0) {
22 | $mac[$j] = $rcvbytes[$i]
23 | $j--
24 | if ($j -eq -1) { $i = -1 }
25 | }
26 | }
27 |
28 | $macstring = New-Object System.Text.StringBuilder
29 | foreach ($byte in $mac) {
30 | [void]$macstring.Append(('{0:X2}' -f $byte) + '-')
31 | }
32 |
33 | [pscustomobject]@{
34 | Computer = $comp
35 | IP = $ip
36 | MacAddress = $macstring.ToString().Trim('-')
37 | }
38 | }
39 | }
40 |
41 | <#
42 | # http://powershell.com/cs/blogs/tips/archive/2013/11/19/getting-mac-address-remotely.aspx
43 | # tried this line also, but it needs admin rights
44 | # getmac /S $env:computername /FO CSV | ConvertFrom-Csv
45 | function Get-MAC ($comp = $env:COMPUTERNAME) {
46 | if (ping1 $comp) {
47 | nbtstat -a $comp | ? {$_ -match 'MAC Address'} | select @{n='Computer';e={$comp}}, @{n='MacAddress';e={$_.split('=')[1].trim()}}
48 | }
49 | }
50 | #>
51 |
52 |
--------------------------------------------------------------------------------
/Get-MailboxStats.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/9vlrxo/requesting_help_to_optimize_this_getmailbox_based/
2 |
3 | # took almost 7 seconds per mailbox (office 365)
4 |
5 | Write-Host 'Gathering Stats, Please Wait..'
6 |
7 | $Mailboxes = Get-Mailbox -ResultSize Unlimited | Select UserPrincipalName, Identity, ArchiveStatus
8 |
9 | $index = 0
10 | $total = @($Mailboxes).Count
11 | $starttime = $lasttime = Get-Date
12 | $MailboxSizes = foreach ($Mailbox in $Mailboxes)
13 | {
14 | $index++
15 | $currtime = (Get-Date) - $starttime
16 | $avg = $currtime.TotalSeconds / $index
17 | $last = ((Get-Date) - $lasttime).TotalSeconds
18 | $left = $total - $index
19 | $WrPrgParam = @{
20 | Activity = (
21 | "Get-MailboxStats $(Get-Date -f s)",
22 | "Total: $($currtime -replace '\..*')",
23 | "Avg: $('{0:N2}' -f $avg)",
24 | "Last: $('{0:N2}' -f $last)",
25 | "ETA: $('{0:N2}' -f ($avg * $left / 60))",
26 | "min ($([string](Get-Date).AddSeconds($avg*$left) -replace '^.* '))"
27 | ) -join ' '
28 | Status = "$index of $total ($left left) [$('{0:N2}' -f ($index / $total * 100))%]"
29 | CurrentOperation = "$Mailbox"
30 | PercentComplete = $index / $total * 100
31 | }
32 | Write-Progress @WrPrgParam
33 | $lasttime = Get-Date
34 |
35 | $MailboxStats = Get-MailboxStatistics $Mailbox.UserPrincipalname | Select LastLogonTime, @{n='TotalItemSizeGB';e={[math]::Round( (($_.TotalItemSize.Value.ToString()).Split("(")[1].Split(' ')[0].Replace(',', '') / 1GB), 2 )}}, ItemCount
36 | $MailboxFolderStats = Get-MailboxFolderStatistics $Mailbox.UserPrincipalName | Where-Object {$_.name -like 'Purges' -or $_.name -like 'DiscoveryHolds'}
37 | $MailboxPurgeFolderStats = $MailboxFolderStats | Where-Object {$_.name -like 'Purges'} | Select Name, @{n='FolderSizeGB';e={[math]::Round( ([decimal](($_.FolderSize -replace '[0-9\.]+ [A-Z]* \(([0-9,]+) bytes\)', '$1').Replace(',', '')) / 1GB), 2 )}}, ItemsInFolder
38 | $MailboxDiscoveryHoldsFolderStats = $MailboxFolderStats | Where-Object {$_.name -like 'DiscoveryHolds'} | Select Name, @{n='FolderSizeGB';e={[math]::Round( ([decimal](($_.FolderSize -replace '[0-9\.]+ [A-Z]* \(([0-9,]+) bytes\)', '$1').Replace(',', '')) / 1GB), 2 )}}, ItemsInFolder
39 |
40 | if ($Mailbox.ArchiveStatus -eq 'Active')
41 | {
42 | $ArchiveStats = Get-MailboxStatistics $Mailbox.UserPrincipalname -Archive | Select @{n='TotalItemSizeGB';e={[math]::Round( (($_.TotalItemSize.Value.ToString()).Split('(')[1].Split(' ')[0].Replace(',', '') / 1GB), 2 )}}, ItemCount
43 |
44 | $ArchiveSize = $ArchiveStats.TotalItemSizeGB
45 | $ArchiveItemCount = $ArchiveStats.ItemCount
46 | }
47 | else
48 | {
49 | $ArchiveSize = 'No Archive'
50 | $ArchiveItemCount = 'No Archive'
51 | }
52 |
53 | [pscustomobject]@{
54 | UserPrincipalName = $Mailbox.UserPrincipalName
55 | LastLoggedIn = $MailboxStats.LastLogonTime
56 | MailboxSize = $MailboxStats.TotalItemSizeGB
57 | MailboxItemCount = $MailboxStats.ItemCount
58 | PurgesFolderSize = $MailboxPurgeFolderStats.FolderSizeGB
59 | PurgeItems = $MailboxPurgeFolderStats.ItemsInFolder
60 | DiscoveryHoldsFolderSize = $MailboxDiscoveryHoldsFolderStats.FolderSizeGB
61 | DiscoveryHoldItems = $MailboxDiscoveryHoldsFolderStats.ItemsInFolder
62 | ArchiveSize = $ArchiveSize
63 | ArchiveItemCount = $ArchiveItemCount
64 | }
65 | }
66 |
67 | $MailboxSizes | Out-GridView -Title 'Mailbox and Archive Sizes'
68 |
--------------------------------------------------------------------------------
/Get-MappedDrives.ps1:
--------------------------------------------------------------------------------
1 | function Get-MappedDrives {
2 | param (
3 | $computer = $env:COMPUTERNAME
4 | )
5 |
6 | $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('Users', $computer)
7 | $reg.GetSubKeyNames() | ? {$_ -match '\d{4,5}$'} | % {
8 | $sid = $_
9 | $reg.OpenSubKey("$sid\Network").GetSubKeyNames() | % {
10 | New-Object psobject -Property @{
11 | Computer = $computer
12 | User = ([System.Security.Principal.SecurityIdentifier]($sid)).Translate([System.Security.Principal.NTAccount]).Value
13 | DriveLetter = $_
14 | Map = $reg.OpenSubKey("$sid\Network\$_").GetValue('RemotePath')
15 | }
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Get-Monitor.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/4qbvbp/get_serial_number_make_and_model_from_attached/
2 |
3 | # alternative
4 | # $Monitors = Get-WmiObject -Class Win32_PnPEntity | Where-Object Service -eq "Monitor"
5 | # https://www.reddit.com/r/PowerShell/comments/6io2ws/check_how_many_monitors_are_connected/
6 |
7 | function Get-Monitor {
8 | [CmdletBinding()]
9 | param (
10 | [Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
11 | [String[]]$ComputerName = $env:ComputerName
12 | )
13 |
14 | # List of Manufacture Codes that could be pulled from WMI and their respective full names. Used for translating later down.
15 | $ManufacturerHash = @{
16 | AAC = 'AcerView'
17 | ACR = 'Acer'
18 | AOC = 'AOC'
19 | AIC = 'AG Neovo'
20 | APP = 'Apple Computer'
21 | AST = 'AST Research'
22 | AUO = 'Asus'
23 | BNQ = 'BenQ'
24 | CMO = 'Acer'
25 | CPL = 'Compal'
26 | CPQ = 'Compaq'
27 | CPT = 'Chunghwa Pciture Tubes, Ltd.'
28 | CTX = 'CTX'
29 | DEC = 'DEC'
30 | DEL = 'Dell'
31 | DPC = 'Delta'
32 | DWE = 'Daewoo'
33 | EIZ = 'EIZO'
34 | ELS = 'ELSA'
35 | ENC = 'EIZO'
36 | EPI = 'Envision'
37 | FCM = 'Funai'
38 | FUJ = 'Fujitsu'
39 | FUS = 'Fujitsu-Siemens'
40 | GSM = 'LG Electronics'
41 | GWY = 'Gateway 2000'
42 | HEI = 'Hyundai'
43 | HIT = 'Hyundai'
44 | HSL = 'Hansol'
45 | HTC = 'Hitachi/Nissei'
46 | HWP = 'HP'
47 | IBM = 'IBM'
48 | ICL = 'Fujitsu ICL'
49 | IVM = 'Iiyama'
50 | KDS = 'Korea Data Systems'
51 | LEN = 'Lenovo'
52 | LGD = 'Asus'
53 | LPL = 'Fujitsu'
54 | MAX = 'Belinea'
55 | MEI = 'Panasonic'
56 | MEL = 'Mitsubishi Electronics'
57 | MS_ = 'Panasonic'
58 | NAN = 'Nanao'
59 | NEC = 'NEC'
60 | NOK = 'Nokia Data'
61 | NVD = 'Fujitsu'
62 | OPT = 'Optoma'
63 | PHL = 'Philips'
64 | REL = 'Relisys'
65 | SAN = 'Samsung'
66 | SAM = 'Samsung'
67 | SBI = 'Smarttech'
68 | SGI = 'SGI'
69 | SNY = 'Sony'
70 | SRC = 'Shamrock'
71 | SUN = 'Sun Microsystems'
72 | SEC = 'Hewlett-Packard'
73 | TAT = 'Tatung'
74 | TOS = 'Toshiba'
75 | TSB = 'Toshiba'
76 | VSC = 'ViewSonic'
77 | ZCM = 'Zenith'
78 | UNK = 'Unknown'
79 | _YV = 'Fujitsu'
80 | }
81 |
82 | # Takes each computer specified and runs the following code:
83 | foreach ($Computer in $ComputerName) {
84 |
85 | # Grabs the Monitor objects from WMI
86 | $Monitors = Get-WmiObject -Namespace root\WMI -Class WMIMonitorID -ComputerName $Computer -ErrorAction SilentlyContinue
87 |
88 | # Takes each monitor object found and runs the following code:
89 | foreach ($Monitor in $Monitors) {
90 |
91 | # Grabs respective data and converts it from ASCII encoding and removes any trailing ASCII null values
92 | $Mon_Model = try{ ([System.Text.Encoding]::ASCII.GetString($Monitor.UserFriendlyName)).Replace([string][char]0x0000, '') }catch{}
93 | $Mon_Serial_Number = ([System.Text.Encoding]::ASCII.GetString($Monitor.SerialNumberID)).Replace([string][char]0x0000, '')
94 | $Mon_Attached_Computer = ($Monitor.PSComputerName).Replace([string][char]0x0000, '')
95 | $Mon_Manufacturer = ([System.Text.Encoding]::ASCII.GetString($Monitor.ManufacturerName)).Replace([string][char]0x0000, '')
96 |
97 | <# Filters out "non monitors". Place any of your own filters here. These two are all-in-one computers with built in displays. I don't need the info from these.
98 | if ($Mon_Model -like '*800 AIO*' -or $Mon_Model -like '*8300 AiO*') {
99 | break
100 | }#>
101 |
102 | # Sets a friendly name based on the hash table above. If no entry found sets it to the original 3 character code
103 | $Mon_Manufacturer_Friendly = $ManufacturerHash.$Mon_Manufacturer
104 | if ($Mon_Manufacturer_Friendly -eq $null) {
105 | $Mon_Manufacturer_Friendly = $Mon_Manufacturer
106 | }
107 |
108 | # Creates a custom monitor object and fills it with 4 NoteProperty members and the respective data
109 | [pscustomobject]@{
110 | Computer = $Mon_Attached_Computer
111 | Manufacturer = $Mon_Manufacturer_Friendly
112 | Model = $Mon_Model
113 | SerialNumber = $Mon_Serial_Number
114 | YearOfManufacture = $Monitor.YearOfManufacture
115 | WeekOfManufacture = $Monitor.WeekOfManufacture
116 | }
117 | }
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/Get-NetworkShortcut.ps1:
--------------------------------------------------------------------------------
1 | # https://serverfault.com/questions/429240/how-do-you-manage-network-locations-through-domain-group-policies
2 |
3 | function Get-NetworkShortcut {
4 | param (
5 | [string]$ComputerName = $env:COMPUTERNAME
6 | )
7 |
8 | function Get-Shortcut ($path) {
9 | $WshShell = New-Object -ComObject WScript.Shell
10 | $Shortcut = $WshShell.CreateShortcut($Path)
11 | $Shortcut | select *
12 | function Release-Ref ($ref) {
13 | ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
14 | [System.GC]::Collect()
15 | [System.GC]::WaitForPendingFinalizers()
16 | }
17 | $Shortcut, $WshShell | % {$null = Release-Ref $_}
18 | }
19 |
20 | $users = dir "\\$ComputerName\c$\users" -Directory | % {$_.Name}
21 |
22 | foreach ($user in $users) {
23 | $networkshortcuts_path = "\\$ComputerName\c$\users\$user\AppData\Roaming\Microsoft\Windows\Network Shortcuts"
24 |
25 | try {
26 | $folders = dir $networkshortcuts_path -ea stop
27 | } catch {
28 | continue
29 | }
30 |
31 | foreach ($folder in $folders) {
32 | [pscustomobject]@{
33 | User = $user
34 | Name = $folder.name
35 | Target = (get-shortcut $(join-path $folder.fullname 'target.lnk')).targetpath
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Get-OfficeVersion.ps1:
--------------------------------------------------------------------------------
1 | # http://powershell.org/forums/topic/creating-a-array-of-info-for-remote-computers/#post-37990
2 | # https://www.reddit.com/r/PowerShell/comments/4gvfdg/noob_tech_question_how_would_i_query_all_domain/
3 |
4 | function Get-OfficeVersion ($computer = $env:COMPUTERNAME) {
5 | $version = 0
6 |
7 | $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
8 |
9 | try {
10 | $reg.OpenSubKey('SOFTWARE\Microsoft\Office').GetSubKeyNames() | % {
11 | if ($_ -match '(\d+)\.') {
12 | if ([int]$matches[1] -gt $version) {
13 | $version = $matches[1]
14 | }
15 | }
16 | }
17 | } catch {}
18 |
19 | $version
20 | }
21 |
--------------------------------------------------------------------------------
/Get-ParameterAliases.ps1:
--------------------------------------------------------------------------------
1 | function get-parameteraliases ($command) {
2 | (Get-Command $command).parameters.values | select name, @{n='aliases';e={$_.aliases}}
3 | }
4 |
--------------------------------------------------------------------------------
/Get-PdfText.ps1:
--------------------------------------------------------------------------------
1 | # http://powershell.org/wp/forums/topic/convertfrom-pdf-powershell-cmdlet/
2 | # https://social.technet.microsoft.com/Forums/scriptcenter/en-US/1268809d-5dc6-4cd2-a97f-a26bc3ae3a8b/using-powershell-to-parse-a-pdf-file?forum=ITCG
3 | # https://www.reddit.com/r/PowerShell/comments/4ad9gp/crappy_powershell_script_to_scrape_the_cafeteria/
4 |
5 | function Get-PdfText
6 | {
7 | [CmdletBinding()]
8 | [OutputType([string])]
9 | param (
10 | [Parameter(Mandatory = $true)]
11 | [string]
12 | $Path
13 | )
14 |
15 | $Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
16 |
17 | try
18 | {
19 | $reader = New-Object iTextSharp.text.pdf.pdfreader -ArgumentList $Path
20 | }
21 | catch
22 | {
23 | throw
24 | }
25 |
26 | $stringBuilder = New-Object System.Text.StringBuilder
27 |
28 | for ($page = 1; $page -le $reader.NumberOfPages; $page++)
29 | {
30 | $text = [iTextSharp.text.pdf.parser.PdfTextExtractor]::GetTextFromPage($reader, $page)
31 | $null = $stringBuilder.AppendLine($text)
32 | }
33 |
34 | $reader.Close()
35 |
36 | return $stringBuilder.ToString()
37 | }
38 |
--------------------------------------------------------------------------------
/Get-Powercfg.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/6lo8b5/config_settings_check/
2 |
3 | function Get-Powercfg {
4 | $schemes = powercfg /l | ? {$_ -match ':'} | % {
5 | $split = $_ -split ':|\s{2}' | % {$_.trim()}
6 |
7 | $guid = $split[1]
8 | $name = $split[2]
9 |
10 | $active = $name.endswith('*')
11 |
12 | if ($active) {
13 | $name = $name.substring(1, $name.length - 4)
14 | } else {
15 | $name = $name.substring(1, $name.length - 2)
16 | }
17 |
18 | [pscustomobject]@{
19 | GUID = $guid
20 | Name = $name
21 | Active = $active
22 | }
23 | }
24 |
25 | $props = New-Object System.Collections.ArrayList
26 | $props.AddRange(@(
27 | 'GUID'
28 | 'Name'
29 | 'Active'
30 | 'SubGUID'
31 | 'SubName'
32 | 'SubAlias'
33 | 'SettingGUID'
34 | 'SettingName'
35 | 'SettingAlias'
36 | ))
37 |
38 | $results = foreach ($scheme in $schemes) {
39 | $settings = powercfg /q $scheme.guid
40 | $settings = $settings.trim()
41 |
42 | $hash = @{
43 | GUID = $scheme.GUID
44 | Name = $scheme.Name
45 | Active = $scheme.Active
46 | }
47 |
48 | $start = $setsubguid = $subguid = $setsettingalias = 0
49 | foreach ($line in $settings) {
50 | if ($line.startswith('Subgroup GUID')) {
51 | $start = 1
52 | $split = $line -split ':|\s{2}' | % {$_.trim()}
53 | $hash.Add('SubGUID', $split[1])
54 | if ($split[2]) {
55 | $hash.Add('SubName', $split[2].substring(1, $split[2].length - 2))
56 | }
57 | $subguid = 1
58 | $setsubguid = 1
59 | } elseif ($line.StartsWith('GUID Alias') -and $subguid -eq 1) {
60 | $hash.Add('SubAlias', $line.Split(':', 2)[1].trim())
61 | $subguid = 0
62 | } elseif ($line.StartsWith('Power Setting GUID')) {
63 | if (!$setsubguid) {
64 | $i = $back = 0
65 | while ($hash.Keys -notcontains 'SubGUID' -and $i -ge 0) {
66 | $back++
67 | $i = $settings.IndexOf($line) - $back
68 | $ln = $settings[$i]
69 | if ($ln.startswith('Subgroup GUID')) {
70 | $split = $ln -split ':|\s{2}' | % {$_.trim()}
71 | $hash.Add('SubGUID', $split[1])
72 | if ($split[2]) {
73 | $hash.Add('SubName', $split[2].substring(1, $split[2].length - 2))
74 | }
75 | $setsubguid = 1
76 | $ln = $settings[$i + 1]
77 | if ($ln.StartsWith('GUID Alias')) {
78 | $hash.Add('SubAlias', $ln.Split(':', 2)[1].trim())
79 | }
80 | }
81 | }
82 | }
83 | $split = $line -split ':|\s{2}' | % {$_.trim()}
84 | $hash.Add('SettingGUID', $split[1])
85 | if ($split[2]) {
86 | $hash.Add('SettingName', $split[2].substring(1, $split[2].length - 2))
87 | }
88 | } elseif ($line.StartsWith('GUID Alias')) {
89 | if (!$start) {
90 | continue
91 | }
92 | $hash.Add('SettingAlias', $line.Split(':', 2)[1].trim())
93 | $setsettingalias = 1
94 | } elseif ($line -match ':') {
95 | if (!$setsettingalias) {
96 | $setsettingalias = 1
97 | continue
98 | }
99 | $split = $line.Split(':', 2).trim()
100 | $split[0] = $split[0].Replace(' ', '')
101 | $num = 0
102 | $new = $split[0] + $num
103 | while ($hash.Keys -contains $new) {
104 | $num++
105 | $new = $split[0] + $num
106 | }
107 | $hash.Add($new, $split[1])
108 | if (!$props.Contains($new)) {
109 | $props.Add($new) | Out-Null
110 | }
111 | } else {
112 | [pscustomobject]$hash
113 | $hash = @{
114 | GUID = $scheme.GUID
115 | Name = $scheme.Name
116 | Active = $scheme.Active
117 | }
118 | $setsubguid = 0
119 | }
120 | }
121 | }
122 |
123 | $results | select $props
124 | }
125 |
--------------------------------------------------------------------------------
/Get-PrinterClients.ps1:
--------------------------------------------------------------------------------
1 | # KNOWN ISSUES:
2 | # only finds printers that are *NOT* locally hosted
3 | # if looking for all possible printers, might have to use Get-PrinterHosts as well
4 | #
5 | # REQUIRES:
6 | # admin rights
7 |
8 | function Get-PrinterClients {
9 | Param (
10 | [string]$comp = $env:COMPUTERNAME
11 | )
12 |
13 | if (!$comp) { throw 'No comp.' }
14 |
15 | $ping = New-Object System.Net.NetworkInformation.Ping
16 | try {
17 | $result = $ping.Send($comp)
18 | } catch {
19 | $result = $null
20 | }
21 |
22 | if ($result.Status -eq 'Success') {
23 | $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('Users', $comp)
24 | [string[]]$users = $reg.GetSubKeyNames() | ? {$_ -match '-\d{5}$'}
25 | foreach ($user in $users) {
26 | try {
27 | $printers = $reg.OpenSubKey("$user\printers\connections").GetSubKeyNames()
28 | } catch {
29 | $printers = '-'
30 | }
31 |
32 | if ($printers -ne '-') {
33 | $printers = @($printers | % {$_.Substring(2).Replace(',', '\').ToUpper()} | select -Unique) -join '; '
34 | }
35 |
36 | [pscustomobject]@{
37 | Computer = $comp
38 | IP = $result.Address.ToString()
39 | User = ([System.Security.Principal.SecurityIdentifier]($user)).Translate([System.Security.Principal.NTAccount]).Value
40 | Printer = $printers
41 | }
42 | }
43 | } else {
44 | [pscustomobject]@{
45 | Computer = $comp
46 | IP = '-'
47 | User = '-'
48 | Printer = '-'
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Get-PrinterHosts.ps1:
--------------------------------------------------------------------------------
1 |
2 | # need admin rights
3 | # if you include USB printers on workstations, it picks up peoples home usb printers as well...
4 | # also including shared printers may include home printers
5 |
6 | function Get-PrinterHosts {
7 | Param (
8 | [string]$comp = $env:COMPUTERNAME
9 | )
10 |
11 | if (!$comp) { throw 'No comps.' }
12 |
13 | $ping = New-Object System.Net.NetworkInformation.Ping
14 | try {
15 | $result = $ping.Send($comp)
16 | } catch {
17 | $result = $null
18 | }
19 |
20 | if ($result.Status -eq 'Success') {
21 | $printers = Get-WmiObject Win32_Printer -ComputerName $comp | select name, sharename, systemname, portname, shared, printerpapernames, capabilitydescriptions, location, comment, drivername
22 |
23 | # get the ip address
24 | $ip = $result.Address.ToString()
25 |
26 | foreach ($printer in $printers) {
27 | [pscustomobject]@{
28 | Computer = $comp.ToUpper()
29 | ComputerIP = $ip
30 | Printer = $printer.Name.ToUpper()
31 | ShareName = $(try { $printer.ShareName.ToUpper() } catch { $null })
32 | SystemName = $(if ($printer.SystemName.StartsWith('\')) {$printer.SystemName.Substring(2).ToUpper()} else {$printer.SystemName.ToUpper()})
33 | Location = $(try { $printer.Location } catch { $null })
34 | Comment = $(try { $printer.Comment } catch { $null })
35 | DriverName = $(try { $printer.DriverName } catch { $null })
36 | Port = $printer.PortName
37 | Shared = $printer.Shared
38 | PrinterPaperNames = $printer.PrinterPaperNames
39 | CapabilityDescriptions = $printer.CapabilityDescriptions
40 | }
41 | }
42 | } else {
43 | [pscustomobject]@{
44 | Computer = $comp.ToUpper()
45 | ComputerIP = '-'
46 | Printer = '-'
47 | ShareName = '-'
48 | SystemName = '-'
49 | Location = '-'
50 | Comment = '-'
51 | DriverName = '-'
52 | Port = '-'
53 | Shared = '-'
54 | PrinterPaperNames = '-'
55 | CapabilityDescriptions = '-'
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Get-ProxyAddresses.ps1:
--------------------------------------------------------------------------------
1 | # to get primary or secondary
2 | # $addresses = Get-ProxyAddresses | select *, @{n='IsSecondary';e={if ($_.addr.startswith('smtp')) {$true} else {$false}}}
3 |
4 | # to get those that do not have a secondary
5 | # $addresses | group name | ? count -eq 1 | % group
6 |
7 | function Get-ProxyAddresses {
8 | Connect-AzureAD | Out-Null
9 |
10 | #$accts = $(Get-MsolUser -All; Get-MsolGroup -All)
11 | $accts = $(Get-AzureADUser -All:$true; Get-AzureADGroup -All:$true)
12 |
13 | $(foreach ($acct in $accts) {
14 | if ($acct.lastdirsynctime) {
15 | $sync = 'AD'
16 | } else {
17 | $sync = 'o365'
18 | }
19 |
20 | if ($acct.signinname) {
21 | $type = 'User'
22 |
23 | $signinname = [pscustomobject]@{
24 | Name = $acct.DisplayName
25 | Sync = $sync
26 | Type = $type
27 | Addr = $acct.signinname.trim()
28 | }
29 | } else {
30 | $type = 'Group'
31 | }
32 |
33 | if ($acct.userprincipalname) {
34 | $upn = [pscustomobject]@{
35 | Name = $acct.DisplayName
36 | Sync = $sync
37 | Type = $type
38 | Addr = $acct.userprincipalname.trim()
39 | }
40 | }
41 |
42 | $proxy = @(foreach ($addr in $acct.proxyaddresses) {
43 | [pscustomobject]@{
44 | Name = $acct.displayname
45 | Sync = $sync
46 | Type = $type
47 | Addr = $addr.trim()
48 | }
49 | })
50 |
51 | if (('smtp:' + $signinname.Addr) -notin $proxy.addr) {
52 | $proxy += $signinname
53 | }
54 |
55 | if (('smtp:' + $upn.addr) -notin $proxy.addr) {
56 | $proxy += $upn
57 | }
58 |
59 | foreach ($altEA in $acct.AlternateEmailAddresses) {
60 | $alt = [pscustomobject]@{
61 | Name = $acct.DisplayName
62 | Sync = $sync
63 | Type = $type
64 | Addr = $altEA.trim()
65 | }
66 |
67 | if (('smtp:' + $alt.addr) -notin $proxy.addr) {
68 | $proxy += $alt
69 | }
70 | }
71 |
72 | $proxy
73 |
74 | }) | select * -Unique
75 | }
76 |
--------------------------------------------------------------------------------
/Get-SKU.ps1:
--------------------------------------------------------------------------------
1 | ## INFO
2 | # get SystemSKU of remote computer
3 | # (gwmi -n root\wmi ms_systeminformation).systemsku
4 |
5 | function Get-SKU {
6 | param (
7 | [object]$comps = $env:COMPUTERNAME
8 | )
9 |
10 | foreach ($computer in $comps) {
11 | try {
12 | # (gp 'HKLM:\HARDWARE\DESCRIPTION\System\BIOS').SystemSku
13 | # reg query \\$computer\HKLM\HARDWARE\DESCRIPTION\System\BIOS /v SystemSku
14 | [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer).OpenSubKey('HARDWARE\DESCRIPTION\System\BIOS').GetValue('SystemSku')
15 | } catch {
16 | try {
17 | # WMIC /NODE: "`"$computer"`" /NAMESPACE:\\root\wmi path MS_SystemInformation
18 | (Get-WMIObject -Namespace root\wmi -Class MS_SystemInformation -ComputerName $computer).SystemSKU
19 | } catch {
20 | return 'Error'
21 | }
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Get-SNMPData.ps1:
--------------------------------------------------------------------------------
1 |
2 | # get snmp description and name
3 |
4 | function Get-SNMPData {
5 | param (
6 | [string]$ip
7 | )
8 |
9 | begin {
10 | $ping = New-Object System.Net.NetworkInformation.Ping
11 | $snmp = New-Object -ComObject olePrn.OleSNMP
12 | }
13 |
14 | process {
15 | $info = [pscustomobject]@{
16 | IP = $ip
17 | Name = ''
18 | Description = ''
19 | Addresses = ''
20 | Online = $false
21 | }
22 |
23 | if ($ping.Send($ip).Status -eq 'Success') {
24 | $info.Online = $true
25 |
26 | $snmp.Open($ip, 'public', 2, 3000)
27 |
28 | try {
29 | $info.Name = $snmp.Get('.1.3.6.1.2.1.1.5.0')
30 | $info.Description = $snmp.Get('.1.3.6.1.2.1.1.1.0')
31 | $info.Addresses = ($snmp.Gettree('.1.3.6.1.2.1.4.20.1.1') | ? {$_ -match '(?:[^\.]{1,3}\.){3}[^\.]{1,3}$' -and $_ -notmatch '127\.0\.0\.1'} | % {$i = $_.split('.'); "$($i[-4]).$($i[-3]).$($i[-2]).$($i[-1])"}) -join ';'
32 | } catch {}
33 | }
34 |
35 | Write-Output $info
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Get-ShaHash.ps1:
--------------------------------------------------------------------------------
1 | function Get-ShaHash {
2 | param (
3 | [Parameter(ValueFromPipeline=$true)]
4 | [string]$file,
5 | [ValidateSet(1, 256, 384, 512)]
6 | [int]$bit = 512
7 | )
8 |
9 | begin {
10 | function Resolve-FullPath ([string]$Path) {
11 | if ( -not ([IO.Path]::IsPathRooted($Path)) ) {
12 | $Path = Join-Path $PWD $Path
13 | }
14 | [IO.Path]::GetFullPath($Path)
15 | }
16 | }
17 |
18 | process {
19 | $file = Resolve-FullPath $file
20 |
21 | $sha = New-Object System.Security.Cryptography.SHA$bit`CryptoServiceProvider
22 | $hash = [BitConverter]::ToString($sha.ComputeHash([IO.File]::ReadAllBytes([IO.FileInfo]$file)))
23 | $hash
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Get-ShortPath.ps1:
--------------------------------------------------------------------------------
1 | filter Get-ShortPath {
2 | param (
3 | [Parameter(ValueFromPipeline=$true)]
4 | [string]$obj
5 | )
6 |
7 | begin {
8 | $fso = New-Object -ComObject Scripting.FileSystemObject
9 | function Release-Ref ($ref) {
10 | ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
11 | [System.GC]::Collect()
12 | [System.GC]::WaitForPendingFinalizers()
13 | }
14 | }
15 |
16 | process {
17 | if (!$obj) {$obj = $pwd}
18 |
19 | $file = gi $obj
20 | if ($file.psiscontainer) {
21 | $fso.getfolder($file.fullname).ShortPath
22 | } else {
23 | $fso.getfile($file.fullname).ShortPath
24 | }
25 | }
26 |
27 | end {
28 | $null = Release-Ref $fso
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Get-Shortcut.ps1:
--------------------------------------------------------------------------------
1 | # Get-Shortcut
2 | #
3 | # Arguments
4 | # Description
5 | # FullName
6 | # Hotkey
7 | # IconLocation = '%SystemRoot%\system32\SHELL32.dll,16' # printer
8 | # RelativePath
9 | # TargetPath
10 | # WindowStyle
11 | # WorkingDirectory
12 |
13 | function Get-Shortcut {
14 | param (
15 | [parameter(mandatory=$true)]
16 | [string]$Path
17 | )
18 |
19 | begin {
20 | $WshShell = New-Object -ComObject WScript.Shell
21 | }
22 |
23 | process {
24 | if (!$Path) {Throw 'No Source'}
25 |
26 | $Shortcut = $WshShell.CreateShortcut($Path)
27 | $Shortcut | select *
28 | }
29 |
30 | end {
31 | function Release-Ref ($ref) {
32 | ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
33 | [System.GC]::Collect()
34 | [System.GC]::WaitForPendingFinalizers()
35 | }
36 | $Shortcut, $WshShell | % {$null = Release-Ref $_}
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Get-User.ps1:
--------------------------------------------------------------------------------
1 | ## INFO
2 | # find last logged on user of remote computer
3 |
4 | # https://www.reddit.com/r/PowerShell/comments/448gdx/noob_need_help_getting_a_list_with_all_xp/
5 |
6 | # get-ciminstance is the successor, but it doesn't work for me...
7 | # http://powershell.com/cs/forums/t/23349.aspx
8 |
9 | # (gp "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI").lastloggedonuser
10 | # reg query \\$computer\HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI /v LastLoggedOnUser
11 | # [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer).OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI').getvalue('LastLoggedOnUser')
12 |
13 | # (gwmi win32_loggedonuser).antecedent # this is remote connections, not necessarily logons. includes computers and users connected to print servers
14 |
15 | # get remote computer idle time!
16 | # http://stackoverflow.com/questions/38664300/log-off-multiple-idle-users
17 |
18 | <#
19 | $owners = @{}
20 | gwmi win32_process -computer $env:computername -Filter 'name = "explorer.exe"' | % {$owners[$_.handle] = $_.getowner().user}
21 | get-process -computer $env:computername explorer | % {$owners[$_.id.tostring()]}
22 | #>
23 |
24 | <# all give about the same information. the first two might give more
25 | # https://www.reddit.com/r/PowerShell/comments/4dwqlc/crypto_tripwire_-_help_with_script/d1v0jg5?context=3
26 | (quser) -replace '\s{2,}', ',' | ConvertFrom-Csv
27 | $server = 'localhost'
28 |
29 | # IDENTICAL
30 | query session /server:$server
31 | qwinsta /server:$server
32 |
33 | # IDENTICAL
34 | query user /server:$server
35 | quser /server:$server
36 |
37 | qprocess explorer.exe /server:$server
38 | #>
39 |
40 | function Get-User {
41 | param (
42 | [string]$comp = $env:COMPUTERNAME,
43 | [ValidateSet('computersystem', 'process', 'dir')]
44 | $method = 'computersystem'
45 | )
46 |
47 | switch ($method) {
48 | 'dir' {
49 | Get-ChildItem \\$comp\c$\users -Directory -Exclude '*$*' | % {Get-ChildItem $_.FullName ntuser.dat* -Force -ea 0} | sort LastWriteTime -Descending | select @{n='Computer';e={$comp}}, @{n='User';e={Split-Path (Split-Path $_.FullName) -Leaf}}, LastWriteTime | ? user -notmatch '\.net'| group computer, user | % {$_.group | select -f 1}
50 | }
51 |
52 | 'computersystem' {
53 | try {
54 | (Get-WmiObject win32_computerSystem -ComputerName $comp).username
55 | } catch {
56 | try {
57 | [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $comp).OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI').getvalue('LastLoggedOnUser')
58 | Get-WmiObject Win32_NetworkLoginProfile -ComputerName $comp
59 | } catch {
60 | 'Error'
61 | }
62 | }
63 | }
64 |
65 | 'process' {
66 | $owners = @{}
67 | Get-WmiObject win32_process -Filter 'name = "explorer.exe"' -ComputerName $comp | % {$owners[$_.handle] = $_.getowner().user}
68 | Get-Process explorer -ComputerName $comp | % {$owners[$_.id.tostring()]}
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/GithubRestApi.ps1:
--------------------------------------------------------------------------------
1 | # https://www.reddit.com/r/PowerShell/comments/lb2j6j/managing_github_files_via_rest_api/
2 | # https://docs.github.com/en/rest/reference/repos#get-repository-content
3 |
4 | # create token https://github.com/settings/tokens
5 | # https://channel9.msdn.com/Blogs/trevor-powershell/Automating-the-GitHub-REST-API-Using-PowerShell
6 | # https://web.archive.org/web/20211109164206/https://channel9.msdn.com/Blogs/trevor-powershell/Automating-the-GitHub-REST-API-Using-PowerShell
7 |
8 | function git-createfile {
9 | param (
10 | $token,
11 | $message = '',
12 | $content,
13 | $owner,
14 | $repo,
15 | $path = '.\'
16 | )
17 |
18 | $base64token = [System.Convert]::ToBase64String([char[]]$token)
19 |
20 | $headers = @{
21 | Authorization = 'Basic {0}' -f $base64token
22 | }
23 |
24 | $body = @{
25 | message = $message
26 | content = [System.Convert]::ToBase64String([char[]]$($content))
27 | } | ConvertTo-Json
28 |
29 | Invoke-RestMethod -Headers $headers -Uri https://api.github.com/repos/$owner/$repo/contents/$path -Body $body -Method Put
30 | }
31 |
32 | # git-createfile -token '' -owner gangstanthony -repo MyProject -path 'test/output.txt' -content 'hello world'
33 |
34 |
35 | function git-getfile {
36 | param (
37 | $token,
38 | $owner,
39 | $repo,
40 | $path
41 | )
42 |
43 | $base64token = [System.Convert]::ToBase64String([char[]]$token)
44 |
45 | $headers = @{
46 | Authorization = 'Basic {0}' -f $base64token
47 | accept = 'application/vnd.github.v3+json'
48 | }
49 |
50 | Invoke-RestMethod -Headers $headers -Uri https://api.github.com/repos/$owner/$repo/contents/$path -Method Get | select *, @{n='content_decoded';e={[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($_.content))}}
51 | }
52 |
53 | # git-getfile -token '' -owner gangstanthony -repo MyProject -path 'test/output.txt'
54 |
55 |
56 | function git-updatefile {
57 | # requires git-getfile
58 | param (
59 | $token,
60 | $message = '',
61 | $content,
62 | $sha,
63 | $owner,
64 | $repo,
65 | $path
66 | )
67 |
68 | $base64token = [System.Convert]::ToBase64String([char[]]$token)
69 |
70 | $headers = @{
71 | Authorization = 'Basic {0}' -f $base64token
72 | }
73 |
74 | if (!$sha) {
75 | $sha = (git-getfile -token $token -owner $owner -repo $repo -path $path).sha
76 | }
77 |
78 | $body = @{
79 | message = $message
80 | content = [System.Convert]::ToBase64String([char[]]$($content))
81 | sha = $sha
82 | } | ConvertTo-Json
83 |
84 | Invoke-RestMethod -Headers $headers -Uri https://api.github.com/repos/$owner/$repo/contents/$path -Body $body -Method Put
85 | }
86 |
87 | # git-updatefile -token '' -owner gangstanthony -repo MyProject -path 'test/output.txt' -content 'newtext'
88 |
89 |
90 | function git-deletefile {
91 | # requires git-getfile
92 | param (
93 | $token,
94 | $message = '',
95 | $sha,
96 | $owner,
97 | $repo,
98 | $path
99 | )
100 |
101 | $base64token = [System.Convert]::ToBase64String([char[]]$token)
102 |
103 | $headers = @{
104 | Authorization = 'Basic {0}' -f $base64token
105 | }
106 |
107 | if (!$sha) {
108 | $sha = (git-getfile -token $token -owner $owner -repo $repo -path $path).sha
109 | }
110 |
111 | $body = @{
112 | message = $message
113 | sha = $sha
114 | } | ConvertTo-Json
115 |
116 | Invoke-RestMethod -Headers $headers -Uri https://api.github.com/repos/$owner/$repo/contents/$path -Body $body -Method Delete
117 | }
118 |
119 | # git-deletefile -token '' -owner gangstanthony -repo MyProject -path 'test/output.txt'
120 |
121 |
122 | function git-uploadfile {
123 | param (
124 | $token,
125 | $message = '',
126 | $file,
127 | $owner,
128 | $repo,
129 | $path = '.\',
130 | $sha,
131 | [switch]$force
132 | )
133 |
134 | $path = (Join-Path $path (Split-Path $file -Leaf))
135 |
136 | $base64token = [System.Convert]::ToBase64String([char[]]$token)
137 |
138 | $headers = @{
139 | Authorization = 'Basic {0}' -f $base64token
140 | }
141 |
142 | if ($force -and !$sha) {
143 | $sha = $(
144 | try {
145 | (git-getfile -token $token -owner $owner -repo $repo -path $path).sha
146 | } catch {
147 | $null
148 | }
149 | )
150 | }
151 |
152 | $body = @{
153 | message = $message
154 | content = [convert]::ToBase64String((Get-Content $file -Encoding Byte))
155 | sha = $sha
156 | } | ConvertTo-Json
157 |
158 | Invoke-RestMethod -Headers $headers -Uri https://api.github.com/repos/$owner/$repo/contents/$path -Body $body -Method Put
159 | }
160 |
161 | # git-uploadfile -token '' -file 'C:\temp\MsWordExample.docx' -owner gangstanthony -repo MyProject -path test -force
162 |
163 |
--------------------------------------------------------------------------------
/Greenshot.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangstanthony/PowerShell/df7e9de1bfc0149f6b900ec65679516c5ed7503a/Greenshot.exe
--------------------------------------------------------------------------------
/How_to_Make_a_PowerShell_Script_Wait_for_a_Specific_Condition.ps1:
--------------------------------------------------------------------------------
1 |
2 | $VerbosePreference = 'Continue'
3 |
4 | ## sleep while the whatever condition is not met yet
5 | while (-not (Test-Path -Path 'C:\test.txt')) {
6 | Start-Sleep -Seconds 1
7 | Write-Verbose -Message "Still waiting for action to complete..."
8 | }
9 |
10 | ## The stopwatch
11 |
12 | $timer = [Diagnostics.Stopwatch]::StartNew()
13 | $timer.Elapsed.TotalSeconds
14 | $timer.Stop()
15 |
16 | $timer = [Diagnostics.Stopwatch]::StartNew()
17 | while (($timer.Elapsed.TotalSeconds -lt 10) -and (-not (Test-Path -Path 'C:\test.txt'))) {
18 | Start-Sleep -Seconds 1
19 | $totalSecs = [math]::Round($timer.Elapsed.TotalSeconds, 0)
20 | Write-Verbose -Message "Still waiting for action to complete after [$totalSecs] seconds..."
21 | }
22 |
23 | function Wait-Action {
24 | <#
25 | .SYNOPSIS
26 | A script to wait for an action to finish.
27 |
28 | .DESCRIPTION
29 | This script executes a scriptblock represented by the Condition parameter continually while the result returns
30 | anything other than $false or $null.
31 |
32 | .PARAMETER Condition
33 | A mandatory scriptblock parameter representing the code to execute to check the action condition. This code
34 | will be continually executed until it returns $false or $null.
35 |
36 | .PARAMETER Timeout
37 | A mandatory integer represneting the time (in seconds) to wait for the condition to complete.
38 |
39 | .PARAMETER ArgumentList
40 | An optional collection of one or more objects to pass to the scriptblock at run time. To use this parameter,
41 | be sure you have a param() block in the Condition scriptblock to accept these parameters.
42 |
43 | .PARAMETER RetryInterval
44 | An optional integer representing the time (in seconds) between the code execution in Condition.
45 |
46 | .EXAMPLE
47 | PS> Wait-Action -Condition { (Get-Job).State | where { $_ -ne 'Running' } -Timeout 10
48 |
49 | This example will wait for all background jobs to complete for up to 10 seconds.
50 | #>
51 |
52 | [OutputType([void])]
53 | [CmdletBinding()]
54 | param
55 | (
56 | [Parameter(Mandatory)]
57 | [ValidateNotNullOrEmpty()]
58 | [scriptblock]$Condition,
59 |
60 | [Parameter(Mandatory)]
61 | [ValidateNotNullOrEmpty()]
62 | [int]$Timeout,
63 |
64 | [Parameter()]
65 | [ValidateNotNullOrEmpty()]
66 | [object[]]$ArgumentList,
67 |
68 | [Parameter()]
69 | [ValidateNotNullOrEmpty()]
70 | [int]$RetryInterval = 5
71 | )
72 | try {
73 | $timer = [Diagnostics.Stopwatch]::StartNew()
74 | while (($timer.Elapsed.TotalSeconds -lt $Timeout) -and (& $Condition $ArgumentList)) {
75 | Start-Sleep -Seconds $RetryInterval
76 | $totalSecs = [math]::Round($timer.Elapsed.TotalSeconds, 0)
77 | Write-Verbose -Message "Still waiting for action to complete after [$totalSecs] seconds..."
78 | }
79 | $timer.Stop()
80 | if ($timer.Elapsed.TotalSeconds -gt $Timeout) {
81 | throw 'Action did not complete before timeout period.'
82 | } else {
83 | Write-Verbose -Message 'Action completed before timeout period.'
84 | }
85 | } catch {
86 | Write-Error -Message $_.Exception.Message
87 | }
88 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 gangstanthony
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Logoff-User.ps1:
--------------------------------------------------------------------------------
1 | function Logoff-User ($Name, $Server) {
2 | if (!(gcm quser -ea 0)) {
3 | throw 'could not find quser.exe'
4 | }
5 |
6 | $users = quser /server:$Server | select -Skip 1
7 |
8 | if ($Name) {
9 | $user = $users | ? {$_ -match $Name}
10 | } else {
11 | $user = $users | Out-Menu
12 | }
13 |
14 | $id = ($user.split() | ? {$_})[2]
15 |
16 | if ($id -match 'disc') {
17 | $id = ($user.split() | ? {$_})[1]
18 | }
19 |
20 | logoff $id /server:$Server
21 | }
22 |
--------------------------------------------------------------------------------
/New-NetworkShortcut.ps1:
--------------------------------------------------------------------------------
1 | # https://serverfault.com/questions/429240/how-do-you-manage-network-locations-through-domain-group-policies
2 |
3 | function New-NetworkShortcut {
4 | param (
5 | [Parameter(Mandatory=$true)] [string]$Name,
6 | [Parameter(Mandatory=$true)] [string]$Target,
7 | [string]$ComputerName = $env:COMPUTERNAME,
8 | [string]$SAM = $env:USERNAME
9 | )
10 |
11 | $networkshortcut_name = $Name
12 | $networkshortcut_target = $Target
13 |
14 | # doesn't work in posh v2
15 | #$networkshortcuts_path = [Environment]::GetFolderPath('NetworkShortcuts')
16 | $networkshortcuts_path = "\\$ComputerName\c$\users\$SAM\AppData\Roaming\Microsoft\Windows\Network Shortcuts"
17 | if (!(Test-Path $networkshortcuts_path)) {
18 | md $networkshortcuts_path
19 | }
20 |
21 | $networkshortcut_path = "$networkshortcuts_path\$networkshortcut_name"
22 | $desktopini_path = "$networkshortcut_path\desktop.ini"
23 | $targetlnk_path = "$networkshortcut_path\target.lnk"
24 |
25 | $desktopini_text = "[.ShellClassInfo]`r`nCLSID2={0AFACED1-E828-11D1-9187-B532F1E9575D}`r`nFlags=2"
26 |
27 | if (Test-Path -Path $networkshortcut_path -PathType Container) {
28 | Remove-Item -Path $networkshortcut_path -Recurse -Force
29 | }
30 |
31 | [void](New-Item -Path $networkshortcut_path -ItemType directory)
32 |
33 | Set-ItemProperty -Path $networkshortcut_path -Name Attributes -Value 1
34 |
35 | Out-File -FilePath $desktopini_path -InputObject $desktopini_text -Encoding ascii
36 |
37 | Set-ItemProperty -Path $desktopini_path -Name Attributes -Value 6
38 |
39 | $WshShell = New-Object -com WScript.Shell
40 | $Shortcut = $WshShell.CreateShortcut($targetlnk_path)
41 | $Shortcut.TargetPath = $networkshortcut_target
42 | $Shortcut.Save()
43 | }
44 |
--------------------------------------------------------------------------------
/PRobocopy.ps1:
--------------------------------------------------------------------------------
1 | function PRobocopy {
2 | param (
3 | [string]$Source = $PWD,
4 | [string]$Destination = 'NULL',
5 | [string[]]$Include,
6 | [long]$Retries = 1000000,
7 | [long]$WaitTime = 30,
8 | [string]$ExcludeAttributes, # RASHCNETO
9 | [switch]$ExcludeChanged,
10 | [switch]$ExcludeNewer,
11 | [switch]$ExcludeOlder,
12 | [switch]$ListOnly,
13 | [switch]$Recurse,
14 | [switch]$NoJobHeader,
15 | [switch]$Bytes,
16 | [switch]$FullPathname,
17 | [switch]$NoClass,
18 | [switch]$NoDirectoryList,
19 | [switch]$TimeStamps,
20 | [switch]$ExcludeJunctions,
21 | [switch]$Mirror,
22 | [switch]$FATFileTimes,
23 | [switch]$Restartable
24 | )
25 |
26 | if ($Source, $Destination, $Include, $ExcludeAttributes, $args -match '\?') {
27 | cmd /c Robocopy.exe /?
28 | return
29 | }
30 | if (!$Source) { Throw 'No source directory provided' }
31 |
32 | $params = @()
33 | if ($Destination.ToUpper() -eq 'NULL') {$params += '/L'}
34 | if ($Retries -ne 1000000) {$params += "/R:$Retries"}
35 | if ($WaitTime -ne 30) {$params += "/W:$WaitTime"}
36 | if ($ExcludeAttributes) {$params += "/XA:$ExcludeAttributes"} # need to add validation
37 | if ($ExcludeChanged) {$params += '/XC'}
38 | if ($ExcludeNewer) {$params += '/XN'}
39 | if ($ExcludeOlder) {$params += '/XO'}
40 | if ($ListOnly) {$params += '/L'}
41 | if ($Recurse) {$params += '/S'}
42 | if ($NoJobHeader) {$params += '/NJH'}
43 | if ($Bytes) {$params += '/BYTES'}
44 | if ($FullPathname) {$params += '/FP'}
45 | if ($NoClass) {$params += '/NC'}
46 | if ($NoDirectoryList) {$params += '/NDL'}
47 | if ($TimeStamps) {$params += '/TL'}
48 | if ($ExcludeJunctions) {$params += '/XJ'}
49 | if ($Mirror) {$params += '/MIR'}
50 | if ($FATFileTimes) {$params += '/FFT'}
51 | if ($Restartable) {$params += '/Z'}
52 | if ($Include) {$params += $Include}
53 |
54 | # Debugging
55 | #$Source
56 | #$Destination
57 | #$params
58 |
59 | robocopy $Source $Destination $params
60 | }
61 |
62 | #cls
63 | #PRobocopy 'path' -Include *.txt, *.ps1 -ExcludeAttributes H -ExcludeChanged -ExcludeNewer -ExcludeOlder -ListOnly -Subdirectories -NoJobHeader -Bytes -FullPathname -NoClass -NoDirectoryList -TimeStamps -ExcludeJunctions -Retries 0 -WaitTime 0 -Mirror -Restartable -FATFileTimes
64 |
--------------------------------------------------------------------------------
/Pulseway_Desktop_Icon.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | ==============================================================================
3 | Create Desktop Icon to Pulseway Support Request
4 | ============+=================================================================
5 | Created: [05/17/2018]
6 | Author: Ethan Bell
7 | ==============================================================================
8 | Modified:
9 | Modifications:
10 | ==============================================================================
11 | Purpose: Create a desktop icon in public profile for Pulseway Support Request
12 | Filename: Pulseway_Desktop_Icon_Support.ps1
13 | ==============================================================================
14 | #>
15 | $TargetApplication = "C:\Program Files\Pulseway\pcmontask.exe"
16 | $TargetArguments = " support"
17 | $ShortcutFile = "$env:Public\Desktop\Get Support.lnk"
18 | $WScriptShell = New-Object -ComObject WScript.Shell
19 | $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
20 | $Shortcut.TargetPath = $TargetApplication
21 | $Shortcut.Arguments = $TargetArguments
22 | $Shortcut.Save()
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PowerShell
2 | My PS Scripts
3 |
4 | Get-FolderAccess screenshot: http://i.imgur.com/21LhwVy.jpg
5 |
6 | Copy-File screenshot: http://imgur.com/hT8yoUm.jpg
7 |
--------------------------------------------------------------------------------
/Reboot.ps1:
--------------------------------------------------------------------------------
1 | <