Windows/powershell: Unterschied zwischen den Versionen

Aus SchnallIchNet
Wechseln zu: Navigation, Suche
(Pull pending updates and install)
Zeile 133: Zeile 133:
 
== Logging ==
 
== Logging ==
  
Filter log by EventID:
+
=== Filter log by EventID ===
  
 
  Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `
 
  Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `
 
  select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"
 
  select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"
 +
 +
 +
=== Get reboot source/reason ===
 +
 +
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap
  
  

Version vom 20. Mai 2021, 11:07 Uhr

Snippets for powershell
Note that Exchange-related powershell commands should be listed here

execution policy

Set-ExecutionPolicy Unrestricted

possible values:

help about_Execution_Policies


external AD-snapin

http://software.dell.com/products/active-roles/powershell.aspx

Nach der Installation dann mit folgendem command einbinden:

Add-PSSnapin Quest.ActiveRoles.ADManagement

Und damit kannst du dann tolle Sachen machen wie:

Get-QADGroup -ContainsMember username


get loadable modules

Get-Module -ListAvailable


import system modules

ImportSystemModules


VEEAM Snapin

asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue

Remoting

Enter-PSSession -computername <computername>
[<computername>]: PS C:\>


Set Systemvariables (persistent)

[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")
  1. Variable Name
  2. Value
  3. Scope: User or Machine

To see such changes you need to start a new Powershell window
and enter:

Get-ChildItem env:

or

Get-ChildItem env:CHRIS

or

Get-ChildItem env:CHR*


get/set registry keys

get item(s):

Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl

new folder:

New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null

new item:

New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null


set AD password

Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)


Clean WinSxS folder

to remove unneeded stuff from c:\windows\WinSxS\*.*
do the following:

Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove


get/set netconnectionprofile

PS C:\> Get-NetConnectionProfile

Name : arifleet.com
InterfaceAlias : Internal
InterfaceIndex : 1
NetworkCategory : DomainAuthenticated
IPv4Connectivity : LocalNetwork
IPv6Connectivity : LocalNetwork

Name : Network
InterfaceAlias : Internet
InterfaceIndex : 3
NetworkCategory : Public
IPv4Connectivity : LocalNetwork
IPv6Connectivity : LocalNetwork

PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private

If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,
restart the 'Network Location Awareness' Service: NlaSvc

Get-Service *nlasvc* | Restart-Service -force

get primary DC (PDC)

Netdom Query Fsmo
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster

Logging

Filter log by EventID

Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"


Get reboot source/reason

Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap


get last logon user

RPC-Call:

(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user


get currently logged on user

query user /server:$env:computername

get uptime of system

(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime


timeserver settings

query source servers:

w32tm /query /source


set source servers:

net stop w32time; 
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;
w32tm /config /reliable:yes;
net start w32time;

Without stopping w32time:

w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update

Sync with timeservers:

w32tm /resync /force

Get Service names

Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name


get services and run state:

Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}

or (simulate case insensitive)

Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}


get list of services that start with watch* (case sensitive)

Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service


Bitlocker

get-tpm
Initialize-Tpm
Get-BitLockerVolume
Enable-BitLocker -TpmProtector C:
Enable-BitLocker -RecoveryPasswordProtector C:


Software

get software installed

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize

or

Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"


remove/uninstall software

$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"
$b.Uninstall()

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0        <-- Check ReturnValue is equal 0
PSComputerName   :

get-pendingreboot

Source: [https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]

Function Get-PendingReboot
{
<#
.SYNOPSIS
    Gets the pending reboot status on a local or remote computer.

.DESCRIPTION
    This function will query the registry on a local or remote computer and determine if the
    system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer 
    Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the 
    CBS registry key as another factor in determining pending reboot state.  "PendingFileRenameOperations" 
    and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.

    CBServicing = Component Based Servicing (Windows 2008+)
    WindowsUpdate = Windows Update / Auto Update (Windows 2003+)
    CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value
    PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)
    PendFileRename = PendingFileRenameOperations (Windows 2003+)
    PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-
                     Virus leverage this key for def/dat removal, giving a false positive PendingReboot

