Aus SchnallIchNet
Wechseln zu: Navigation, Suche

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

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


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:


Get-ChildItem env:CHRIS


Get-ChildItem env:CHR*

get/set netconnectionprofile

PS C:\> Get-NetConnectionProfile

Name :
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

get primary DC (PDC)

Netdom Query Fsmo

get last logon user


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

timeserver settings

query source servers:

w32tm /query /source

set source servers:

net stop w32time; 
w32tm /config /syncfromflags:manual /manualpeerlist:;
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

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 '' | 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

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 | 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

# 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 | Set-ADGroup -GroupScope DomainLocal


set secure zone transfer servers

For all Zones:

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


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 $
   (get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags
   echo ""
   echo ""

set 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
   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
   Set-Acl -Path $folder.FullName -AclObject $acl

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


/t     Traverse through folders
/c     Continue on errors


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>

Delete SPN from host:

setspn -D host/<serveralias> <server>

SCCM Related

Pull pending updates and install

function Get-CMMissingUpdate {

param (
$computer = "localhost"

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


function Install-CMMissingUpdate {

param (
$computer = "localhost"

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




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