.PARAMETER ComputerName
    A single Computer or an array of computer names.  The default is localhost ($env:COMPUTERNAME).

.PARAMETER ErrorLog
    A single path to send error data to a log file.

.EXAMPLE
    PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize

    Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending
    -------- ----------- ------------- ------------ -------------- -------------- -------------
    DC01           False         False                       False                        False
    DC02           False         False                       False                        False
    FS01           False         False                       False                        False

    This example will capture the contents of C:\ServerList.txt and query the pending reboot
    information from the systems contained in the file and display the output in a table. The
    null values are by design, since these systems do not have the SCCM 2012 client installed,
    nor was the PendingFileRenameOperations value populated.

.EXAMPLE
    PS C:\> Get-PendingReboot

    Computer           : WKS01
    CBServicing        : False
    WindowsUpdate      : True
    CCMClient          : False
    PendComputerRename : False
    PendFileRename     : False
    PendFileRenVal     : 
    RebootPending      : True

    This example will query the local machine for pending reboot information.

.EXAMPLE
    PS C:\> $Servers = Get-Content C:\Servers.txt
    PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation

    This example will create a report that contains pending reboot information.

.LINK
    Component-Based Servicing:
    http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx

    PendingFileRename/Auto Update:
    http://support.microsoft.com/kb/2723674
    http://technet.microsoft.com/en-us/library/cc960241.aspx
    http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx

    SCCM 2012/CCM_ClientSDK:
    http://msdn.microsoft.com/en-us/library/jj902723.aspx

.NOTES
    Author:  Brian Wilhite
    Email:   bcwilhite (at) live.com
    Date:    29AUG2012
    PSVer:   2.0/3.0/4.0/5.0
    Updated: 27JUL2015
    UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change
             Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.
             Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)
             Added CCMClient property - Used with SCCM 2012 Clients only
             Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter
             Removed $Data variable from the PSObject - it is not needed
             Bug with the way CCMClientSDK returned null value if it was false
             Removed unneeded variables
             Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry
             Removed .Net Registry connection, replaced with WMI StdRegProv
             Added ComputerPendingRename
#>

[CmdletBinding()]
param(
        [Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [Alias("CN","Computer")]
        [String[]]$ComputerName="$env:COMPUTERNAME",
        [String]$ErrorLog
        )

Begin {  }## End Begin Script Block
Process {
  Foreach ($Computer in $ComputerName) {
        Try {
            ## Setting pending values to false to cut down on the number of else statements
            $CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false
                        
            ## Setting CBSRebootPend to null since not all versions of Windows has this value
            $CBSRebootPend = $null

            ## Querying WMI for build version
            $WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop

            ## Making registry connection to the local/remote computer
            $HKLM = [UInt32] "0x80000002"
            $WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"

            ## If Vista/2008 & Above query the CBS Reg Key
            If ([Int32]$WMI_OS.BuildNumber -ge 6001) {
                    $RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")
                    $CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"
            }

            ## Query WUAU from the registry
            $RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")
            $WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"

            ## Query PendingFileRenameOperations from the registry
            $RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")
            $RegValuePFRO = $RegSubKeySM.sValue

            ## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation
            $Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames
            $PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')

            ## Query ComputerName and ActiveComputerName from the registry
            $ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName")            
            $CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")

            If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {
                $CompPendRen = $true
            }

            ## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true
            If ($RegValuePFRO) {
                    $PendFileRename = $true
            }

            ## Determine SCCM 2012 Client Reboot Pending Status
            ## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0
            $CCMClientSDK = $null
            $CCMSplat = @{
                NameSpace='ROOT\ccm\ClientSDK'
                Class='CCM_ClientUtilities'
                Name='DetermineIfRebootPending'
                ComputerName=$Computer
                ErrorAction='Stop'
            }
            ## Try CCMClientSDK
            Try {
                $CCMClientSDK = Invoke-WmiMethod @CCMSplat
            } Catch [System.UnauthorizedAccessException] {
                $CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue
                If ($CcmStatus.Status -ne 'Running') {
                    Write-Warning "$Computer`: Error - CcmExec service is not running."
                    $CCMClientSDK = $null
                }
            } Catch {
                $CCMClientSDK = $null
            }

            If ($CCMClientSDK) {
                If ($CCMClientSDK.ReturnValue -ne 0) {
                        Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)"          
                    }
                    If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {
                        $SCCM = $true
                    }
            }
            
            Else {
                $SCCM = $null
            }

            ## Creating Custom PSObject and Select-Object Splat
            $SelectSplat = @{
                Property=(
                    'Computer',
                    'CBServicing',
                    'WindowsUpdate',
                    'CCMClientSDK',
                    'PendComputerRename',
                    'PendFileRename',
                    'PendFileRenVal',
                    'RebootPending'
                )}
            New-Object -TypeName PSObject -Property @{
                Computer=$WMI_OS.CSName
                CBServicing=$CBSRebootPend
                WindowsUpdate=$WUAURebootReq
                CCMClientSDK=$SCCM
                PendComputerRename=$CompPendRen
                PendFileRename=$PendFileRename
                PendFileRenVal=$RegValuePFRO
                RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)
            } | Select-Object @SelectSplat

        } Catch {
            Write-Warning "$Computer`: $_"
            ## If $ErrorLog, log the file to a user specified location/path
            If ($ErrorLog) {
                Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append
            }
        }
  }## End Foreach ($Computer in $ComputerName)
}## End Process

End {  }## End End

}## End Function Get-PendingReboot


Get Group Memberships of AD-Object

Get-ADPrincipalGroupMembership -identity <USER>


Search/Filter Users

Get-ADUser reference: @M$

Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \
-Server 'Fleetservices.intra'

or export result to CSV-File

Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv

get logon scripts of ad-users:

Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \
-properties name,scriptpath | select name,scriptpath


get 'password never expires' flag:

get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch


Bulk-Replace UPN domain of users

Import-Module ActiveDirectory
$oldSuffix = "olddomain.tld"
$newSuffix = "newdomain.tld"
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"
$server = "localhost"

Get-ADUser -SearchBase $ou -filter * | ForEach-Object {
   $newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)
   $_ | Set-ADUser -server $server -UserPrincipalName $newUpn
}

Bulk-Clear Manager from AD Users

$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager

# list managers
$users.manager

$users | Set-ADUser -Manager $null

Search/Filter Computers

Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'


Bulk change Group Scope

$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"

$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"

# Print list
$MyGroupList.name

# Set scope
$MyGroupList | Set-ADGroup -GroupScope Universal

# Now we can change to DomainLocal
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"

$MyGroupList.name

$MyGroupList | Set-ADGroup -GroupScope DomainLocal


DNS

set secure zone transfer servers

For all Zones:

Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers  -SecondaryServers <IP-1>,<IP-2>,<IP-n>


File operations

create shortcut

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"
$Shortcut.Save()


robocopy

robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log
  1. /MIR specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.
  2. /FFT uses fat file timing instead of NTFS. This means the granularity is a bit less precise.
  3. /W:5 reduces the wait time between failures to 5 seconds instead of the 30 second default.
  4. /R:2 reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.
  5. /Z ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.
  6. /B copy files in Backup mode.
  7. /ZB use restartable mode; if access denied use Backup mode.
  8. /MT[:n] Do multi-threaded copies with n threads (default 8).
  9. /CREATE creates directories and zero-length files only.
  10. /XF file [file]... eXclude Files matching given names/paths/wildcards.
  11. /XD dirs [dirs]... eXclude Directories matching given names/paths.
  12. /XA:H makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.
  13. /log:RobocopySync.log write output into logfile instead stdout. Use in combination with /tee to get output to stdout AND logfile
  14. /COPY:copyflag[s] what to COPY for files (default is /COPY:DAT). (copyflags : D=Data, A=Attributes, T=Timestamps). (S=Security=NTFS ACLs, O=Owner info, U=aUditing info).
  15. /COPYALL Same as /COPY:DATSOU)


set thumbnail-image

from an exchange server

Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg"  -Encoding Byte -ReadCount 0))


from an AD

$photo = [byte[]](Get-Content path of pic -Encoding byte)
Set-ADUser username -Replace @{thumbnailPhoto=$photo}

get .Net Version installed

wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version


List files/folderstructure recursively

List files including their relative path and output full UNC Path:

foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {
   $out = "\\SERVER\Share$\folder\foo\" + $myfile
   echo $out >> ./fileList.txt
}


List shared folders

get-WmiObject -class Win32_Share 


get ACL folder permissions

get-acl C:\folder | Format-List
$children = get-childitem e:\

foreach($child in $children) {
   echo $child.name
   (get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags
   echo ""
   echo ""
}


set/remove ACL folder permissions

Traverse through whole tree:

foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {
   $AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
   $acl = Get-Acl $folder.fullname
   $acl.SetAccessRuleProtection($false, $true)  # Inheritance on
   $acl.SetAccessRule($AccessRule)
   Set-Acl -Path $folder.FullName -AclObject $acl
}

This folder only:

foreach ($folder in get-item \\<server>\e$\Folder) {
   $AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")
   $acl = Get-Acl $folder.fullname
   $acl.SetAccessRuleProtection($true, $false)  # Inheritance off
   $acl.SetAccessRule($AccessRule)
   Set-Acl -Path $folder.FullName -AclObject $acl
}


Remove permissions by DOMAIN:

$acl = Get-Acl D:\path\to\folder
$rules = $acl.access | Where-Object {
   (-not $_.IsInherited) -and
   $_.IdentityReference -like "DOMAIN\*"
}

foreach($rule in $rules) {
   $acl.RemoveAccessRule($rule)
}

Remove a User/Group completely from ACLs:
(This includes all Allow AND Deny rules)

$acl = Get-Acl D:\path
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")
$acl.PurgeAccessRules($usersid)
$acl | Set-Acl D:\path

get/set/copy NTFS permissions

Copy some folder eg. E:\Data to F:\DataNew

Since the old and new foldernames differ, we'll have to get the permissions of the root folder:

cd E:\data
icacls . /save ..\DATA-root_perms.txt /c

now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:

icacls .\ /save ..\DATA_perms.txt /c /t

now we have 2 permission files which we can restore on the new folder:

cd F:\DataNew
icacls . /restore E:\DATA-root_perms.txt /c
icacls .\ /restore E:\DATA_perms.txt /c

If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:

cd e:
icacls .\Data /save .\DATA_perms.txt /c /t
icacls F: /restore E:\DATA_perms.txt /c

where:

/t     Traverse through folders
/c     Continue on errors


setspn

List SPN:

setspn -L <accountname>
setspn -L <hostname>

Register new SPN:

setspn -R <server>

It will register SPN "HOST/server" and "HOST/{DNS of server}"

Register additional SPN (alias) for <server>:

setspn -S host/<serveralias> <server>


winMTR.ps1

<#
.SYNOPSIS
An MTR clone for PowerShell.
Written by Tyler Applebaum.
Version 2.0

.LINK
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2
http://www.team-cymru.org/IP-ASN-mapping.html#dns

.DESCRIPTION
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.
Big shout out to Team Cymru for the ASN resolution.
Thanks to DrDrrae for a bugfix on PowerShell v5

.PARAMETER Target
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.

.PARAMETER PingCycles
Specifies the number of ICMP packets to send per hop. Default is 10.

.PARAMETER DNSServer
An optional parameter to specify a different DNS server than configured on your network adapter.

.INPUTS
System.String, System.Int32

.OUTPUTS
PSObject containing the traceroute results. Also saves a file to the desktop.

.EXAMPLE
PS C:\> Get-Traceroute 8.8.4.4 -b 512
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.

.EXAMPLE
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.
#>

#Requires -version 4
[CmdletBinding()]
  param(
    [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
    [String]$Target,

    [Parameter(ValueFromPipeline)]
    [Alias("c")]
    [ValidateRange(5,100)]
    [int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100

    [Parameter(ValueFromPipeline)]
    [Alias("b")]
    [ValidateRange(32,1000)]
    [int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes

    [Parameter(ValueFromPipeline)]
    [Alias("s")]
    [IPAddress]$DNSServer = $Null,
	
    [Parameter(ValueFromPipeline)]
    [Alias("f")]
    [String]$Filename = "Traceroute_$Target"

    )
Function script:Set-Variables {
$PerTraceArr = @()
$script:ASNOwnerArr = @()
$ASNOwnerObj = New-Object PSObject
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.
$script:i = 0
$script:x = 0
$script:z = 0
$script:WHOIS = ".origin.asn.cymru.com"
$script:ASNWHOIS = ".asn.cymru.com"
} #End Set-Variables

Function script:Set-WindowSize {
$Window = $Host.UI.RawUI
  If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {
    $NewSize = $Window.BufferSize
    $NewSize.Height = 3000
    $NewSize.Width = 175
    $Window.BufferSize = $NewSize

    $NewSize = $Window.WindowSize
    $NewSize.Height = 50
    $NewSize.Width = 175
    $Window.WindowSize = $NewSize
  }
} #End Set-WindowSize

Function script:Get-Traceroute {
  $script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute
} #End Get-Traceroute

Function script:Resolve-ASN {
  $HopASN = $null #Reset to null each time
  $HopASNRecord = $null #Reset to null each time
  If ($Hop -notlike "TimedOut" -AND $Hop -notmatch "^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*") { #Don't waste a lookup on RFC1918 IPs
    $HopSplit = $Hop.Split('.')
    $HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]
    $HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings
  }
  Else {
    $HopASNRecord = $null
  }

  If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;
    $HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]
    Write-Verbose "Object found $HopASN"
  }

  ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.
    $HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]
    Write-Verbose "String found $HopASN"
  }

  Else {
    $HopASN = "-"
  }
} #End Resolve-ASN

Function script:Resolve-ASNOwner {
  If ($HopASN -notlike "-") {  
  $IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)
  Write-Verbose "Current object: $ASNOwnerObj"
  
    If (!($ASNOwnerArr.ASN.Contains($HopASN)) -OR ($ASNOwnerArr."ASN Owner"[$IndexNo].Contains('-'))){ #Keep "ASNOwnerArr.ASN" in double quotes so it will be treated as a string and not an object
      Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily
      $HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings

	  If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;
        $HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]
        Write-Verbose "Object found $HopASNOwner"
      }
	  ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.
        $HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]
        Write-Verbose "String found $HopASNOwner"
	  }
	  Else {
        $HopASNOwner = "-"
	  }
	  $ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force
	  $ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force
	  $ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache
    }
    Else { #We get to use a cached entry and save Team Cymru some lookups
      Write-Verbose "ASN Owner found in cache"
	  $HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"
    }
  }
  Else {
    $HopASNOwner = "-"
    Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"
  }
} #End Resolve-ASNOwner

Function script:Resolve-DNS {
$HopNameArr = $null
$script:HopName = New-Object psobject
  If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {
    $z++ #Increment the count for the progress bar
    $script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost
    Write-Verbose "Hop = $Hop"

    If ($HopNameArr.NameHost -AND $HopNameArr.NameHost.GetType().IsArray) { #Check for array first; sometimes resolvers are stupid and return NS records with the PTR in an array.
      $script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost[0] #If Resolve-DNS brings back an array containing NS records, select just the PTR
      Write-Verbose "Object found $HopName"
    }

    ElseIf ($HopNameArr.NameHost -AND $HopNameArr.NameHost.GetType().FullName -like "System.String") { #Normal case. One PTR record. Will break up an array of multiple PTRs separated with a comma.
      $script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one
      Write-Verbose "String found $HopName"
    }

    ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.
      $script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP
      Write-Verbose "HopNameArr apparently empty for $HopName"
    }
    Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)
  }
  Else {
    $z++
    $script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut
    Write-Verbose "Hop = $Hop"
  }
} #End Resolve-DNS

Function script:Get-PerHopRTT {
  $PerHopRTTArr = @() #Store all RTT values per hop
  $SAPSObj = $null #Clear the array each cycle
  $SendICMP = New-Object System.Net.NetworkInformation.Ping
  $i++ #Advance the count
  $x = 0 #Reset x for the next hop count. X tracks packet loss percentage.
  $BufferData = "a" * $BufLen #Send the UTF-8 letter "a"
  $ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)
  If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop
    For ($y = 1; $y -le $PingCycles; $y++){
     $HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout
     $HopRTT = $HopResults.RoundtripTime
     $PerHopRTTArr += $HopRTT #Add RTT to HopRTT array
      If ($HopRTT -eq 0) {
        $x = $x + 1
      }
    Write-Progress -Activity "Testing Packet Loss to Hop #$z of $($TraceResults.length)" -Status "Sending ICMP Packet $y of $PingCycles to $Hop - Result: $HopRTT ms" -PercentComplete ($y / $PingCycles*100)
    } #End for loop
    $PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array
    $HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum
    $HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum
    $HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average
    $HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"
    $HopText = [string]$HopRTT + "ms"
    If ($HopLoss -like "*100*") { #100% loss, but name resolves
      $HopResults = $null
      $HopRTT = $null
      $HopText = $null
      $HopRTTAvg = "-"
      $HopRTTMin = "-"
      $HopRTTMax = "-"
      }
  } #End main ping loop
  Else { #Hop TimedOut - no ping attempted
    $HopResults = $null
    $HopRTT = $null
    $HopText = $null
    $HopLoss = "100.0%"
    $HopRTTAvg = "-"
    $HopRTTMin = "-"
    $HopRTTMax = "-"
    } #End TimedOut condition
  $script:SAPSObj = [PSCustomObject]@{
  "Hop" = $i
  "Hop Name" = $HopName.NameHost
  "ASN" = $HopASN
  "ASN Owner" = $HopASNOwner
  "`% Loss" = $HopLoss
  "Hop IP" = $Hop
  "Avg RTT" = $HopRTTAvg
  "Min RTT" = $HopRTTMin
  "Max RTT" = $HopRTTMax
  }
  $PerTraceArr += $SAPSObj #Add the object to the array
} #End Get-PerHopRTT

. Set-Variables
. Set-WindowSize
. Get-Traceroute
ForEach ($Hop in $TraceResults) {
  . Resolve-ASN
  . Resolve-ASNOwner
  . Resolve-DNS
  . Get-PerHopRTT
}

$PerTraceArr | Format-Table -Autosize
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8

top like output

in processor time

While(1) {  
   $p = get-counter '\Process(*)\% Processor Time'; 
   cls; 
   $p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a
}


in percent

while(1) {
   cls; 
   Get-Counter '\Process(*)\% Processor Time' `
   | Select-Object -ExpandProperty countersamples `
   | Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `
   | Sort-Object -Property cookedvalue -Descending `
   | Select-Object -First 25 `
   | ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; 
   sleep 2
}


Delete SPN from host:

setspn -D host/<serveralias> <server>

SCCM Related

Pull pending updates and install

function Get-CMMissingUpdate {

param (
$computer = $env:computername
)

    Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer

}


function Install-CMMissingUpdate {

param (
$computer = $env:computername
)

    ([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (
     Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))

}

SSL/TLS

yadda


Disable SSL 2.0

New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD


Disable SSL 3.0

New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD


Enable TLS 1.1 & TLS 1.2

New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD

New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD