https://schnallich.net/api.php?action=feedcontributions&user=Cbs&feedformat=atom
SchnallIchNet - Benutzerbeiträge [de]
2024-03-29T04:42:32Z
Benutzerbeiträge
MediaWiki 1.25.3
https://schnallich.net/index.php?title=OpenSSL&diff=1765
OpenSSL
2024-03-05T12:58:22Z
<p>Cbs: /* PEM to DER and DER 2 PEM */</p>
<hr />
<div>==Optionale Parameter fuer die folgenden commandos==<br />
<br />
-config /path/to/own/my_openssl.cnf<br />
separate config-datei verwenden.<br />
<br />
-nodes<br />
verhindert das verschluesseln des key mit einem Passwort.<br/><br />
Die ist wichtig bei key's fuer serverdienste. oder das passwort<br/><br />
muss beim neustart des dienstes eingegeben werden.<br />
<br />
<br />
==Request (CSR) erstellen==<br />
<br />
openssl req -newkey rsa:2048 -out request.pem -keyout pub-sec-key.pem<br />
Generiert einen neuen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Passend dazu wird ein Request in der Datei request.pem erstellt.<br />
<br />
openssl req -new -out request.pem -key pub-sec-key.pem<br />
Wie zuvor, nur wird der Request zum bereits vorhandenen Schlüssel pub-sec-key.pem generiert.<br />
<br />
openssl req -text -noout -in request.pem<br />
Zeigt den Request request.pem an.<br />
<br />
openssl req -verify -noout -in request.pem<br />
Verifiziert die Selbstsignatur des Requests request.pem.<br />
<br />
openssl req -noout -modulus -in request.pem | openssl sha1 -c<br />
Generiert einen SHA1-Fingerabdruck vom Modulus des Schlüssels aus dem Request request.pem.<br />
<br />
openssl x509 -x509toreq -in self-signed-certificate.pem -signkey pub-sec-key.pem -out request.pem<br />
Erstellt neuen Request aus altem Selbstzertifikat.<br />
<br />
<br />
==Request (CSR) mit CA signieren==<br />
<br />
openssl ca -out certs/openVPN_Vorname.Nachname.crt -in openVPN_Vorname.Nachname.csr<br />
<br />
<br />
==Certificate (CRT) erstellen==<br />
<br />
openssl req -x509 -days 365 -newkey rsa:2048 \<br />
-out self-signed-certificate.pem -keyout pub-sec-key.pem<br />
Generiert einen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Es wird ein selbst signiertes Zertifikat erstellt und in der Datei self-signed-certificate.pem gespeichert. Das Zertifikat ist 365 Tag gültig und für simple Testzwecke gedacht.<br />
<br />
openssl req -x509 -days 365 -new -out self-signed-certificate.pem -key pub-sec-key.pem<br />
Wie zuvor, erstellt jedoch ein selbst signiertes Zertifikat aus einem vorhandenen Schlüssel pub-sec-key.pem.<br />
<br />
<br />
== ECC Key erstellen ==<br />
<br />
openssl ecparam -list_curves<br />
List possible curves<br />
<br />
openssl ecparam -name secp384r1 -genkey -out private.ecc-key.pem<br />
Erstellt einen elliptic curve key, der zur Generierung eines passenden CSR verwendet werden kann.<br />
<br />
== Certifikate konvertieren, ausgeben, pruefen ==<br />
<br />
openssl x509 -text -noout -md5 -in self-signed-certificate.pem<br />
Gibt das Zertifikat self-signed-certificate.pem als Klartext aus.<br />
<br />
openssl x509 -fingerprint -noout -md5 -in self-signed-certificate.pem<br />
Gibt den Fingerabdruck des X.509 Zertifikats self-signed-certificate.pem aus. Der Algorithmus ist hier MD5, SHA1 kann<br />
verwendet werden, wenn -md5 durch -sha1 ersetzt wird.<br />
<br />
openssl verify -issuer_checks -CAfile self-signed-certificate.pem self-signed-certificate.pem<br />
Überprüft ein selbst signiertes Zertifikat.<br />
<br />
openssl s_client -showcerts -CAfile self-signed-certificate.pem -connect www.dfn-pca.de:443<br />
Baut eine OpenSSL-Verbindung unter Verwendung des Zertifikats self-signed-certificate.pem zum angegebenen Server auf. Es wird dabei die gesamte Zertifikatskette angezeigt.<br />
<br />
openssl crl -noout -text -CAfile self-signed-certificate.pem crl.pem<br />
Gibt die Zertifikats-Widerrufsliste crl.pem in Klartext aus.<br />
<br />
<br />
=== PKCS12/PFX conversion ===<br />
<br />
Create PKCS12 from PEM:<br />
<br />
openssl pkcs12 -export -in myCertificate.crt -inkey myCertificate.key -certfile cacert.pem -out myCertificate.pkcs12<br />
<br />
<br />
export pem's from pkcs12-files:<br />
<br />
openssl pkcs12 -in cert.p12 -clcerts -nokeys -nodes -out ./cert.pem<br />
openssl pkcs12 -in cert.p12 -cacerts -nokeys -nodes -out ./root-chain.pem<br />
openssl pkcs12 -in cert.p12 -nocerts -nodes -out ./key.pem<br />
<br />
=== PKCS7 conversion ===<br />
<br />
openssl pkcs7 -in cert.p7b -inform DER -print_certs -out cert.pem<br />
<br />
<br />
=== PEM to DER and DER 2 PEM ===<br />
<br />
Use the OpenSSL commands to convert between formats as follows:<br />
<br />
To convert a certificate from PEM to DER:<br />
openssl x509 -in input.crt -inform PEM -out output.crt -outform DER<br />
<br />
To convert a certificate from DER to PEM:<br />
openssl x509 -in input.crt -inform DER -out output.crt -outform PEM<br />
<br />
To convert a key from PEM to DER:<br />
openssl rsa -in input.key -inform PEM -out output.key -outform DER<br />
<br />
To convert a key from DER to PEM:<br />
openssl rsa -in input.key -inform DER -out output.key -outform PEM<br />
<br />
== Schluessel (KEY) bearbeiten ==<br />
<br />
veraenderungen an vorhandenen schluesseln vornehmen<br />
<br />
<br />
=== Schluessel (KEY) passwort aendern ===<br />
<br />
openssl rsa -in mykey.pem -des3 -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn unter verwendung eines anderen passwortes wieder ab.<br />
<br />
<br />
=== Schluessel (KEY) passwort entfernen ===<br />
<br />
openssl rsa -in mykey.pem -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn OHNE neues passwort wieder ab. (unsicher!!)<br />
<br />
<br />
==CRLs==<br />
<br />
Die CRL ist eine Widerrufliste in der die ungültigen Zertifikate eingetragen<br />
sind und Zugänge aufgehoben werden können (z.B. beim Ausscheiden eines<br />
Mitarbeiters). Dazu wird periodisch eine gültige CRL erstellt. Einzelne<br />
Zertifikate können dann manuell entfernt werden. Die Sperrung erfolgt dann<br />
beim nächsten Anlegen der Liste. Daher sollte die Liste entweder sofort nach<br />
deaktivieren eines Zertifikats oder, je nach Dringlichkeit, täglich oder<br />
wöchentlich per Cronjob erstellt werden.<br />
<br />
<br />
===das Zertifikat von 'meier' entfernen===<br />
<br />
openssl ca -revoke meiercert.pem<br />
<br />
oder <br />
<br />
openssl ca -revoke ./newcerts/03.pem'<br />
<br />
<br />
===Nummern der gesperrten Zertifikate anzeigen===<br />
<br />
openssl crl -in crls/crl.pem -noout -text<br />
<br />
<br />
===gültige CRL erstellen===<br />
<br />
openssl ca -gencrl -out crls/crl.pem<br />
dies muss nach '''JEDEM''' widerruf von certifikaten gemacht werden!!!!<br />
<br />
<br />
===CRL in das binäre DER-Format umwandeln===<br />
<br />
openssl crl -in crls/crl.pem -outform der -out crls/cert.crl<br />
<br />
<br />
== Verifying ==<br />
<br />
=== That a Private Key Matches a Certificate ===<br />
<br />
openssl x509 -noout -text -in server.crt<br />
openssl rsa -noout -text -in server.key<br />
<br />
The `modulus' and the `public exponent' portions in the key and the Certificate must match. But since the public exponent is usually 65537 and it's bothering comparing long modulus you can use the following approach:<br />
<br />
<br />
openssl x509 -noout -modulus -in server.crt | openssl md5<br />
openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And then compare these really shorter numbers. With overwhelming probability they will differ if the keys are different. As a "one-liner":<br />
<br />
openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And with auto-magic comparison (If more than one hash is displayed, they don't match):<br />
<br />
(openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5) | uniq<br />
<br />
BTW, if I want to check to which key or certificate a particular CSR belongs you can compute<br />
<br />
$ openssl req -noout -modulus -in server.csr | openssl md5<br />
<br />
(Shamelessly stolen from [https://kb.wisc.edu/middleware/page.php?id=4064 here])<br />
<br />
<br />
=== That a cacert matches a server cert ===<br />
<br />
openssl verify -verbose -CAfile cacert.pem server.crt<br />
<br />
<br />
== Pinning / TLSA / etc. ==<br />
<br />
=== Get public key PIN ===<br />
<br />
Get PIN from CERT:<br />
<br />
openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from KEY:<br />
<br />
openssl rsa -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from ECC KEY:<br />
<br />
openssl ec -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from CSR:<br />
<br />
openssl req -in signing-request.csr -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
=== TLSA hash ===<br />
<br />
openssl x509 -in cert.pem -noout -fingerprint -sha256 | tr -d ":" | sed 's/SHA256 Fingerprint=//'<br />
<br />
<br />
==S/MIME==<br />
<br />
===Sign Message===<br />
<br />
openssl smime -sign -in in.txt -text -out mail.msg -signer mycert.pem -inkey mykey.pem -certfile mycerts.pem</div>
Cbs
https://schnallich.net/index.php?title=OpenSSL&diff=1764
OpenSSL
2024-02-01T07:57:04Z
<p>Cbs: </p>
<hr />
<div>==Optionale Parameter fuer die folgenden commandos==<br />
<br />
-config /path/to/own/my_openssl.cnf<br />
separate config-datei verwenden.<br />
<br />
-nodes<br />
verhindert das verschluesseln des key mit einem Passwort.<br/><br />
Die ist wichtig bei key's fuer serverdienste. oder das passwort<br/><br />
muss beim neustart des dienstes eingegeben werden.<br />
<br />
<br />
==Request (CSR) erstellen==<br />
<br />
openssl req -newkey rsa:2048 -out request.pem -keyout pub-sec-key.pem<br />
Generiert einen neuen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Passend dazu wird ein Request in der Datei request.pem erstellt.<br />
<br />
openssl req -new -out request.pem -key pub-sec-key.pem<br />
Wie zuvor, nur wird der Request zum bereits vorhandenen Schlüssel pub-sec-key.pem generiert.<br />
<br />
openssl req -text -noout -in request.pem<br />
Zeigt den Request request.pem an.<br />
<br />
openssl req -verify -noout -in request.pem<br />
Verifiziert die Selbstsignatur des Requests request.pem.<br />
<br />
openssl req -noout -modulus -in request.pem | openssl sha1 -c<br />
Generiert einen SHA1-Fingerabdruck vom Modulus des Schlüssels aus dem Request request.pem.<br />
<br />
openssl x509 -x509toreq -in self-signed-certificate.pem -signkey pub-sec-key.pem -out request.pem<br />
Erstellt neuen Request aus altem Selbstzertifikat.<br />
<br />
<br />
==Request (CSR) mit CA signieren==<br />
<br />
openssl ca -out certs/openVPN_Vorname.Nachname.crt -in openVPN_Vorname.Nachname.csr<br />
<br />
<br />
==Certificate (CRT) erstellen==<br />
<br />
openssl req -x509 -days 365 -newkey rsa:2048 \<br />
-out self-signed-certificate.pem -keyout pub-sec-key.pem<br />
Generiert einen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Es wird ein selbst signiertes Zertifikat erstellt und in der Datei self-signed-certificate.pem gespeichert. Das Zertifikat ist 365 Tag gültig und für simple Testzwecke gedacht.<br />
<br />
openssl req -x509 -days 365 -new -out self-signed-certificate.pem -key pub-sec-key.pem<br />
Wie zuvor, erstellt jedoch ein selbst signiertes Zertifikat aus einem vorhandenen Schlüssel pub-sec-key.pem.<br />
<br />
<br />
== ECC Key erstellen ==<br />
<br />
openssl ecparam -list_curves<br />
List possible curves<br />
<br />
openssl ecparam -name secp384r1 -genkey -out private.ecc-key.pem<br />
Erstellt einen elliptic curve key, der zur Generierung eines passenden CSR verwendet werden kann.<br />
<br />
== Certifikate konvertieren, ausgeben, pruefen ==<br />
<br />
openssl x509 -text -noout -md5 -in self-signed-certificate.pem<br />
Gibt das Zertifikat self-signed-certificate.pem als Klartext aus.<br />
<br />
openssl x509 -fingerprint -noout -md5 -in self-signed-certificate.pem<br />
Gibt den Fingerabdruck des X.509 Zertifikats self-signed-certificate.pem aus. Der Algorithmus ist hier MD5, SHA1 kann<br />
verwendet werden, wenn -md5 durch -sha1 ersetzt wird.<br />
<br />
openssl verify -issuer_checks -CAfile self-signed-certificate.pem self-signed-certificate.pem<br />
Überprüft ein selbst signiertes Zertifikat.<br />
<br />
openssl s_client -showcerts -CAfile self-signed-certificate.pem -connect www.dfn-pca.de:443<br />
Baut eine OpenSSL-Verbindung unter Verwendung des Zertifikats self-signed-certificate.pem zum angegebenen Server auf. Es wird dabei die gesamte Zertifikatskette angezeigt.<br />
<br />
openssl crl -noout -text -CAfile self-signed-certificate.pem crl.pem<br />
Gibt die Zertifikats-Widerrufsliste crl.pem in Klartext aus.<br />
<br />
<br />
=== PKCS12/PFX conversion ===<br />
<br />
Create PKCS12 from PEM:<br />
<br />
openssl pkcs12 -export -in myCertificate.crt -inkey myCertificate.key -certfile cacert.pem -out myCertificate.pkcs12<br />
<br />
<br />
export pem's from pkcs12-files:<br />
<br />
openssl pkcs12 -in cert.p12 -clcerts -nokeys -nodes -out ./cert.pem<br />
openssl pkcs12 -in cert.p12 -cacerts -nokeys -nodes -out ./root-chain.pem<br />
openssl pkcs12 -in cert.p12 -nocerts -nodes -out ./key.pem<br />
<br />
=== PKCS7 conversion ===<br />
<br />
openssl pkcs7 -in cert.p7b -inform DER -print_certs -out cert.pem<br />
<br />
<br />
=== PEM to DER and DER 2 PEM ===<br />
<br />
Use the OpenSSL commands to convert between formats as follows:<br />
<br />
To convert a certificate from PEM to DER:<br />
openssl x509 -in input.crt -inform PEM –out output.crt -outform DER<br />
<br />
To convert a certificate from DER to PEM:<br />
openssl x509 -in input.crt -inform DER -out output.crt -outform PEM<br />
<br />
To convert a key from PEM to DER:<br />
openssl rsa -in input.key -inform PEM -out output.key -outform DER<br />
<br />
To convert a key from DER to PEM:<br />
openssl rsa -in input.key -inform DER -out output.key -outform PEM<br />
<br />
== Schluessel (KEY) bearbeiten ==<br />
<br />
veraenderungen an vorhandenen schluesseln vornehmen<br />
<br />
<br />
=== Schluessel (KEY) passwort aendern ===<br />
<br />
openssl rsa -in mykey.pem -des3 -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn unter verwendung eines anderen passwortes wieder ab.<br />
<br />
<br />
=== Schluessel (KEY) passwort entfernen ===<br />
<br />
openssl rsa -in mykey.pem -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn OHNE neues passwort wieder ab. (unsicher!!)<br />
<br />
<br />
==CRLs==<br />
<br />
Die CRL ist eine Widerrufliste in der die ungültigen Zertifikate eingetragen<br />
sind und Zugänge aufgehoben werden können (z.B. beim Ausscheiden eines<br />
Mitarbeiters). Dazu wird periodisch eine gültige CRL erstellt. Einzelne<br />
Zertifikate können dann manuell entfernt werden. Die Sperrung erfolgt dann<br />
beim nächsten Anlegen der Liste. Daher sollte die Liste entweder sofort nach<br />
deaktivieren eines Zertifikats oder, je nach Dringlichkeit, täglich oder<br />
wöchentlich per Cronjob erstellt werden.<br />
<br />
<br />
===das Zertifikat von 'meier' entfernen===<br />
<br />
openssl ca -revoke meiercert.pem<br />
<br />
oder <br />
<br />
openssl ca -revoke ./newcerts/03.pem'<br />
<br />
<br />
===Nummern der gesperrten Zertifikate anzeigen===<br />
<br />
openssl crl -in crls/crl.pem -noout -text<br />
<br />
<br />
===gültige CRL erstellen===<br />
<br />
openssl ca -gencrl -out crls/crl.pem<br />
dies muss nach '''JEDEM''' widerruf von certifikaten gemacht werden!!!!<br />
<br />
<br />
===CRL in das binäre DER-Format umwandeln===<br />
<br />
openssl crl -in crls/crl.pem -outform der -out crls/cert.crl<br />
<br />
<br />
== Verifying ==<br />
<br />
=== That a Private Key Matches a Certificate ===<br />
<br />
openssl x509 -noout -text -in server.crt<br />
openssl rsa -noout -text -in server.key<br />
<br />
The `modulus' and the `public exponent' portions in the key and the Certificate must match. But since the public exponent is usually 65537 and it's bothering comparing long modulus you can use the following approach:<br />
<br />
<br />
openssl x509 -noout -modulus -in server.crt | openssl md5<br />
openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And then compare these really shorter numbers. With overwhelming probability they will differ if the keys are different. As a "one-liner":<br />
<br />
openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And with auto-magic comparison (If more than one hash is displayed, they don't match):<br />
<br />
(openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5) | uniq<br />
<br />
BTW, if I want to check to which key or certificate a particular CSR belongs you can compute<br />
<br />
$ openssl req -noout -modulus -in server.csr | openssl md5<br />
<br />
(Shamelessly stolen from [https://kb.wisc.edu/middleware/page.php?id=4064 here])<br />
<br />
<br />
=== That a cacert matches a server cert ===<br />
<br />
openssl verify -verbose -CAfile cacert.pem server.crt<br />
<br />
<br />
== Pinning / TLSA / etc. ==<br />
<br />
=== Get public key PIN ===<br />
<br />
Get PIN from CERT:<br />
<br />
openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from KEY:<br />
<br />
openssl rsa -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from ECC KEY:<br />
<br />
openssl ec -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from CSR:<br />
<br />
openssl req -in signing-request.csr -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
=== TLSA hash ===<br />
<br />
openssl x509 -in cert.pem -noout -fingerprint -sha256 | tr -d ":" | sed 's/SHA256 Fingerprint=//'<br />
<br />
<br />
==S/MIME==<br />
<br />
===Sign Message===<br />
<br />
openssl smime -sign -in in.txt -text -out mail.msg -signer mycert.pem -inkey mykey.pem -certfile mycerts.pem</div>
Cbs
https://schnallich.net/index.php?title=Windows/exchange&diff=1763
Windows/exchange
2024-01-16T08:51:28Z
<p>Cbs: /* Search Mailbox content */</p>
<hr />
<div><br />
== PowerShell ==<br />
<br />
powershell commands<br />
<br />
<br />
=== possible access rights ===<br />
<br />
<pre><br />
The Access Rights parameters are as below:<br />
<br />
ReadItems: The user has the right to read items within the specified folder.<br />
CreateItems The user has the right to create items within the specified folder.<br />
EditOwnedItems The user has the right to edit the items that the user owns in the specified folder.<br />
DeleteOwnedItems The user has the right to delete items that the user owns in the specified folder.<br />
EditAllItems The user has the right to edit all items in the specified folder.<br />
DeleteAllItems The user has the right to delete all items in the specified folder.<br />
CreateSubfolders The user has the right to create subfolders in the specified folder.<br />
FolderOwner The user is the owner of the specified folder. The user has the right to view and move the folder and create subfolders. The user can’t read items, edit items, delete items, or create items.<br />
FolderContact The user is the contact for the specified public folder.<br />
FolderVisible The user can view the specified folder, but can’t read or edit items within the specified public folder.<br />
<br />
The Roles with which we can provide the access rights are as below:<br />
<br />
None FolderVisible<br />
Owner CreateItems, ReadItems, CreateSubfolders, FolderOwner, FolderContact, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingEditor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
Editor CreateItems, ReadItems, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingAuthor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
Author CreateItems, ReadItems, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
NonEditingAuthor CreateItems, ReadItems, FolderVisible<br />
Reviewer ReadItems, FolderVisible<br />
Contributor CreateItems, FolderVisible<br />
<br />
Ref: http://technet.microsoft.com/en-us/library/dd298062(v=exchg.150).aspx<br />
<br />
The following roles apply specifically to calendar folders:<br />
<br />
AvailabilityOnly View only availability data<br />
LimitedDetails View availability data with subject and location<br />
</pre><br />
<br />
<br />
=== create mailbox ===<br />
<br />
Create a new mailbox<br />
<br />
New-Mailbox -Name 'prospect NL' -Alias 'prospect.nl' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Rooms and Equipment' \<br />
-UserPrincipalName 'prospect.nl@arifleet.com' -SamAccountName 'prospect.nl' -FirstName 'prospect' -Initials '' -LastName 'NL' \<br />
-Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Stuttgart Mailbox DB One'<br />
<br />
<br />
=== create linked mailbox ===<br />
<br />
New-Mailbox -Name 'Koroch, Ernst' -Alias 'ekoroch' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Users' -UserPrincipalName \<br />
'ekoroch@arifleet.com' -SamAccountName 'ekoroch' -FirstName 'Ernst' -Initials '' -LastName 'Koroch' -Database 'Stuttgart Mailbox DB One' \<br />
-LinkedMasterAccount 'fleetservices\ekoroch' -LinkedDomainController 'dc03.fleetservices.intra' -LinkedCredential \<br />
'System.Management.Automation.PSCredential'<br />
<br />
<br />
=== Repair Mailbox ===<br />
<br />
see: [https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx]<br />
<br />
New-MailboxRepairRequest -Mailbox <Emailaddress> -CorruptionType SearchFolder,AggregateCounts,ProvisionedFolder,FolderView [-DetectOnly]<br />
<br />
<br />
=== Email-Enable AD Group ===<br />
<br />
Enable-DistributionGroup <ADGroupID> -PrimarySmtpAddress yadda@domain.tld<br />
<br />
<br />
=== Email-Enable AD User ===<br />
<br />
Enable-Mailbox <UserID> -PrimarySmtpAddress yadda@domain.tld -displayname "Yadda, Yadda"<br />
<br />
<br />
=== add mailbox permissions ===<br />
<br />
Add full access to mailbox 'mailbox@arifleet.de' for user 'DOMAIN\user': <br />
<br />
Add-MailboxPermission -Identity mailbox@arifleet.de -User DOMAIN\user -AccessRights Fullaccess -InheritanceType All<br />
<br />
-AccessRights <right> <br/><br />
where <right> may be<br />
<br />
FullAccess<br />
ExternalAccount<br />
DeleteItem<br />
ReadPermission<br />
ChangePermission<br />
ChangeOwner<br />
<br />
disable auto-mapping of <br />
<br />
-Automapping $false<br />
<br />
<br />
=== remove mailbox permissions ===<br />
<br />
remove-MailboxPermission -Identity mailbox@arifleet.de -user domari\user -AccessRights Fullaccess -inheritance all<br />
<br />
<br />
=== add/remove 'Send as' permissions ===<br />
<br />
Add-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
You can grant the permissions by using Active Directory Users & Computers. Simply open the properties of the group, switch to the Security tab, add the mailbox user or group, and then tick the Send As box and apply the change. After making this change you may notice that it does not take effect for up to 2 hours. This is due to caching on the Exchange servers. Though you can speed up the change by restarting the Information Store that is obviously not going to be practical in most production environments, so you’ll often find that you just need to wait.<br />
<br />
Remove-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
<br />
==== 'Send as'/'SendOnBehalf' Distributiongroups ====<br />
<br />
Set-DistributionGroup <DistributionGroupName> -GrantSendOnBehalfTo USER@arifleet.com<br />
<br />
and sendOnBehalf for Distributiongroups<br />
<br />
<br />
<br />
==== SentItem Configuration ====<br />
<br />
Until Exchange 2010:<br />
<br />
Set-MailboxSentItemsConfiguration <ALIAS> -SendAsItemsCopiedTo SenderAndFrom<br />
<br />
Exchange 2016:<br />
<br />
Set-Mailbox -identity <UPN> [-DomainController <HOSTNAME>] -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true<br />
<br />
<br />
=== add mailbox folder permissions ===<br />
<br />
Add-MailboxFolderPermission -Identity poolcar@netcar24.com:\Calendar -user csteidl@arifleet.com -AccessRights [[Windows/exchange#possible_access_rights|<see RIGHTS>]]<br />
<br />
Set default-rights for ressource mailboxes (to show up subjects a.s.o.):<br />
<br />
Set-MailboxFolderPermission meetingroom:\Calendar -User Default -AccessRights Reviewer<br />
<br />
=== get mailbox permissions ===<br />
<br />
get permissions of fhess on mailbox prospect.be<br />
<br />
Get-MailboxPermission -Identity prospect.be@arifleet.com -User "fhess"<br />
<br />
<br />
get folder permissions<br />
<br />
get-mailboxfolderpermission -identity fhess<br />
<br />
<br />
get UPN of users<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.User.ADRecipient.UserPrincipalName }<br />
<br />
<br />
get full user details<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.identity.adrecipient.identity }<br />
<br />
<br />
<br />
=== Find permissions granted to spec. users ===<br />
<br />
Get-Mailbox -RecipientType 'UserMailbox' -ResultSize Unlimited | Get-MailboxPermission | where { $_.user.tostring() -eq "DOMAIN\username" -and $_.IsInherited -eq $false }<br />
<br />
<br />
<br />
=== enable autoreply / vacation message ===<br />
<br />
set the message (optionally) and enable auto reply<br />
<br />
$message = get-content message.txt<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState enabled \<br />
-ExternalAudience <none/all/known> \<br />
-InternalMessage "$message" \<br />
-ExternalMessage "$message"<br />
<br />
<br />
=== disable auto-reply / vacation message ===<br />
<br />
disable auto reply<br />
<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState disabled<br />
<br />
<br />
=== Retention policies ===<br />
<br />
create server side retention policies<br />
<br />
<br />
==== Create Retention Policy Tag ====<br />
<br />
New-RetentionPolicyTag "ARI STG - Delete all 180 days" -Type All -Comment "Deletes all items older 180 days" -RetentionEnabled $true \<br />
-AgeLimitForRetention 180 -RetentionAction DeleteAndAllowRecovery<br />
<br />
RetentionAction: MoveToFolder, MoveToDeletedItems, DeleteAndAllowRecovery, PermanentlyDelete, MoveToArchive<br />
<br />
<br />
==== Create Retention Policy ====<br />
<br />
New-RetentionPolicy "ARI STG - Delete ALL items older 180 days" -RetentionPolicyTagLinks "ARI STG - Delete all 180 days"<br />
<br />
Activate policy by: Open Mailbox Properties --> Mailbox Settings --> Messaging Records Mgmt --> Apply Retention policy<br />
<br />
<br />
=== get distribution group members ===<br />
<br />
get-distributiongroupmember <group><br />
<br />
get-distributiongroupmember mailaddress@arifleet.de<br />
<br />
<br />
=== get users by filter and add to distributiongroup ===<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -ne 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -eq 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
<br />
<br />
=== Get Mailbox by ExchangeGuid/Mapi-session ===<br />
<br />
get-mailbox -ResultSize unlimited | where {$_.ExchangeGuid -eq "265182e3-a31c-4a9f-e38e-687f5a7c2d6b"}<br />
<br />
<br />
=== Get Mailbox by Ressource type ===<br />
<br />
<br />
Get-Mailbox -RecipientTypeDetails RoomMailbox<br />
<br />
Get-Mailbox -RecipientTypeDetails EquipmentMailbox<br />
<br />
<br />
=== Get Mail Public folder ===<br />
<br />
Get-MailPublicFolder helpdesk@sub.domain.com | Get-PublicFolder [| Select *]<br />
<br />
<br />
=== Logging ===<br />
<br />
further logfiles can be found here:<br />
<br />
C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\ProtocolLog<br />
<br />
<br />
==== Track accross multiple servers ====<br />
<br />
get-transportserver<br />
<br />
<br />
e.g. that to "get-messagetrackinglog":<br />
<br />
get-transportserver | get-messagetrackinglog<br />
<br />
<br />
==== message tracking ====<br />
<br />
get-messagetrackinglog -Sender 'user@arifleet.de' -Start "5/04/2015 5:00:00 AM" -End "5/15/2015 8:30:00 AM"<br />
<br />
get-transportserver | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
get-transportservice | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
-Start "6/01/2015 5:00:00 AM" \<br />
-End "6/01/2015 10:30:00 AM" \<br />
-resultsize unlimited | ft -Wrap<br />
<br />
<pre><br />
-MessageSubject <String><br />
-Recipients <String[]><br />
-Start/-End (get-date).AddHours(-1).toString()<br />
-ResultSize Unlimited<br />
</pre><br />
<br />
some more examples:<br />
<br />
get-messagetrackinglog -Recipients:recipient@email.be -Start "6/8/2015 4:42:00 AM" -End "6/9/2015 9:52:00 PM" | Select *,{$_.Recipients} | export-csv .\maillog.csv<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | \<br />
where-object {$_.Recipients -like “*@gmail.com, *@yahoo.com” -AND $_.EventId -eq “Send”} |ft -auto >>C:\External mails.txt<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | sort -property Timestamp<br />
<br />
=== repair mailbox ===<br />
<br />
New-MailboxRepairRequest -Mailbox schaden@arifleet.de -CorruptionType SearchFolder<br />
<br />
<br />
-CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview<br />
-Archive Prueft Mailbox _und_ Archive<br />
-DetectOnly Prueft nur, keine Reparatur!<br />
<br />
Ergebnisse der Prüfung werden im Anwendungs Event-Log des Servers protokolliert. Die Events tragen die folgenden Ereignis-IDs:<br />
<br />
10044,10045,10046,10047,10048,10049,10050,10051,10059,10062<br />
<br />
mit einem rechtsklick auf 'Application' laesst dich das eventlog nach diesen ID's filtern.<br />
<br />
<br />
=== move mailbox between exchange-databases ===<br />
<br />
Move Mailboxes between exchange >= 2010 servers <br/><br />
the output is piped into 'ft' (format table) to get complete output and not stripped it...<br />
<br />
New-MoveRequest -Identity mailbox@arifleet.de -TargetDatabase ‘Whatever Database-Name 001’ | ft -AutoSize -Wrap<br />
<br />
create a batch<br />
<br />
Get-Mailbox -Database "Stuttgart Mailbox DB One" | Where-Object { $_.alias -like "jira*" } | New-MoveRequest -TargetDatabase [...]<br />
<br />
Options:<br />
<br />
-BadItemLimit 0<br />
-Suspend <br />
-SuspendComment "Resume after 11:00 p.m. PST"<br />
-SuspendWhenReadyToComplete<br />
-BatchName "Some Name to identify the Batch-Moves"<br />
<br />
get moverequest status:<br />
<br />
Get-MoveRequestStatistics "sadg"<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics | select DisplayName,alias,Status,TotalMailboxSize,PercentComplete| ft<br />
<br />
<br />
=== get Mailbox sizes ===<br />
<br />
Get-MailboxDatabase | Where-Object { $_.Name -like "STG*" } | Get-MailboxStatistics | sort -property TotalItemSize -desc \<br />
| select DisplayName,ItemCount,TotalItemSize,TotalDeletedItemSize |ft<br />
<br />
<br />
=== get database size ===<br />
<br />
Get-MailboxDatabase -status | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Sort-Object DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Where-Object { $_.name -like "STG*" } | Sort -property DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
=== Export Mailbox (Folder) ===<br />
<br />
New-MailboxExportRequest -mailbox schaden \<br />
-includefolders "******@arifleet.de/00 UNFALLORDNER ab 1.3.2011/Storopack R+V (*.***@*******.com) TK 150 \/ keine VK RA Schmid" \<br />
-filepath "\\stgwpvinfEXC01\g$\Storopack R+V (*.***@*******.com) TK 150_keine VK RA Schmid.pst"<br />
<br />
# be sure to mask e.g. '/' characters in foldernames with '\'<br />
# leave out '''-includefolders''' to export the entire mailbox<br/><br />
## add a '.../*' to -includefolders to include subfolders<br />
<br />
=== Search Mailbox content ===<br />
<br />
This one searches for all messages between 1/1/2017 and 12/31/2018 and creates copies of it within the Mailbox of targetmailbox into targetfolder:<br />
<br />
Search-Mailbox -Identity <USER-ID> -SearchQuery "received>=01/01/2017 AND received<=12/31/2018" -targetmailbox "<TARGET-USER-ID>" -targetfolder "SearchResults"<br />
<br />
SearchQuery examples: <br/><br />
<br />
"Subject:Project Hamilton"<br/><br />
"election OR candidate OR vote" - all messages that contain one of the words in whole message<br />
<br />
<b>If the Subject you are searching for contains COLONS, they need to be masked using back tick "Subject:AW`: yadda yadda"</b><br />
<br />
Delete resulting emails:<br />
<br />
-deletecontent<br />
<br />
=== set thumbnail-image ===<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
<br />
=== Import/Acivate new Certificate ===<br />
<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path c:\certificates\YOUR_CERTIFICATE.cer -Encoding byte -ReadCount 0))<br />
<br />
In case of encrypted .pfx or something like that:<br />
<br />
$pass = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -Password $pass -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path Webmail.pfx -Encoding byte -ReadCount 0))<br />
<br />
activate:<br />
<br />
Enable-ExchangeCertificate -Thumbprint 1234ae0567a72fccb75b1d0198628675333d010e -Services POP,IMAP,SMTP,IIS<br />
<br />
=== DAG/Cluster stuff ===<br />
<br />
Check who's master:<br />
<br />
Get-ClusterGroup EU-DAG<br />
<br />
<br />
Get detailed DAG info:<br />
<br />
Get-DatabaseAvailabilityGroup STG-DAG -status | fl<br />
<br />
<br />
Test replication health (do so on all cluster members):<br />
<br />
Test-ReplicationHealth -server EXC02<br />
<br />
<br />
Get mount status, copy/reply queue, Index state<br />
<br />
Get-MailboxDatabaseCopyStatus -server exc01<br />
<br />
<br />
Check Queues:<br />
<br />
get-queue -server stgwpvinfexc02<br />
<br />
<br />
Move queued messages to other server:<br />
<br />
Redirect-Message -Server Mailbox01 -Target Mailbox02<br />
<br />
<br />
Check service health (do so on all cluster members):<br/><br />
(test whether all the Microsoft Windows services that Exchange requires on a server have started)<br />
<br />
Test-servicehealth –server EXC02<br />
<br />
<br />
Test MapiConnectivity (Note: this will only test if the DB’s are mounted/active copy on the specific server):<br />
<br />
Test-MapiConnectivity -server EXC02<br />
<br />
<br />
Test/view replication:<br />
<br />
Get-MailboxdatabaseCopystatus -server EXC02<br />
<br />
<br />
Failover Cluster:<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup <br />
<br />
This will failover the 2 node cluster to the other node<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup -node EXC01<br />
<br />
This will failover the cluster to the node EXC01<br />
<br />
<br />
Move Databases:<br />
<br />
Move-ActiveMailboxDatabase DB3 -ActivateOnServer MBX4<br />
<br />
This example performs a switchover of the database DB3 to the Mailbox server MBX4. When the command completes, MBX4 hosts the active copy of DB3. Because the MountDialOverride parameter isn't specified, MBX4 mounts the database using a database auto mount dial setting of Lossless.<br />
<br />
<br />
Get-MailboxDatabase stg-* | Move-ActiveMailboxDatabase -ActivateOnServer MBX4<br />
<br />
Same as above, but moves all databases starting with 'STG-*' to MBX04<br />
<br />
<br />
Move-ActiveMailboxDatabase DB1 -ActivateOnServer MBX3 -MountDialOverride:GoodAvailability<br />
<br />
This example performs a switchover of the database DB1 to the Mailbox server MBX3. When the command completes, MBX3 hosts the active copy of DB1. Because the MountDialOverride parameter is specified with a value of Good Availability, MBX3 mounts the database using a database auto mount dial setting of GoodAvailability.<br />
<br />
== Outlook stuff ==<br />
<br />
=== get all add-ins ===<br />
<br />
Be aware that HKCU can only be grabbed if running in the user context!<br />
<br />
$searchScopes = "HKCU:\SOFTWARE\Microsoft\Office\Outlook\Addins","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins"<br />
$searchScopes | % {Get-ChildItem -Path $_ | % {Get-ItemProperty -Path $_.PSPath} | Select-Object @{n="Name";e={Split-Path $_.PSPath -leaf}},FriendlyName,Description} | Sort-Object -Unique -Property name<br />
<br />
<br />
== Transport stuff ==<br />
<br />
some stuff i used the GUI for<br />
<br />
<br />
=== Relay Configuration (GUI) ===<br />
<br />
Go:<br />
Server-Configuration --> Hub Transport --> Receive Connectors (Tab)<br />
<br />
- Select a valuable connector which matches you needs or create a new.<br />
- for me there was 'Relay internal' which was to allow anonymous connects from spec. hosts/nets --> Double-Click<br />
- Switch to 'Network'-Tab --> Add IP or rage to lower box.<br />
<br />
<br />
<br />
=== Max connection from single IP ===<br />
<br />
set-ReceiveConnector -Identity "exc03\Application_Relay" -MaxInboundConnectionPerSource 50<br />
<br />
sets the max inbound connections per source IP to 50 (default 20)<br />
<br />
<br />
<br />
=== Create an anonymous Receive Connector ===<br />
<br />
after you created an receive connector by GUI you will have to run:<br />
<br />
Get-ReceiveConnector "STGWPVINFEXC02\Application_Relay_Intern" | \<br />
Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"</div>
Cbs
https://schnallich.net/index.php?title=Bind&diff=1762
Bind
2023-11-07T15:20:51Z
<p>Cbs: /* DNSSEC signing */</p>
<hr />
<div><br />
==queries==<br />
<br />
# query bind server-version<pre>dig @localhost version.bind txt chaos</pre><br />
<br />
<br />
==security==<br />
<br />
# be authorative !!!1!!111!!einelf<br />
# protect against ddos-enslaving<br />
# nutze DNSSec!!<br />
# verifiziere dnssec-keys!!<br />
# erstelle keys um dynamische zone-updates zu erlauben!!!<br/>keine updates auf basis von ip-adressen!!!!!<br />
<br />
<br />
== protect bind9 against ddos-enslaving ==<br />
<br />
es gibt mehrere moeglichkeiten.<br/><br />
zum einen habe ich VIEW's eingefuehrt damit meine dns nach aussen 'nur' noch authoritativ antworten. <br/><br />
<br/><br />
da meine dns-server ebenfalls SPF, DKIM und DNSSEC und nicht zuletzt IPv6 unterstuetzen, koennen antworten dennoch sehr gross sein. <br/><br />
dies ist fuer den betreiber eines servers, der nichts mit der anfrage zutun hat sehr <br/><br />
aergerlich, da seine bandbreite verbrannt wird. <br/><br />
das ganze potenziert sich wenn z.b. nicht eine einzelne adresse abgefragt wird, sondern anfragen vom type = ANY <br/><br />
gestellt werden. hier werden nicht selten responses erreicht die 30 - 50 records enthalten.... <br/><br />
<br/><br />
ich habe mich daher entschieden meinen bind9 so zu patchen, dass es NUR noch per TCP type = ANY anfragen beantwortet.<br/><br />
<br/><br />
hier der patch:<br/><br />
<br />
<pre><br />
--- bind9-9.8.4.dfsg.P1/bin/named/query.c.orig 2013-08-23 14:49:39.000000000 +0200<br />
+++ bind9-9.8.4.dfsg.P1/bin/named/query.c 2013-08-22 14:11:53.000000000 +0200<br />
@@ -7658,6 +7658,12 @@<br />
if (dns_rdatatype_ismeta(qtype)) {<br />
switch (qtype) {<br />
case dns_rdatatype_any:<br />
+ /* direct all TYPE=255/ANY queries to TCP */<br />
+ if (qtype == dns_rdatatype_any &&<br />
+ (client->attributes & NS_CLIENTATTR_TCP) == 0)<br />
+ {<br />
+ client->message->flags |= DNS_MESSAGEFLAG_TC;<br />
+ }<br />
break; /* Let query_find handle it. */<br />
case dns_rdatatype_ixfr:<br />
case dns_rdatatype_axfr:<br />
</pre><br />
<br />
dies sorgt dafuer, dass anfragen vom type=ANY mit dem hinweis abgelehnt werden, dass hierfuer nicht UDP sondern TCP verwendet werden muss und der client stellt seine anfrage erneut per TCP-protokoll. fuer legitime anfragen bedeutet das: es dauert ein paar millisekunden laenger bis die anfrage beantwortet ist.<br/><br />
fuer angreifer die einen DDoS durchfuehren wollen, ist dies allerdings ein problem. beim TCP protokoll kann man die absenderadresse nicht (so leicht) faelschen und es gehen nur noch winzige 'DNS_MESSAGEFLAG_TC' messages an den angegriffenen raus.<br />
<br />
<br />
===DNSSEC signing===<br />
<br />
MINI-MINI howto... ;-)<br/><br />
<br />
zuerst erstellen wir den ZSK (ZoneSigningKey) und den KSK (KeySigningKey)<br />
<pre><br />
cd /etc/bind<br />
# ZSK erstellen<br />
dnssec-keygen -a ECDSAP256SHA256 -e -n ZONE alg13.com<br />
# KSK erstellen<br />
dnssec-keygen -a ECDSAP256SHA256 -e -n ZONE -f KSK alg13.com<br />
</pre><br />
dies erstellt je 2 schluessel (public/private), also insgesamt 4 key's<br />
z.b.<br/><br />
Kexample1.com.+005+61648 ==> ZSK<br/><br />
Kexample1.com.+005+22804 ==> KSK<br/><br />
wenn man vergessen hat, welcher key der KSK- bzw. der ZSK-key ist,<br/><br />
ist das nicht weiter schlimm...<br/><br />
wenn man in die publik key's rein schaut findet man etwas wie:<br />
<br />
DNSKEY 256<br />
<br />
dies ist der ZSK, oder:<br />
<br />
DNSKEY 257<br />
<br />
dann ist es der KSK<br />
<br />
<br />
wenn man die key's beim signieren vertauscht, bekommt man fehlermeldungen beim signieren (No shit, Sherlock!) ;-)<br/><br />
die meldung am ende sieht dann in etwa so aus:<br />
<pre><br />
The zone is not fully signed for the following algorithms: RSASHA1.<br />
dnssec-signzone: fatal: DNSSEC completeness test failed.<br />
</pre><br />
dann die keys einfach vertauschen beim signieren und nochmal probieren...<br/><br />
<br/><br />
<br />
nun packen wir den inhalt der .key dateien in unser zonen-file:<br />
cat Kexample1.com*.key >> /var/cache/bind/example1.com.hosts<br />
<br />
nun signieren wir unser zonen-file:<br />
dnssec-signzone -s now+0 -e now+2419200 -o example1.com -k Kexample1.com.+005+22804 /var/cache/bind/example1.com.hosts Kexample1.com.+005+61648<br />
-e now+2419200 = 30 days<br />
<br />
wenn das fehlerfrei durchlaufen wird, bekommen wir die datei:<br />
/var/cache/bind/example1.com.hosts.signed<br />
<br />
diese machen wir nun unserem bind bekannt indem wir in<br/><br />
der named.conf folgende anpassungen machen:<br />
<pre><br />
options {<br />
[...]<br />
<br />
dnssec-enable yes;<br />
<br />
[...]<br />
};<br />
<br />
[...]<br />
<br />
zone "example1.com" {<br />
[...]<br />
<br />
file "/var/cache/bind/example1.com.hosts.signed";<br />
<br />
[...]<br />
};<br />
</pre><br />
<br />
nun noch ein:<br />
/etc/init.d/bind9 restart<br />
<br />
und testen obs geht:<br />
dig @my-dnssec.server.tld example1.com any<br />
dies sollte nun einiges an 'DNSKEY'-eintraegen zurueck geben.<br />
<br />
===DNSSEC verify===<br />
<br />
[http://fanf.livejournal.com/107310.html VIA]<br/><br />
<br />
How to set up DNSSEC validation with BIND-9.7<br />
<br />
* The root zone is now signed! It's time to install the trust anchor on your recursive name servers. Getting it is more fiddly than it should be, since BIND does not recognize the format of the trust anchor as it is published by IANA.<br />
* Get the root DNSKEY RR set which is roughly what BIND requires for trust anchors.<br />
$ dig +multi +noall +answer DNSKEY . >root-dnskey<br />
The resulting file contains two keys, a short-lived zone-signing key (flags = 256) and the key-signing key (flags = 257) which is the one we care about.<br />
<br />
<pre><br />
. 86400 IN DNSKEY 256 3 8 (<br />
AwEAAb1gcDhBlH/9MlgUxS0ik2dwY/JiBIpV+EhKZV7L<br />
ccxNc6Qlj467QjHQ3Fgm2i2LE9w6LqPFDSng5qVq1OYF<br />
yTBt3DQppqDnAPriTwW5qIQNDNFv34yo63sAdBeU4G9t<br />
v7dzT5sPyAgmVh5HDCe+6XM2+Iel1+kUKCel8Icy19hR<br />
) ; key id = 41248<br />
. 86400 IN DNSKEY 257 3 8 (<br />
AwEAAagAIKlVZrpC6Ia7gEzahOR+9W29euxhJhVVLOyQ<br />
bSEW0O8gcCjFFVQUTf6v58fLjwBd0YI0EzrAcQqBGCzh<br />
/RStIoO8g0NfnfL2MTJRkxoXbfDaUeVPQuYEhg37NZWA<br />
JQ9VnMVDxP/VHL496M/QZxkjf5/Efucp2gaDX6RS6CXp<br />
oY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3<br />
LQpzW5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGO<br />
Yl7OyQdXfZ57relSQageu+ipAdTTJ25AsRTAoub8ONGc<br />
LmqrAmRLKBP1dfwhYB4N7knNnulqQxA+Uk1ihz0=<br />
) ; key id = 19036<br />
</pre><br />
<br />
* Turn the DNSKEY into a DS RR set. The dnssec-dsfromkey program ignores the ZSK and only emits DS RRs for the KSK.<br />
$ dnssec-dsfromkey -f root-dnskey . >root-ds<br />
It emits two RRs, one using SHA-1 and one using SHA-256.<br />
<br />
<pre><br />
. IN DS 19036 8 1 B256BD09DC8DD59F0E0F0D8541B8328DD986DF6E<br />
. IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5<br />
</pre><br />
<br />
* Fetch https://data.iana.org/root-anchors/root-anchors.xml which contains a copy of the SHA-256 DS record in XML format.<br />
<br />
<pre><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<TrustAnchor id="AD42165F-3B1A-4778-8F42-D34A1D41FD93"<br />
source="http://data.iana.org/root-anchors/root-anchors.xml"><br />
<Zone>.</Zone><br />
<KeyDigest id="Kjqmt7v" validFrom="2010-07-15T00:00:00+00:00"><br />
<KeyTag>19036</KeyTag><br />
<Algorithm>8</Algorithm><br />
<DigestType>2</DigestType><br />
<Digest>49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5</Digest><br />
</KeyDigest><br />
</TrustAnchor><br />
</pre><br />
<br />
* You can also fetch https://data.iana.org/root-anchors/root-anchors.asc and use it to verify the XML trust anchor using PGP.<br />
* Verify that the XML trust anchor matches the DS record you generated from the DNSKEY record.<br />
* Reformat the DNSKEY record into a BIND managed-keys clause. This tells BIND to automatically update the trust anchor according to RFC 5011.<br />
<br />
<pre><br />
managed-keys {<br />
"." initial-key 257 3 8 "<br />
AwEAAagAIKlVZrpC6Ia7gEzahOR+9W29euxhJhVVLOyQ<br />
bSEW0O8gcCjFFVQUTf6v58fLjwBd0YI0EzrAcQqBGCzh<br />
/RStIoO8g0NfnfL2MTJRkxoXbfDaUeVPQuYEhg37NZWA<br />
JQ9VnMVDxP/VHL496M/QZxkjf5/Efucp2gaDX6RS6CXp<br />
oY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3<br />
LQpzW5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGO<br />
Yl7OyQdXfZ57relSQageu+ipAdTTJ25AsRTAoub8ONGc<br />
LmqrAmRLKBP1dfwhYB4N7knNnulqQxA+Uk1ihz0= ";<br />
};<br />
</pre><br />
<br />
* Add the managed-keys clause to your named.conf<br />
* In the options section of named.conf you should have the directive<br />
<br />
dnssec-lookaside auto;<br />
<br />
This enables DNSSEC lookaside validation, which is necessary to bridge gaps (such as ac.uk) in the chain of trust between the root and lower-level signed zones (such as cam.ac.uk). BIND comes with a DLV trust anchor built in, which it will also update according to RFC 5011.<br />
<br />
* $ rndc reconfig<br />
* Check that DNSSEC validation is working. Verify that the "ad" (authenticated data) flag is present in the output of these commands:<br />
<br />
$ dig +dnssec www.nic.cat.<br />
$ dig +dnssec www.cam.ac.uk.<br />
<br />
The first of these is validated using a chain of trust from the root - DNSSEC as it is ideally intended to work. The second relies on the DLV stop-gap.<br />
<br />
=== chain of trust ===<br />
<br />
[[Datei:DNSSEC.png]]<br />
<br />
<br />
===dns-key erstellen===<br />
dnssec-keygen -a HMAC-MD5 -b 512 -n USER foo22.bar44.com<br />
dieser key kann z.b. fuer die dns-zone foo22.bar44.com verwendet werden<br/><br />
um dynamische zone-updates zu erlauben.<br/> <br />
die keys werden nach /etc/bind/ kopiert<br/><br />
dann muss man dann noch folgendes<br/><br />
'''ausserhalb''' der options-section in die named.conf eintragen:<br />
<pre><br />
[...]<br />
<br />
key foo22.bar44.com. {<br />
algorithm HMAC-MD5;<br />
secret "1Yjjw072uaYWq1eehnA/xtbXOB6Ul3Q/5FFv9//2I4UUm6yscXIFuDp8 nmRQ2QFRfrsU+R1R2zIpJjZ4pFJOrw==";<br />
};<br />
<br />
[...]<br />
<br />
zone "foo22.bar44.com." {<br />
[...]<br />
allow-update {<br />
key foo22.bar44.com.;<br />
};<br />
[...]<br />
};<br />
<br />
[...]<br />
</pre><br />
# secret = der wert aus Kfoo22.bar44.com.+157+06098.key (pub-key)<br />
<br />
==complete named.conf==<br />
<pre><br />
controls {<br />
unix "/var/run/bind/named.ctl"<br />
perm 0600 owner <BIND-UID> group <BIND-GID><br />
keys { "rndc-key"; };<br />
};<br />
<br />
<br />
// key for zone foo22.bar44.com<br />
key foo22.bar44.com. {<br />
algorithm HMAC-MD5;<br />
secret "1Yjjw072uaYWq1eehnA/xtbXOB6Ul3Q/5FFv9//2I4UUm6yscXIFuDp8 nmRQ2QFRfrsU+R1R2zIpJjZ4pFJOrw==";<br />
};<br />
<br />
// i have an acl defining the openNIC root-servers<br />
// these servers are responsible for domains like:<br />
// .null, .geek, .indy, ...<br />
// this is because i will not use openNIC root servers for general root-servers<br />
// only forward-only zones will redirect the requests to these root's<br />
// but you will have to add new zones for every new top-level domain <br />
// openNIC will serve...<br />
acl "openNICroots" {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
<br />
<br />
<br />
options {<br />
pid-file "/var/run/bind/run/named.pid";<br />
directory "/var/cache/bind";<br />
statistics-file "/var/log/named.stats";<br />
dump-file "/var/log/named.dump";<br />
zone-statistics yes;<br />
<br />
/*<br />
// comment in if you run official zones only!!!!<br />
blackhole {<br />
10/8;<br />
172.16/12;<br />
192.168/16;<br />
};<br />
*/<br />
<br />
auth-nxdomain no;<br />
allow-query { none; };<br />
<br />
allow-transfer {<br />
127.0.0.1;<br />
62.116.129.129; // ns9.schlundtech.de<br />
62.116.163.100; // ns10.schlundtech.de<br />
62.116.162.121; // ns10.schlundtech.de<br />
};<br />
<br />
max-transfer-time-in 10;<br />
max-transfer-idle-in 5;<br />
max-transfer-time-out 10;<br />
max-transfer-idle-out 5;<br />
serial-query-rate 20;<br />
transfer-format many-answers;<br />
transfers-in 80;<br />
transfers-out 80;<br />
transfers-per-ns 30;<br />
tcp-clients 200;<br />
max-cache-size unlimited;<br />
cleaning-interval 60;<br />
lame-ttl 1200;<br />
version "Herr 2.7";<br />
};<br />
<br />
<br />
<br />
// MY Zones here...<br />
<br />
zone "huetzelgruetzel.com" {<br />
[....]<br />
also-notify {<br />
// notify my slaves explicily!<br />
11.12.13.14;<br />
11.12.13.15;<br />
};<br />
};<br />
<br />
<br />
<br />
// openNIC zones<br />
// sadly my ACL openNICroots is not usable in<br />
// 'forwarders {};' definition!!! :-(<br />
zone "geek" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "glue" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
//"openNICroots";<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "indy" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "null" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "oss" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "parody" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "ing" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "bbs" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "fur" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
<br />
zone "free" {<br />
type forward;<br />
forward only;<br />
forwarders {<br />
82.229.244.191;<br />
88.191.51.140;<br />
216.67.98.38;<br />
216.87.84.209;<br />
71.170.11.156;<br />
58.6.115.42;<br />
58.6.115.43;<br />
};<br />
};<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/exchange&diff=1761
Windows/exchange
2023-10-16T13:57:33Z
<p>Cbs: /* Search Mailbox content */</p>
<hr />
<div><br />
== PowerShell ==<br />
<br />
powershell commands<br />
<br />
<br />
=== possible access rights ===<br />
<br />
<pre><br />
The Access Rights parameters are as below:<br />
<br />
ReadItems: The user has the right to read items within the specified folder.<br />
CreateItems The user has the right to create items within the specified folder.<br />
EditOwnedItems The user has the right to edit the items that the user owns in the specified folder.<br />
DeleteOwnedItems The user has the right to delete items that the user owns in the specified folder.<br />
EditAllItems The user has the right to edit all items in the specified folder.<br />
DeleteAllItems The user has the right to delete all items in the specified folder.<br />
CreateSubfolders The user has the right to create subfolders in the specified folder.<br />
FolderOwner The user is the owner of the specified folder. The user has the right to view and move the folder and create subfolders. The user can’t read items, edit items, delete items, or create items.<br />
FolderContact The user is the contact for the specified public folder.<br />
FolderVisible The user can view the specified folder, but can’t read or edit items within the specified public folder.<br />
<br />
The Roles with which we can provide the access rights are as below:<br />
<br />
None FolderVisible<br />
Owner CreateItems, ReadItems, CreateSubfolders, FolderOwner, FolderContact, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingEditor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
Editor CreateItems, ReadItems, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingAuthor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
Author CreateItems, ReadItems, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
NonEditingAuthor CreateItems, ReadItems, FolderVisible<br />
Reviewer ReadItems, FolderVisible<br />
Contributor CreateItems, FolderVisible<br />
<br />
Ref: http://technet.microsoft.com/en-us/library/dd298062(v=exchg.150).aspx<br />
<br />
The following roles apply specifically to calendar folders:<br />
<br />
AvailabilityOnly View only availability data<br />
LimitedDetails View availability data with subject and location<br />
</pre><br />
<br />
<br />
=== create mailbox ===<br />
<br />
Create a new mailbox<br />
<br />
New-Mailbox -Name 'prospect NL' -Alias 'prospect.nl' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Rooms and Equipment' \<br />
-UserPrincipalName 'prospect.nl@arifleet.com' -SamAccountName 'prospect.nl' -FirstName 'prospect' -Initials '' -LastName 'NL' \<br />
-Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Stuttgart Mailbox DB One'<br />
<br />
<br />
=== create linked mailbox ===<br />
<br />
New-Mailbox -Name 'Koroch, Ernst' -Alias 'ekoroch' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Users' -UserPrincipalName \<br />
'ekoroch@arifleet.com' -SamAccountName 'ekoroch' -FirstName 'Ernst' -Initials '' -LastName 'Koroch' -Database 'Stuttgart Mailbox DB One' \<br />
-LinkedMasterAccount 'fleetservices\ekoroch' -LinkedDomainController 'dc03.fleetservices.intra' -LinkedCredential \<br />
'System.Management.Automation.PSCredential'<br />
<br />
<br />
=== Repair Mailbox ===<br />
<br />
see: [https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx]<br />
<br />
New-MailboxRepairRequest -Mailbox <Emailaddress> -CorruptionType SearchFolder,AggregateCounts,ProvisionedFolder,FolderView [-DetectOnly]<br />
<br />
<br />
=== Email-Enable AD Group ===<br />
<br />
Enable-DistributionGroup <ADGroupID> -PrimarySmtpAddress yadda@domain.tld<br />
<br />
<br />
=== Email-Enable AD User ===<br />
<br />
Enable-Mailbox <UserID> -PrimarySmtpAddress yadda@domain.tld -displayname "Yadda, Yadda"<br />
<br />
<br />
=== add mailbox permissions ===<br />
<br />
Add full access to mailbox 'mailbox@arifleet.de' for user 'DOMAIN\user': <br />
<br />
Add-MailboxPermission -Identity mailbox@arifleet.de -User DOMAIN\user -AccessRights Fullaccess -InheritanceType All<br />
<br />
-AccessRights <right> <br/><br />
where <right> may be<br />
<br />
FullAccess<br />
ExternalAccount<br />
DeleteItem<br />
ReadPermission<br />
ChangePermission<br />
ChangeOwner<br />
<br />
disable auto-mapping of <br />
<br />
-Automapping $false<br />
<br />
<br />
=== remove mailbox permissions ===<br />
<br />
remove-MailboxPermission -Identity mailbox@arifleet.de -user domari\user -AccessRights Fullaccess -inheritance all<br />
<br />
<br />
=== add/remove 'Send as' permissions ===<br />
<br />
Add-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
You can grant the permissions by using Active Directory Users & Computers. Simply open the properties of the group, switch to the Security tab, add the mailbox user or group, and then tick the Send As box and apply the change. After making this change you may notice that it does not take effect for up to 2 hours. This is due to caching on the Exchange servers. Though you can speed up the change by restarting the Information Store that is obviously not going to be practical in most production environments, so you’ll often find that you just need to wait.<br />
<br />
Remove-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
<br />
==== 'Send as'/'SendOnBehalf' Distributiongroups ====<br />
<br />
Set-DistributionGroup <DistributionGroupName> -GrantSendOnBehalfTo USER@arifleet.com<br />
<br />
and sendOnBehalf for Distributiongroups<br />
<br />
<br />
<br />
==== SentItem Configuration ====<br />
<br />
Until Exchange 2010:<br />
<br />
Set-MailboxSentItemsConfiguration <ALIAS> -SendAsItemsCopiedTo SenderAndFrom<br />
<br />
Exchange 2016:<br />
<br />
Set-Mailbox -identity <UPN> [-DomainController <HOSTNAME>] -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true<br />
<br />
<br />
=== add mailbox folder permissions ===<br />
<br />
Add-MailboxFolderPermission -Identity poolcar@netcar24.com:\Calendar -user csteidl@arifleet.com -AccessRights [[Windows/exchange#possible_access_rights|<see RIGHTS>]]<br />
<br />
Set default-rights for ressource mailboxes (to show up subjects a.s.o.):<br />
<br />
Set-MailboxFolderPermission meetingroom:\Calendar -User Default -AccessRights Reviewer<br />
<br />
=== get mailbox permissions ===<br />
<br />
get permissions of fhess on mailbox prospect.be<br />
<br />
Get-MailboxPermission -Identity prospect.be@arifleet.com -User "fhess"<br />
<br />
<br />
get folder permissions<br />
<br />
get-mailboxfolderpermission -identity fhess<br />
<br />
<br />
get UPN of users<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.User.ADRecipient.UserPrincipalName }<br />
<br />
<br />
get full user details<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.identity.adrecipient.identity }<br />
<br />
<br />
<br />
=== Find permissions granted to spec. users ===<br />
<br />
Get-Mailbox -RecipientType 'UserMailbox' -ResultSize Unlimited | Get-MailboxPermission | where { $_.user.tostring() -eq "DOMAIN\username" -and $_.IsInherited -eq $false }<br />
<br />
<br />
<br />
=== enable autoreply / vacation message ===<br />
<br />
set the message (optionally) and enable auto reply<br />
<br />
$message = get-content message.txt<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState enabled \<br />
-ExternalAudience <none/all/known> \<br />
-InternalMessage "$message" \<br />
-ExternalMessage "$message"<br />
<br />
<br />
=== disable auto-reply / vacation message ===<br />
<br />
disable auto reply<br />
<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState disabled<br />
<br />
<br />
=== Retention policies ===<br />
<br />
create server side retention policies<br />
<br />
<br />
==== Create Retention Policy Tag ====<br />
<br />
New-RetentionPolicyTag "ARI STG - Delete all 180 days" -Type All -Comment "Deletes all items older 180 days" -RetentionEnabled $true \<br />
-AgeLimitForRetention 180 -RetentionAction DeleteAndAllowRecovery<br />
<br />
RetentionAction: MoveToFolder, MoveToDeletedItems, DeleteAndAllowRecovery, PermanentlyDelete, MoveToArchive<br />
<br />
<br />
==== Create Retention Policy ====<br />
<br />
New-RetentionPolicy "ARI STG - Delete ALL items older 180 days" -RetentionPolicyTagLinks "ARI STG - Delete all 180 days"<br />
<br />
Activate policy by: Open Mailbox Properties --> Mailbox Settings --> Messaging Records Mgmt --> Apply Retention policy<br />
<br />
<br />
=== get distribution group members ===<br />
<br />
get-distributiongroupmember <group><br />
<br />
get-distributiongroupmember mailaddress@arifleet.de<br />
<br />
<br />
=== get users by filter and add to distributiongroup ===<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -ne 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -eq 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
<br />
<br />
=== Get Mailbox by ExchangeGuid/Mapi-session ===<br />
<br />
get-mailbox -ResultSize unlimited | where {$_.ExchangeGuid -eq "265182e3-a31c-4a9f-e38e-687f5a7c2d6b"}<br />
<br />
<br />
=== Get Mailbox by Ressource type ===<br />
<br />
<br />
Get-Mailbox -RecipientTypeDetails RoomMailbox<br />
<br />
Get-Mailbox -RecipientTypeDetails EquipmentMailbox<br />
<br />
<br />
=== Get Mail Public folder ===<br />
<br />
Get-MailPublicFolder helpdesk@sub.domain.com | Get-PublicFolder [| Select *]<br />
<br />
<br />
=== Logging ===<br />
<br />
further logfiles can be found here:<br />
<br />
C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\ProtocolLog<br />
<br />
<br />
==== Track accross multiple servers ====<br />
<br />
get-transportserver<br />
<br />
<br />
e.g. that to "get-messagetrackinglog":<br />
<br />
get-transportserver | get-messagetrackinglog<br />
<br />
<br />
==== message tracking ====<br />
<br />
get-messagetrackinglog -Sender 'user@arifleet.de' -Start "5/04/2015 5:00:00 AM" -End "5/15/2015 8:30:00 AM"<br />
<br />
get-transportserver | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
get-transportservice | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
-Start "6/01/2015 5:00:00 AM" \<br />
-End "6/01/2015 10:30:00 AM" \<br />
-resultsize unlimited | ft -Wrap<br />
<br />
<pre><br />
-MessageSubject <String><br />
-Recipients <String[]><br />
-Start/-End (get-date).AddHours(-1).toString()<br />
-ResultSize Unlimited<br />
</pre><br />
<br />
some more examples:<br />
<br />
get-messagetrackinglog -Recipients:recipient@email.be -Start "6/8/2015 4:42:00 AM" -End "6/9/2015 9:52:00 PM" | Select *,{$_.Recipients} | export-csv .\maillog.csv<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | \<br />
where-object {$_.Recipients -like “*@gmail.com, *@yahoo.com” -AND $_.EventId -eq “Send”} |ft -auto >>C:\External mails.txt<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | sort -property Timestamp<br />
<br />
=== repair mailbox ===<br />
<br />
New-MailboxRepairRequest -Mailbox schaden@arifleet.de -CorruptionType SearchFolder<br />
<br />
<br />
-CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview<br />
-Archive Prueft Mailbox _und_ Archive<br />
-DetectOnly Prueft nur, keine Reparatur!<br />
<br />
Ergebnisse der Prüfung werden im Anwendungs Event-Log des Servers protokolliert. Die Events tragen die folgenden Ereignis-IDs:<br />
<br />
10044,10045,10046,10047,10048,10049,10050,10051,10059,10062<br />
<br />
mit einem rechtsklick auf 'Application' laesst dich das eventlog nach diesen ID's filtern.<br />
<br />
<br />
=== move mailbox between exchange-databases ===<br />
<br />
Move Mailboxes between exchange >= 2010 servers <br/><br />
the output is piped into 'ft' (format table) to get complete output and not stripped it...<br />
<br />
New-MoveRequest -Identity mailbox@arifleet.de -TargetDatabase ‘Whatever Database-Name 001’ | ft -AutoSize -Wrap<br />
<br />
create a batch<br />
<br />
Get-Mailbox -Database "Stuttgart Mailbox DB One" | Where-Object { $_.alias -like "jira*" } | New-MoveRequest -TargetDatabase [...]<br />
<br />
Options:<br />
<br />
-BadItemLimit 0<br />
-Suspend <br />
-SuspendComment "Resume after 11:00 p.m. PST"<br />
-SuspendWhenReadyToComplete<br />
-BatchName "Some Name to identify the Batch-Moves"<br />
<br />
get moverequest status:<br />
<br />
Get-MoveRequestStatistics "sadg"<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics | select DisplayName,alias,Status,TotalMailboxSize,PercentComplete| ft<br />
<br />
<br />
=== get Mailbox sizes ===<br />
<br />
Get-MailboxDatabase | Where-Object { $_.Name -like "STG*" } | Get-MailboxStatistics | sort -property TotalItemSize -desc \<br />
| select DisplayName,ItemCount,TotalItemSize,TotalDeletedItemSize |ft<br />
<br />
<br />
=== get database size ===<br />
<br />
Get-MailboxDatabase -status | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Sort-Object DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Where-Object { $_.name -like "STG*" } | Sort -property DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
=== Export Mailbox (Folder) ===<br />
<br />
New-MailboxExportRequest -mailbox schaden \<br />
-includefolders "******@arifleet.de/00 UNFALLORDNER ab 1.3.2011/Storopack R+V (*.***@*******.com) TK 150 \/ keine VK RA Schmid" \<br />
-filepath "\\stgwpvinfEXC01\g$\Storopack R+V (*.***@*******.com) TK 150_keine VK RA Schmid.pst"<br />
<br />
# be sure to mask e.g. '/' characters in foldernames with '\'<br />
# leave out '''-includefolders''' to export the entire mailbox<br/><br />
## add a '.../*' to -includefolders to include subfolders<br />
<br />
=== Search Mailbox content ===<br />
<br />
This one searches for all messages between 1/1/2017 and 12/31/2018 and creates copies of it within the Mailbox of targetmailbox into targetfolder:<br />
<br />
Search-Mailbox -Identity <USER-ID> -SearchQuery "received>=01/01/2017 AND received<=12/31/2018" -targetmailbox "<TARGET-USER-ID>" -targetfolder "SearchResults"<br />
<br />
SearchQuery examples: <br/><br />
<br />
"Subject:Project Hamilton"<br/><br />
"election OR candidate OR vote" - all messages that contain one of the words in whole message<br/><br />
<br />
<b>If the Subject you are searching for contains COLONS, they need to be masked using back tick "Subject:AW`: yadda yadda"</b><br />
<br />
=== set thumbnail-image ===<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
<br />
=== Import/Acivate new Certificate ===<br />
<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path c:\certificates\YOUR_CERTIFICATE.cer -Encoding byte -ReadCount 0))<br />
<br />
In case of encrypted .pfx or something like that:<br />
<br />
$pass = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -Password $pass -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path Webmail.pfx -Encoding byte -ReadCount 0))<br />
<br />
activate:<br />
<br />
Enable-ExchangeCertificate -Thumbprint 1234ae0567a72fccb75b1d0198628675333d010e -Services POP,IMAP,SMTP,IIS<br />
<br />
=== DAG/Cluster stuff ===<br />
<br />
Check who's master:<br />
<br />
Get-ClusterGroup EU-DAG<br />
<br />
<br />
Get detailed DAG info:<br />
<br />
Get-DatabaseAvailabilityGroup STG-DAG -status | fl<br />
<br />
<br />
Test replication health (do so on all cluster members):<br />
<br />
Test-ReplicationHealth -server EXC02<br />
<br />
<br />
Get mount status, copy/reply queue, Index state<br />
<br />
Get-MailboxDatabaseCopyStatus -server exc01<br />
<br />
<br />
Check Queues:<br />
<br />
get-queue -server stgwpvinfexc02<br />
<br />
<br />
Move queued messages to other server:<br />
<br />
Redirect-Message -Server Mailbox01 -Target Mailbox02<br />
<br />
<br />
Check service health (do so on all cluster members):<br/><br />
(test whether all the Microsoft Windows services that Exchange requires on a server have started)<br />
<br />
Test-servicehealth –server EXC02<br />
<br />
<br />
Test MapiConnectivity (Note: this will only test if the DB’s are mounted/active copy on the specific server):<br />
<br />
Test-MapiConnectivity -server EXC02<br />
<br />
<br />
Test/view replication:<br />
<br />
Get-MailboxdatabaseCopystatus -server EXC02<br />
<br />
<br />
Failover Cluster:<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup <br />
<br />
This will failover the 2 node cluster to the other node<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup -node EXC01<br />
<br />
This will failover the cluster to the node EXC01<br />
<br />
<br />
Move Databases:<br />
<br />
Move-ActiveMailboxDatabase DB3 -ActivateOnServer MBX4<br />
<br />
This example performs a switchover of the database DB3 to the Mailbox server MBX4. When the command completes, MBX4 hosts the active copy of DB3. Because the MountDialOverride parameter isn't specified, MBX4 mounts the database using a database auto mount dial setting of Lossless.<br />
<br />
<br />
Get-MailboxDatabase stg-* | Move-ActiveMailboxDatabase -ActivateOnServer MBX4<br />
<br />
Same as above, but moves all databases starting with 'STG-*' to MBX04<br />
<br />
<br />
Move-ActiveMailboxDatabase DB1 -ActivateOnServer MBX3 -MountDialOverride:GoodAvailability<br />
<br />
This example performs a switchover of the database DB1 to the Mailbox server MBX3. When the command completes, MBX3 hosts the active copy of DB1. Because the MountDialOverride parameter is specified with a value of Good Availability, MBX3 mounts the database using a database auto mount dial setting of GoodAvailability.<br />
<br />
== Outlook stuff ==<br />
<br />
=== get all add-ins ===<br />
<br />
Be aware that HKCU can only be grabbed if running in the user context!<br />
<br />
$searchScopes = "HKCU:\SOFTWARE\Microsoft\Office\Outlook\Addins","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins"<br />
$searchScopes | % {Get-ChildItem -Path $_ | % {Get-ItemProperty -Path $_.PSPath} | Select-Object @{n="Name";e={Split-Path $_.PSPath -leaf}},FriendlyName,Description} | Sort-Object -Unique -Property name<br />
<br />
<br />
== Transport stuff ==<br />
<br />
some stuff i used the GUI for<br />
<br />
<br />
=== Relay Configuration (GUI) ===<br />
<br />
Go:<br />
Server-Configuration --> Hub Transport --> Receive Connectors (Tab)<br />
<br />
- Select a valuable connector which matches you needs or create a new.<br />
- for me there was 'Relay internal' which was to allow anonymous connects from spec. hosts/nets --> Double-Click<br />
- Switch to 'Network'-Tab --> Add IP or rage to lower box.<br />
<br />
<br />
<br />
=== Max connection from single IP ===<br />
<br />
set-ReceiveConnector -Identity "exc03\Application_Relay" -MaxInboundConnectionPerSource 50<br />
<br />
sets the max inbound connections per source IP to 50 (default 20)<br />
<br />
<br />
<br />
=== Create an anonymous Receive Connector ===<br />
<br />
after you created an receive connector by GUI you will have to run:<br />
<br />
Get-ReceiveConnector "STGWPVINFEXC02\Application_Relay_Intern" | \<br />
Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"</div>
Cbs
https://schnallich.net/index.php?title=OpenSSL&diff=1760
OpenSSL
2023-09-11T09:41:35Z
<p>Cbs: </p>
<hr />
<div>==Optionale Parameter fuer die folgenden commandos==<br />
<br />
-config /path/to/own/my_openssl.cnf<br />
separate config-datei verwenden.<br />
<br />
-nodes<br />
verhindert das verschluesseln des key mit einem Passwort.<br/><br />
Die ist wichtig bei key's fuer serverdienste. oder das passwort<br/><br />
muss beim neustart des dienstes eingegeben werden.<br />
<br />
<br />
==Request (CSR) erstellen==<br />
<br />
openssl req -newkey rsa:2048 -out request.pem -keyout pub-sec-key.pem<br />
Generiert einen neuen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Passend dazu wird ein Request in der Datei request.pem erstellt.<br />
<br />
openssl req -new -out request.pem -key pub-sec-key.pem<br />
Wie zuvor, nur wird der Request zum bereits vorhandenen Schlüssel pub-sec-key.pem generiert.<br />
<br />
openssl req -text -noout -in request.pem<br />
Zeigt den Request request.pem an.<br />
<br />
openssl req -verify -noout -in request.pem<br />
Verifiziert die Selbstsignatur des Requests request.pem.<br />
<br />
openssl req -noout -modulus -in request.pem | openssl sha1 -c<br />
Generiert einen SHA1-Fingerabdruck vom Modulus des Schlüssels aus dem Request request.pem.<br />
<br />
openssl x509 -x509toreq -in self-signed-certificate.pem -signkey pub-sec-key.pem -out request.pem<br />
Erstellt neuen Request aus altem Selbstzertifikat.<br />
<br />
<br />
==Request (CSR) mit CA signieren==<br />
<br />
openssl ca -out certs/openVPN_Vorname.Nachname.crt -in openVPN_Vorname.Nachname.csr<br />
<br />
<br />
==Certificate (CRT) erstellen==<br />
<br />
openssl req -x509 -days 365 -newkey rsa:2048 \<br />
-out self-signed-certificate.pem -keyout pub-sec-key.pem<br />
Generiert einen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Es wird ein selbst signiertes Zertifikat erstellt und in der Datei self-signed-certificate.pem gespeichert. Das Zertifikat ist 365 Tag gültig und für simple Testzwecke gedacht.<br />
<br />
openssl req -x509 -days 365 -new -out self-signed-certificate.pem -key pub-sec-key.pem<br />
Wie zuvor, erstellt jedoch ein selbst signiertes Zertifikat aus einem vorhandenen Schlüssel pub-sec-key.pem.<br />
<br />
<br />
== ECC Key erstellen ==<br />
<br />
openssl ecparam -list_curves<br />
List possible curves<br />
<br />
openssl ecparam -name secp384r1 -genkey -out private.ecc-key.pem<br />
Erstellt einen elliptic curve key, der zur Generierung eines passenden CSR verwendet werden kann.<br />
<br />
== Certifikate konvertieren, ausgeben, pruefen ==<br />
<br />
openssl x509 -text -noout -md5 -in self-signed-certificate.pem<br />
Gibt das Zertifikat self-signed-certificate.pem als Klartext aus.<br />
<br />
openssl x509 -fingerprint -noout -md5 -in self-signed-certificate.pem<br />
Gibt den Fingerabdruck des X.509 Zertifikats self-signed-certificate.pem aus. Der Algorithmus ist hier MD5, SHA1 kann<br />
verwendet werden, wenn -md5 durch -sha1 ersetzt wird.<br />
<br />
openssl verify -issuer_checks -CAfile self-signed-certificate.pem self-signed-certificate.pem<br />
Überprüft ein selbst signiertes Zertifikat.<br />
<br />
openssl s_client -showcerts -CAfile self-signed-certificate.pem -connect www.dfn-pca.de:443<br />
Baut eine OpenSSL-Verbindung unter Verwendung des Zertifikats self-signed-certificate.pem zum angegebenen Server auf. Es wird dabei die gesamte Zertifikatskette angezeigt.<br />
<br />
openssl crl -noout -text -CAfile self-signed-certificate.pem crl.pem<br />
Gibt die Zertifikats-Widerrufsliste crl.pem in Klartext aus.<br />
<br />
<br />
=== PKCS12/PFX conversion ===<br />
<br />
Create PKCS12 from PEM:<br />
<br />
openssl pkcs12 -export -in myCertificate.crt -inkey myCertificate.key -certfile cacert.pem -out myCertificate.pkcs12<br />
<br />
<br />
export pem's from pkcs12-files:<br />
<br />
openssl pkcs12 -in cert.p12 -clcerts -nokeys -nodes -out ./cert.pem<br />
openssl pkcs12 -in cert.p12 -cacerts -nokeys -nodes -out ./root-chain.pem<br />
openssl pkcs12 -in cert.p12 -nocerts -nodes -out ./key.pem<br />
<br />
=== PKCS7 conversion ===<br />
<br />
openssl pkcs7 -in cert.p7b -inform DER -print_certs -out cert.pem<br />
<br />
<br />
=== PEM to DER and DER 2 PEM ===<br />
<br />
Use the OpenSSL commands to convert between formats as follows:<br />
<br />
To convert a certificate from PEM to DER:<br />
openssl x509 -in input.crt -inform PEM –out output.crt -outform DER<br />
<br />
To convert a certificate from DER to PEM:<br />
openssl x509 -in input.crt -inform DER -out output.crt -outform PEM<br />
<br />
To convert a key from PEM to DER:<br />
openssl rsa -in input.key -inform PEM -out output.key -outform DER<br />
<br />
To convert a key from DER to PEM:<br />
openssl rsa -in input.key -inform DER -out output.key -outform PEM<br />
<br />
== Schluessel (KEY) bearbeiten ==<br />
<br />
veraenderungen an vorhandenen schluesseln vornehmen<br />
<br />
<br />
=== Schluessel (KEY) passwort aendern ===<br />
<br />
openssl rsa -in mykey.pem -des3 -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn unter verwendung eines anderen passwortes wieder ab.<br />
<br />
<br />
=== Schluessel (KEY) passwort entfernen ===<br />
<br />
openssl rsa -in mykey.pem -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn OHNE neues passwort wieder ab. (unsicher!!)<br />
<br />
<br />
==CRLs==<br />
<br />
Die CRL ist eine Widerrufliste in der die ungültigen Zertifikate eingetragen<br />
sind und Zugänge aufgehoben werden können (z.B. beim Ausscheiden eines<br />
Mitarbeiters). Dazu wird periodisch eine gültige CRL erstellt. Einzelne<br />
Zertifikate können dann manuell entfernt werden. Die Sperrung erfolgt dann<br />
beim nächsten Anlegen der Liste. Daher sollte die Liste entweder sofort nach<br />
deaktivieren eines Zertifikats oder, je nach Dringlichkeit, täglich oder<br />
wöchentlich per Cronjob erstellt werden.<br />
<br />
<br />
===das Zertifikat von 'meier' entfernen===<br />
<br />
openssl ca -revoke meiercert.pem<br />
<br />
oder <br />
<br />
openssl ca -revoke ./newcerts/03.pem'<br />
<br />
<br />
===Nummern der gesperrten Zertifikate anzeigen===<br />
<br />
openssl crl -in crls/crl.pem -noout -text<br />
<br />
<br />
===gültige CRL erstellen===<br />
<br />
openssl ca -gencrl -out crls/crl.pem<br />
dies muss nach '''JEDEM''' widerruf von certifikaten gemacht werden!!!!<br />
<br />
<br />
===CRL in das binäre DER-Format umwandeln===<br />
<br />
openssl crl -in crls/crl.pem -outform der -out crls/cert.crl<br />
<br />
<br />
== Verifying ==<br />
<br />
=== That a Private Key Matches a Certificate ===<br />
<br />
openssl x509 -noout -text -in server.crt<br />
openssl rsa -noout -text -in server.key<br />
<br />
The `modulus' and the `public exponent' portions in the key and the Certificate must match. But since the public exponent is usually 65537 and it's bothering comparing long modulus you can use the following approach:<br />
<br />
<br />
openssl x509 -noout -modulus -in server.crt | openssl md5<br />
openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And then compare these really shorter numbers. With overwhelming probability they will differ if the keys are different. As a "one-liner":<br />
<br />
openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And with auto-magic comparison (If more than one hash is displayed, they don't match):<br />
<br />
(openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5) | uniq<br />
<br />
BTW, if I want to check to which key or certificate a particular CSR belongs you can compute<br />
<br />
$ openssl req -noout -modulus -in server.csr | openssl md5<br />
<br />
(Shamelessly stolen from [https://kb.wisc.edu/middleware/page.php?id=4064 here])<br />
<br />
<br />
=== That a cacert matches a server cert ===<br />
<br />
openssl verify -verbose -CAfile cacert.pem server.crt<br />
<br />
<br />
== Pinning / TLSA / etc. ==<br />
<br />
=== Get public key PIN ===<br />
<br />
Get PIN from CERT:<br />
<br />
openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from KEY:<br />
<br />
openssl rsa -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from ECC KEY:<br />
<br />
openssl ec -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from CSR:<br />
<br />
openssl req -in signing-request.csr -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
=== TLSA hash ===<br />
<br />
openssl x509 -in cert.pem -noout -fingerprint -sha256 | tr -d ":" | sed 's/SHA256 Fingerprint=//'</div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1759
Windows/powershell
2023-08-22T12:02:04Z
<p>Cbs: /* set AD password */</p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== Activation through License Server fails ==<br />
<br />
If that happens you need to: <br />
<br />
# Delete current key<br />
# Set general Key N69G4-B89J2-4G8F4-WWYCC-J464C<br />
# Trigger activation again<br />
<br />
Detele current Key:<br />
<br />
slmgr /upk<br />
<br />
Set new Key:<br />
<br />
slmgr /ipk N69G4-B89J2-4G8F4-WWYCC-J464C<br />
<br />
Trigger activation:<br />
<br />
slmgr /ato<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
or<br />
<br />
Set-ADAccountPassword -Identity $user -OldPassword (ConvertTo-SecureString -AsPlainText "p@ssw0rd" -Force) -NewPassword (ConvertTo-SecureString -AsPlainText "qwert@12345" -Force)<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== Change Drive Letter ==<br />
<br />
From D: to Z: in this example:<br />
<br />
Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'}<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
Query SPN:<br />
<br />
setspn -T europe -F -Q */ff1backup.domain.tld<br />
<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Trigger Client Action ===<br />
<br />
<pre><br />
Cycle ID<br />
ApplicationDeployment Evaluation Cycle "{00000000-0000-0000-0000-000000000121}"<br />
DiscoveryData Collection Cycle "{00000000-0000-0000-0000-000000000003}"<br />
FileCollection Cycle "{00000000-0000-0000-0000-000000000010}"<br />
HardwareInventory Cycle "{00000000-0000-0000-0000-000000000001}"<br />
MachinePolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000021}"<br />
SoftwareInventory Cycle "{00000000-0000-0000-0000-000000000002}"<br />
SoftwareMetering Usage Report Cycle "{00000000-0000-0000-0000-000000000031}"<br />
SoftwareUpdate Deployment Evaluation Cycle "{00000000-0000-0000-0000-000000000114}"<br />
SoftwareUpdate Scan Cycle "{00000000-0000-0000-0000-000000000113}"<br />
StateMessage Refresh "{00000000-0000-0000-0000-000000000111}"<br />
UserPolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000026}"<br />
UserPolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000027}"<br />
WindowsInstallers Source List Update Cycle "{00000000-0000-0000-0000-000000000032}"<br />
MachinePolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000022}"<br />
</pre><br />
<br />
Run Cycle:<br />
<br />
Invoke-WMIMethod -Namespace root\ccm -Class SMS_CLIENT -Name TriggerSchedule "{00000000-0000-0000-0000-000000000121}"<br />
<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1758
Windows/powershell
2023-07-21T09:13:55Z
<p>Cbs: /* setspn */</p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== Activation through License Server fails ==<br />
<br />
If that happens you need to: <br />
<br />
# Delete current key<br />
# Set general Key N69G4-B89J2-4G8F4-WWYCC-J464C<br />
# Trigger activation again<br />
<br />
Detele current Key:<br />
<br />
slmgr /upk<br />
<br />
Set new Key:<br />
<br />
slmgr /ipk N69G4-B89J2-4G8F4-WWYCC-J464C<br />
<br />
Trigger activation:<br />
<br />
slmgr /ato<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== Change Drive Letter ==<br />
<br />
From D: to Z: in this example:<br />
<br />
Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'}<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
Query SPN:<br />
<br />
setspn -T europe -F -Q */ff1backup.domain.tld<br />
<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Trigger Client Action ===<br />
<br />
<pre><br />
Cycle ID<br />
ApplicationDeployment Evaluation Cycle "{00000000-0000-0000-0000-000000000121}"<br />
DiscoveryData Collection Cycle "{00000000-0000-0000-0000-000000000003}"<br />
FileCollection Cycle "{00000000-0000-0000-0000-000000000010}"<br />
HardwareInventory Cycle "{00000000-0000-0000-0000-000000000001}"<br />
MachinePolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000021}"<br />
SoftwareInventory Cycle "{00000000-0000-0000-0000-000000000002}"<br />
SoftwareMetering Usage Report Cycle "{00000000-0000-0000-0000-000000000031}"<br />
SoftwareUpdate Deployment Evaluation Cycle "{00000000-0000-0000-0000-000000000114}"<br />
SoftwareUpdate Scan Cycle "{00000000-0000-0000-0000-000000000113}"<br />
StateMessage Refresh "{00000000-0000-0000-0000-000000000111}"<br />
UserPolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000026}"<br />
UserPolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000027}"<br />
WindowsInstallers Source List Update Cycle "{00000000-0000-0000-0000-000000000032}"<br />
MachinePolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000022}"<br />
</pre><br />
<br />
Run Cycle:<br />
<br />
Invoke-WMIMethod -Namespace root\ccm -Class SMS_CLIENT -Name TriggerSchedule "{00000000-0000-0000-0000-000000000121}"<br />
<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1757
Windows/powershell
2023-04-25T06:19:36Z
<p>Cbs: </p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== Activation through License Server fails ==<br />
<br />
If that happens you need to: <br />
<br />
# Delete current key<br />
# Set general Key N69G4-B89J2-4G8F4-WWYCC-J464C<br />
# Trigger activation again<br />
<br />
Detele current Key:<br />
<br />
slmgr /upk<br />
<br />
Set new Key:<br />
<br />
slmgr /ipk N69G4-B89J2-4G8F4-WWYCC-J464C<br />
<br />
Trigger activation:<br />
<br />
slmgr /ato<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== Change Drive Letter ==<br />
<br />
From D: to Z: in this example:<br />
<br />
Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'}<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Trigger Client Action ===<br />
<br />
<pre><br />
Cycle ID<br />
ApplicationDeployment Evaluation Cycle "{00000000-0000-0000-0000-000000000121}"<br />
DiscoveryData Collection Cycle "{00000000-0000-0000-0000-000000000003}"<br />
FileCollection Cycle "{00000000-0000-0000-0000-000000000010}"<br />
HardwareInventory Cycle "{00000000-0000-0000-0000-000000000001}"<br />
MachinePolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000021}"<br />
SoftwareInventory Cycle "{00000000-0000-0000-0000-000000000002}"<br />
SoftwareMetering Usage Report Cycle "{00000000-0000-0000-0000-000000000031}"<br />
SoftwareUpdate Deployment Evaluation Cycle "{00000000-0000-0000-0000-000000000114}"<br />
SoftwareUpdate Scan Cycle "{00000000-0000-0000-0000-000000000113}"<br />
StateMessage Refresh "{00000000-0000-0000-0000-000000000111}"<br />
UserPolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000026}"<br />
UserPolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000027}"<br />
WindowsInstallers Source List Update Cycle "{00000000-0000-0000-0000-000000000032}"<br />
MachinePolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000022}"<br />
</pre><br />
<br />
Run Cycle:<br />
<br />
Invoke-WMIMethod -Namespace root\ccm -Class SMS_CLIENT -Name TriggerSchedule "{00000000-0000-0000-0000-000000000121}"<br />
<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Cisco/CLI&diff=1756
Cisco/CLI
2023-02-21T15:06:04Z
<p>Cbs: /* Import SSL/TLS Cert and Key */</p>
<hr />
<div><br />
== Firmware upgrade ==<br />
<br />
<br />
=== Copy (SCP) firmware to asa ===<br />
<br />
Be sure to explicitly name the file on the target or upload will fail.<br/><br />
ASA will not name the file the same like the sourcefile by its own.<br />
<br />
scp asa<VERSION>-<PATCH>-smp-k8.bin asa.domain.tld:disk0:/asa<VERSION>-<PATCH>-smp-k8.bin<br />
<br />
<br />
<br />
=== Upgrade firmware ===<br />
<br />
Upload new firmware to flash before starting.<br/><br />
<br />
<pre><br />
! Deactivate old boot image<br />
no boot system disk0:/asa963-1-smp-k8.bin<br />
<br />
! Add new image as primary boot with old as backup<br />
boot system disk0:/asa964-3-smp-k8.bin<br />
boot system disk0:/asa963-1-smp-k8.bin<br />
<br />
! Save changes to config<br />
write memory<br />
<br />
! This will cause the standby firewall to reload<br />
failover reload-standby<br />
<br />
! After getting messages that standby has rebooted, verify that failover is ready<br />
show failover<br />
<br />
! This forces active firewall to become standby, and standby to active<br />
no failover active<br />
<br />
! reload new standby firewall after failing over<br />
failover reload-standby<br />
</pre><br />
<br />
== Cheat Sheet ==<br />
<br />
Another thing you can do with the ASDM client is to enable command previews.<br/><br />
This allows you to configure things in the ASDM but before it sends them to the firewall it will show you the CLI that is being used.<br/><br />
This is enabled through the ASDM > Tools > Preferences > Preview commands before sending them to the device<br />
<br />
<br />
=== Show/Enable and Disable Logs in terminal ===<br />
<br />
Enable:<br />
<br />
terminal monitor<br />
<br />
Disable:<br />
<br />
terminal no monitor<br />
<br />
<br />
=== Disable pager ===<br />
<br />
terminal pager 0<br />
<br />
<br />
=== Show NAT/PAT translation table ===<br />
<br />
show xlate<br />
<br />
<br />
=== Show access-group ===<br />
<br />
will show you access lists bound to each interface:<br />
show running-config | include access-group <br />
<br />
<pre><br />
# sh run | incl access-gr<br />
access-group inside_to_outside_dmz in interface inside<br />
access-group stgoffice_to_inside_outside in interface stgoffice<br />
access-group dmz_to_inside_outside in interface dmz<br />
access-group guestwireless_to_inside_outside in interface guestwlan<br />
access-group bmw_to_inside_dmz in interface bmw<br />
access-group allowarius in interface outside-itenos<br />
access-group outside_to_inside_dmz in interface outside-telekom<br />
</pre><br />
<br />
<br />
=== Show access-list ===<br />
<br />
will show you the rules with all groups expanded and resolve names to IPs.<br/><br />
It also shows you the hit count of the rule so you can see if it’s not being used.<br/><br />
Lastly it shows you the access list sequence number if you need to put a rule in the middle of the ruleset:<br />
show access-list <access-list name><br />
<br />
<pre><br />
# sh access-list inside_to_outside_dmz<br />
access-list inside_to_outside_dmz; 381 elements; name hash: 0x9b447bd7<br />
access-list inside_to_outside_dmz line 1 remark Allow access to SHDEAGB<br />
access-list inside_to_outside_dmz line 2 extended permit ip object NET_RZ object SHDEAGB (hitcnt=0) 0xb3e4ce53<br />
access-list inside_to_outside_dmz line 2 extended permit ip 10.3.11.0 255.255.255.0 10.1.1.0 255.255.255.0 (hitcnt=0) 0xb3e4ce53<br />
access-list inside_to_outside_dmz line 3 remark Allow access to VPN clients<br />
access-list inside_to_outside_dmz line 4 extended permit ip object-group NET_RFC1918 object AnyConnect (hitcnt=1519518) 0xbacaa3e8<br />
access-list inside_to_outside_dmz line 4 extended permit ip 10.0.0.0 255.0.0.0 10.219.112.0 255.255.255.0 (hitcnt=1495910) 0x7e937191<br />
access-list inside_to_outside_dmz line 4 extended permit ip 192.168.0.0 255.255.0.0 10.219.112.0 255.255.255.0 (hitcnt=23461) 0x484233c3<br />
access-list inside_to_outside_dmz line 4 extended permit ip 172.16.0.0 255.240.0.0 10.219.112.0 255.255.255.0 (hitcnt=147) 0xda51da6b<br />
access-list inside_to_outside_dmz line 5 extended permit ip object-group NET_RFC1918 object NET_Stuttgart_Office (hitcnt=7856134) 0xcec84ac2<br />
access-list inside_to_outside_dmz line 5 extended permit ip 10.0.0.0 255.0.0.0 10.3.14.0 255.255.254.0 (hitcnt=7492424) 0x6f88731b<br />
access-list inside_to_outside_dmz line 5 extended permit ip 192.168.0.0 255.255.0.0 10.3.14.0 255.255.254.0 (hitcnt=363163) 0x6ba488f1<br />
access-list inside_to_outside_dmz line 5 extended permit ip 172.16.0.0 255.240.0.0 10.3.14.0 255.255.254.0 (hitcnt=547) 0x71ac3184<br />
</pre><br />
<br />
<br />
Show access-list beginning at a specific line:<br />
<br />
sh access-list dmz_to_inside_outside | beg line 71<br />
<br />
<br />
=== Show object (oneline) ===<br />
<br />
See objects on one line:<br />
show running-config object in-line<br />
<br />
<pre><br />
# show running-config object in-line | incl 11.89<br />
object network ADDR_STGMON001 host 192.168.11.89<br />
</pre><br />
<br />
<br />
=== Show object-group by name ===<br />
<br />
sh run object-group id <GRP_Name><br />
<br />
<br />
=== Show running config beginning from pattern ===<br />
<br />
# more system:running-config | beg tunnel-group 100.11.12.13<br />
<br />
=== Delete NAT/PAT table entry ===<br />
<br />
clear xlate lport 500 type dynamic local 1.2.3.4<br />
<br />
<br />
=== Packet tracer ===<br />
<br />
Test an access list:<br />
<br />
If you are trying to see what traffic would do when hitting an access list, you can use packet tracer. Here is the syntax:<br />
<br />
packet-tracer input <input interface name> <protocol> <source ip> <source port> <destination ip> <destination port><br />
<br />
<pre><br />
# packet-tracer input inside tcp 192.168.68.10 1234 8.8.8.8 80<br />
<br />
Phase: 1<br />
Type: ACCESS-LIST<br />
Subtype:<br />
Result: ALLOW<br />
Config:<br />
Implicit Rule<br />
Additional Information:<br />
MAC Access list<br />
<br />
Phase: 2<br />
Type: ROUTE-LOOKUP<br />
Subtype: Resolve Egress Interface<br />
Result: ALLOW<br />
Config:<br />
Additional Information:<br />
found next-hop 62.x.y.1 using egress ifc outside-telekom<br />
<br />
Phase: 3<br />
Type: ACCESS-LIST<br />
Subtype:<br />
Result: DROP<br />
Config:<br />
Implicit Rule<br />
Additional Information:<br />
<br />
Result:<br />
input-interface: inside<br />
input-status: up<br />
input-line-status: up<br />
output-interface: outside-telekom<br />
output-status: up<br />
output-line-status: up<br />
Action: drop<br />
Drop-reason: (acl-drop) Flow is denied by configured rule<br />
</pre><br />
<br />
<br />
==== accelerated security path filter tables ====<br />
<br />
This shows the detailed compiled filter list for an ACL (in/out)<br />
<br />
show asp table filter [access-list <acl-name>] [hits]<br />
<br />
<pre><br />
out id=0x7f6c84f1ccb0, priority=13, domain=filter-aaa, deny=false<br />
hits=0, user_data=0x7f6c6fcd8840, filter_id=0xf(CARANOACL), protocol=6<br />
src ip=192.168.160.0, mask=255.255.255.0, port=3389<br />
dst ip=10.219.106.60, mask=255.255.255.255, port=0<br />
out id=0x7f6c7df487e0, priority=13, domain=filter-aaa, deny=false<br />
hits=0, user_data=0x7f6c6fcd86c0, filter_id=0xf(CARANOACL), protocol=6<br />
src ip=10.219.106.60, mask=255.255.255.255, port=3389<br />
dst ip=192.168.160.0, mask=255.255.255.0, port=0<br />
</pre><br />
<br />
=== Capture traffic ===<br />
<br />
Create a packet capture<br />
If you want to capture traffic in real time, you can setup a trace on the firewall. Syntax:<br />
<br />
capture <cap> interface <intname> match <protocol> <source> <destination><br />
<br />
To start capture:<br />
<br />
# cap billcap inter outside-telekom match ip any host 8.8.8.8<br />
<br />
To view capture detail: <br />
<br />
show capture <capname><br />
<br />
To restart capture: <br />
<br />
clear capture <capname><br />
<br />
To remove capture: <br />
<br />
no capture <capname><br />
<br />
To view all running captures: <br />
<br />
show capture<br />
<br />
To download capture from firewall: <br />
<br />
https://<FWIP>/admin/capture/<capname>/pcap<br />
<br />
or if http(s) is not accessable<br />
<br />
copy /pcap capture:<capname> disk0:<capname><br />
<br />
from a client you have SSH access to the system do:<br />
<br />
scp user@asa:disk0:<capname> ./<capname><br />
<br />
Dont forget to stop capture and delete the disk0:<capname> file!<br />
<br />
=== Show NAT ===<br />
<br />
will show you the nat rules in the order they are processed:<br />
<br />
show nat <br />
<br />
will give more detail including resolving the objects to IP addresses:<br />
<br />
show nat detail<br />
<br />
<br />
=== Write running config to Flash ===<br />
<br />
write mem<br />
<br />
<br />
== NAT / PAT ==<br />
<br />
yadda <br />
<br />
<br />
=== Types and Rules ===<br />
<br />
# Manual NAT Policies (Section 1)<br />
## These are manual NAT rules (BEFORE AUTO-Rules)<br />
# Auto NAT Policies (Section 2)<br />
## These are NAT rules created automatically by adding NAT to the 'network object' object<br />
# Manual NAT Policies (Section 3)<br />
## These are manual NAT rules (AFTER AUTO-Rules)<br />
<br />
<br />
<br />
=== Create NAT rules ===<br />
<br />
Create a (default) NAT Rule (BEFORE-AUTO)<br />
<br />
nat (guestwlan,dmz) source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
Create a (default) NAT Rule (BEFORE-AUTO) at a specific line number<br />
<br />
nat (guestwlan,dmz) '''9''' source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
Create an AUTO-NAT Rule<br/><br/><br />
<br />
1st of all create the 'network object' object (if not exists)<br />
<br />
network object YOUR_NAME_OF_OBJECT<br />
host 10.11.12.13<br />
exit<br />
<br />
<br />
Now edit the network object again and add the NAT entry directly to the object:<br />
<br />
network object YOUR_NAME_OF_OBJECT<br />
nat (dmz,outside) static 8.8.8.8<br />
exit<br />
<br />
This creates an AUTO-NAT Rule incomming from the 'dmz' interface and outgoing to the 'outside' interface,<br/><br />
which translates the internal IP 10.11.12.13 to the routable IP 8.8.8.8 before leaving the network towards the internat *lol*<br/><br />
Be aware that the network object is listed within the config on 2 seperate places. So if you grep for YOUR_NAME_OF_OBJECT in config you'll get it listed twice!<br/><br/><br />
<br />
<br />
Create a NAT Rule (AFTER-AUTO) (untested!)<br />
<br />
nat (guestwlan,dmz) '''after-auto''' source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
<br />
<br />
== IPSec ==<br />
<br />
yadda yadda<br />
<br />
=== IPSec Tunnel-Template ===<br />
<br />
<pre><br />
route outside-interface-name 192.168.160.0 255.255.255.0 <IP of outside-interface-name><br />
<br />
object network NET_FIRMNAME <br />
subnet 192.168.0.0 255.255.255.0<br />
<br />
object-group network GRP_FIRMNAME_REMOTE_ACCESS<br />
network-object object NET_10.0.0.0_24<br />
network-object object NET_DMZ<br />
network-object object NET_Server<br />
<br />
access-list DC_to_FIRMNAME_ENCDOM extended permit ip object-group GRP_FIRMNAME_REMOTE_ACCESS object NET_FIRMNAME<br />
access-list FIRMANEACL extended permit icmp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 3389<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 22<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 6556<br />
<br />
nat (inside,outside-telekom) source static GRP_FIRMNAME_REMOTE_ACCESS GRP_FIRMNAME_REMOTE_ACCESS destination static NET_FIRMNAME NET_FIRMNAME no-proxy-arp route-lookup<br />
nat (dmz,outside-telekom) source static GRP_FIRMNAME_REMOTE_ACCESS GRP_FIRMNAME_REMOTE_ACCESS destination static NET_FIRMNAME NET_FIRMNAME no-proxy-arp route-lookup<br />
<br />
group-policy FIRMNAMEACCESSPOLICY internal<br />
group-policy FIRMNAMEACCESSPOLICY attributes<br />
vpn-filter value FIRMANEACL<br />
vpn-tunnel-protocol ikev1 ikev2<br />
<br />
tunnel-group 1.2.3.4 type ipsec-l2l<br />
tunnel-group 1.2.3.4 general-attributes<br />
default-group-policy FIRMNAMEACCESSPOLICY<br />
tunnel-group 1.2.3.4 ipsec-attributes<br />
ikev1 pre-shared-key <PSK><br />
ikev2 remote-authentication pre-shared-key <PSK><br />
ikev2 local-authentication pre-shared-key <PSK><br />
<br />
<br />
crypto map outside-telekom_map 40 match address DC_to_FIRMNAME_ENCDOM<br />
crypto map outside-telekom_map 40 set peer 1.2.3.4<br />
crypto map outside-telekom_map 40 set ikev1 transform-set ESP-AES-256-SHA<br />
crypto map outside-telekom_map 40 set ikev2 ipsec-proposal AES256<br />
crypto map outside-telekom_map 40 set pfs group5<br />
crypto map outside-telekom_map 40 set security-association lifetime kilobytes unlimited<br />
</pre><br />
<br />
<br />
Clear tunnel-group completely without previously deconfiguring general- and ipsec-attributes:<br />
<br />
clear configure tunnel-group 1.2.3.4<br />
<br />
=== IPSec debugging ===<br />
<br />
Basic <br/><br />
<br/> <br />
Show established isakmp sa's:<br />
<br />
show crypto isakmp sa<br />
show isakmp sa<br />
<br />
<br />
Show established ipsec sa's:<br />
<br />
show crypto ipsec sa<br />
show ipsec sa<br />
<br />
show ipsec sa peer a.b.c.d<br />
<br />
<br />
Start show/follow logs (Debuglevel = 100):<br />
<br />
debug crypto isakmp 100<br />
<br />
or<br />
<br />
debug crypto ipsec 100<br />
<br />
<br />
And stop logs:<br />
<br />
no debug crypto isakmp<br />
<br />
or<br />
<br />
no debug crypto ipsec<br />
<br />
<br />
==== Tear down tunnel ====<br />
<br />
Find session index:<br />
<br />
<pre><br />
# show vpn-sessiondb l2l<br />
<br />
Session Type: LAN-to-LAN<br />
<br />
Connection : 100.11.12.13<br />
Index : 7186 IP Addr : 100.11.12.13 <-- note index number<br />
Protocol : IKEv1<br />
Encryption : IKEv1: (1)AES256 Hashing : IKEv1: (1)SHA1<br />
Bytes Tx : 0 Bytes Rx : 0<br />
Login Time : 12:35:24 CEST Mon Apr 30 2018<br />
Duration : 1h:39m:56s<br />
</pre><br />
<br />
Kill session:<br />
<br />
(config)# vpn-sessiondb logoff index 7186<br />
<br />
<br />
==== Restart tunnel ====<br />
<br />
clear ipsec sa peer 100.11.12.13<br />
<br />
<br />
== SSL-VPN / Anyconnect ==<br />
<br />
yadda yadda<br />
<br />
<br />
=== SSL-VPN Client info ===<br />
<br />
shows overall stats for current/cumulative/peak connections:<br />
<br />
show vpn-sessiondb<br />
<br />
shows user info:<br />
<br />
show vpn-sessiondb anyconnect<br />
<br />
shows user info on 1 line so it’s useful for searching:<br />
<br />
show vpn-sessiondb full anyconnect<br />
<br />
<br />
== Certificate handling ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Certs ===<br />
<br />
show crypto ca certificate<br />
<br />
<br />
=== Import SSL/TLS Cert and Key ===<br />
<br />
Unfortionally you'll have to use a base64 encoded PKCS12 formatted file:<br/><br />
<br />
Create Base64 encoded file by:<br />
<br />
echo "-----BEGIN PKCS12-----" > cert.pfx.base64; base64 cert.pfx >> cert.pfx.base64; echo "-----END PKCS12-----" >> cert.pfx.base64 <br />
<br />
<pre><br />
crypto ca import trustpoint-remote.domain.tld-2020 pkcs12 <password><br />
<br />
Enter the base 64 encoded pkcs12.<br />
End with the word "quit" on a line by itself:<br />
-----BEGIN PKCS12-----<br />
MIIVmQIBAzCCFV8GCSqGSIb3DQEHAaCCFVAEghVMMIIVSDCCD/8GCSqGSIb3DQEHBqCCD/Awgg/s<br />
AgEAMIIP5QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQI72fdKN6IkNECAggAgIIPuMXN/b7v<br />
<snip><br />
hTI1xlJM6sI+Axo3UwflV10Kc+KsGBfNjnlxQDElMCMGCSqGSIb3DQEJFTEWBBRrAoZRSm257M2O<br />
mu49GEiimnYqAjAxMCEwCQYFKw4DAhoFAAQUOmTsXE2LkxjxBKjPHWA9mizi+XkECGu5W+dQgEbq<br />
AgIIAA==<br />
-----END PKCS12-----<br />
quit<br />
% The CA cert is not self-signed.<br />
<br />
% Do you also want to create trustpoints for CAs higher in<br />
% the hierarchy? [yes/no]: yes<br />
INFO: Import PKCS12 operation completed successfully<br />
</pre><br />
<br />
<br />
Now activate the trustpoint on interface 'outside'<br />
<br />
ssl trust-point trustpoint-remote.domain.tld-2020 outside<br />
<br />
== SSL/TLS cipher handling ==<br />
<br />
yadda<br />
<br />
<br />
=== show ciphers ===<br />
<br />
All:<br />
<br />
# show ssl ciphers all<br />
These are the ciphers for the given cipher level; not all ciphers<br />
are supported by all versions of SSL/TLS.<br />
These names can be used to create a custom cipher list<br />
ECDHE-ECDSA-AES256-GCM-SHA384 (tlsv1.2)<br />
ECDHE-RSA-AES256-GCM-SHA384 (tlsv1.2)<br />
DHE-RSA-AES256-GCM-SHA384 (tlsv1.2)<br />
[...]<br />
<br />
Configured:<br />
<br />
# show running-config ssl<br />
<br />
<br />
=== set ciphers ===<br />
<br />
ssl cipher default custom "AES128-SHA:AES256-SHA"<br />
ssl cipher tlsv1 custom "AES128-SHA:AES256-SHA"<br />
ssl cipher tlsv1.2 custom "AES256-SHA:AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA"<br />
ssl cipher dtlsv1 custom "AES128-SHA:AES256-SHA"</div>
Cbs
https://schnallich.net/index.php?title=SchnallIchNet:Inhalt&diff=1755
SchnallIchNet:Inhalt
2023-01-16T13:13:48Z
<p>Cbs: /* Inhalt */</p>
<hr />
<div>=Inhalt=<br />
* [[Spezial:Alle_Seiten|Alle Seiten anzeigen]]<br />
* [[Spezial:Popularpages|Meist benutzte Seiten]]<br />
<br />
Oder verwendet bitte die 'Such-Funktion'<br/><br />
<!--<br />
...oder ihr verwendet Sub-Domains, z.B.:<br/><br />
# http://vim.schnallich.net/<br />
# http://awk.schnallich.net/<br />
<br/><br />
Verfuegbare Domains dafuer:<br />
# '''schnallich.net'''<br />
# '''netzadmin.de'''<br />
# '''tun.ing''' (openNIC root-servers only)<br />
# '''chris.ing''' (openNIC root-servers only)<br />
# '''chris.geek''' (openNIC root-servers only)<br />
# '''brenda.geek''' (openNIC root-servers only)<br />
--></div>
Cbs
https://schnallich.net/index.php?title=Cisco/CLI&diff=1754
Cisco/CLI
2022-11-09T13:19:29Z
<p>Cbs: /* Capture traffic */</p>
<hr />
<div><br />
== Firmware upgrade ==<br />
<br />
<br />
=== Copy (SCP) firmware to asa ===<br />
<br />
Be sure to explicitly name the file on the target or upload will fail.<br/><br />
ASA will not name the file the same like the sourcefile by its own.<br />
<br />
scp asa<VERSION>-<PATCH>-smp-k8.bin asa.domain.tld:disk0:/asa<VERSION>-<PATCH>-smp-k8.bin<br />
<br />
<br />
<br />
=== Upgrade firmware ===<br />
<br />
Upload new firmware to flash before starting.<br/><br />
<br />
<pre><br />
! Deactivate old boot image<br />
no boot system disk0:/asa963-1-smp-k8.bin<br />
<br />
! Add new image as primary boot with old as backup<br />
boot system disk0:/asa964-3-smp-k8.bin<br />
boot system disk0:/asa963-1-smp-k8.bin<br />
<br />
! Save changes to config<br />
write memory<br />
<br />
! This will cause the standby firewall to reload<br />
failover reload-standby<br />
<br />
! After getting messages that standby has rebooted, verify that failover is ready<br />
show failover<br />
<br />
! This forces active firewall to become standby, and standby to active<br />
no failover active<br />
<br />
! reload new standby firewall after failing over<br />
failover reload-standby<br />
</pre><br />
<br />
== Cheat Sheet ==<br />
<br />
Another thing you can do with the ASDM client is to enable command previews.<br/><br />
This allows you to configure things in the ASDM but before it sends them to the firewall it will show you the CLI that is being used.<br/><br />
This is enabled through the ASDM > Tools > Preferences > Preview commands before sending them to the device<br />
<br />
<br />
=== Show/Enable and Disable Logs in terminal ===<br />
<br />
Enable:<br />
<br />
terminal monitor<br />
<br />
Disable:<br />
<br />
terminal no monitor<br />
<br />
<br />
=== Disable pager ===<br />
<br />
terminal pager 0<br />
<br />
<br />
=== Show NAT/PAT translation table ===<br />
<br />
show xlate<br />
<br />
<br />
=== Show access-group ===<br />
<br />
will show you access lists bound to each interface:<br />
show running-config | include access-group <br />
<br />
<pre><br />
# sh run | incl access-gr<br />
access-group inside_to_outside_dmz in interface inside<br />
access-group stgoffice_to_inside_outside in interface stgoffice<br />
access-group dmz_to_inside_outside in interface dmz<br />
access-group guestwireless_to_inside_outside in interface guestwlan<br />
access-group bmw_to_inside_dmz in interface bmw<br />
access-group allowarius in interface outside-itenos<br />
access-group outside_to_inside_dmz in interface outside-telekom<br />
</pre><br />
<br />
<br />
=== Show access-list ===<br />
<br />
will show you the rules with all groups expanded and resolve names to IPs.<br/><br />
It also shows you the hit count of the rule so you can see if it’s not being used.<br/><br />
Lastly it shows you the access list sequence number if you need to put a rule in the middle of the ruleset:<br />
show access-list <access-list name><br />
<br />
<pre><br />
# sh access-list inside_to_outside_dmz<br />
access-list inside_to_outside_dmz; 381 elements; name hash: 0x9b447bd7<br />
access-list inside_to_outside_dmz line 1 remark Allow access to SHDEAGB<br />
access-list inside_to_outside_dmz line 2 extended permit ip object NET_RZ object SHDEAGB (hitcnt=0) 0xb3e4ce53<br />
access-list inside_to_outside_dmz line 2 extended permit ip 10.3.11.0 255.255.255.0 10.1.1.0 255.255.255.0 (hitcnt=0) 0xb3e4ce53<br />
access-list inside_to_outside_dmz line 3 remark Allow access to VPN clients<br />
access-list inside_to_outside_dmz line 4 extended permit ip object-group NET_RFC1918 object AnyConnect (hitcnt=1519518) 0xbacaa3e8<br />
access-list inside_to_outside_dmz line 4 extended permit ip 10.0.0.0 255.0.0.0 10.219.112.0 255.255.255.0 (hitcnt=1495910) 0x7e937191<br />
access-list inside_to_outside_dmz line 4 extended permit ip 192.168.0.0 255.255.0.0 10.219.112.0 255.255.255.0 (hitcnt=23461) 0x484233c3<br />
access-list inside_to_outside_dmz line 4 extended permit ip 172.16.0.0 255.240.0.0 10.219.112.0 255.255.255.0 (hitcnt=147) 0xda51da6b<br />
access-list inside_to_outside_dmz line 5 extended permit ip object-group NET_RFC1918 object NET_Stuttgart_Office (hitcnt=7856134) 0xcec84ac2<br />
access-list inside_to_outside_dmz line 5 extended permit ip 10.0.0.0 255.0.0.0 10.3.14.0 255.255.254.0 (hitcnt=7492424) 0x6f88731b<br />
access-list inside_to_outside_dmz line 5 extended permit ip 192.168.0.0 255.255.0.0 10.3.14.0 255.255.254.0 (hitcnt=363163) 0x6ba488f1<br />
access-list inside_to_outside_dmz line 5 extended permit ip 172.16.0.0 255.240.0.0 10.3.14.0 255.255.254.0 (hitcnt=547) 0x71ac3184<br />
</pre><br />
<br />
<br />
Show access-list beginning at a specific line:<br />
<br />
sh access-list dmz_to_inside_outside | beg line 71<br />
<br />
<br />
=== Show object (oneline) ===<br />
<br />
See objects on one line:<br />
show running-config object in-line<br />
<br />
<pre><br />
# show running-config object in-line | incl 11.89<br />
object network ADDR_STGMON001 host 192.168.11.89<br />
</pre><br />
<br />
<br />
=== Show object-group by name ===<br />
<br />
sh run object-group id <GRP_Name><br />
<br />
<br />
=== Show running config beginning from pattern ===<br />
<br />
# more system:running-config | beg tunnel-group 100.11.12.13<br />
<br />
=== Delete NAT/PAT table entry ===<br />
<br />
clear xlate lport 500 type dynamic local 1.2.3.4<br />
<br />
<br />
=== Packet tracer ===<br />
<br />
Test an access list:<br />
<br />
If you are trying to see what traffic would do when hitting an access list, you can use packet tracer. Here is the syntax:<br />
<br />
packet-tracer input <input interface name> <protocol> <source ip> <source port> <destination ip> <destination port><br />
<br />
<pre><br />
# packet-tracer input inside tcp 192.168.68.10 1234 8.8.8.8 80<br />
<br />
Phase: 1<br />
Type: ACCESS-LIST<br />
Subtype:<br />
Result: ALLOW<br />
Config:<br />
Implicit Rule<br />
Additional Information:<br />
MAC Access list<br />
<br />
Phase: 2<br />
Type: ROUTE-LOOKUP<br />
Subtype: Resolve Egress Interface<br />
Result: ALLOW<br />
Config:<br />
Additional Information:<br />
found next-hop 62.x.y.1 using egress ifc outside-telekom<br />
<br />
Phase: 3<br />
Type: ACCESS-LIST<br />
Subtype:<br />
Result: DROP<br />
Config:<br />
Implicit Rule<br />
Additional Information:<br />
<br />
Result:<br />
input-interface: inside<br />
input-status: up<br />
input-line-status: up<br />
output-interface: outside-telekom<br />
output-status: up<br />
output-line-status: up<br />
Action: drop<br />
Drop-reason: (acl-drop) Flow is denied by configured rule<br />
</pre><br />
<br />
<br />
==== accelerated security path filter tables ====<br />
<br />
This shows the detailed compiled filter list for an ACL (in/out)<br />
<br />
show asp table filter [access-list <acl-name>] [hits]<br />
<br />
<pre><br />
out id=0x7f6c84f1ccb0, priority=13, domain=filter-aaa, deny=false<br />
hits=0, user_data=0x7f6c6fcd8840, filter_id=0xf(CARANOACL), protocol=6<br />
src ip=192.168.160.0, mask=255.255.255.0, port=3389<br />
dst ip=10.219.106.60, mask=255.255.255.255, port=0<br />
out id=0x7f6c7df487e0, priority=13, domain=filter-aaa, deny=false<br />
hits=0, user_data=0x7f6c6fcd86c0, filter_id=0xf(CARANOACL), protocol=6<br />
src ip=10.219.106.60, mask=255.255.255.255, port=3389<br />
dst ip=192.168.160.0, mask=255.255.255.0, port=0<br />
</pre><br />
<br />
=== Capture traffic ===<br />
<br />
Create a packet capture<br />
If you want to capture traffic in real time, you can setup a trace on the firewall. Syntax:<br />
<br />
capture <cap> interface <intname> match <protocol> <source> <destination><br />
<br />
To start capture:<br />
<br />
# cap billcap inter outside-telekom match ip any host 8.8.8.8<br />
<br />
To view capture detail: <br />
<br />
show capture <capname><br />
<br />
To restart capture: <br />
<br />
clear capture <capname><br />
<br />
To remove capture: <br />
<br />
no capture <capname><br />
<br />
To view all running captures: <br />
<br />
show capture<br />
<br />
To download capture from firewall: <br />
<br />
https://<FWIP>/admin/capture/<capname>/pcap<br />
<br />
or if http(s) is not accessable<br />
<br />
copy /pcap capture:<capname> disk0:<capname><br />
<br />
from a client you have SSH access to the system do:<br />
<br />
scp user@asa:disk0:<capname> ./<capname><br />
<br />
Dont forget to stop capture and delete the disk0:<capname> file!<br />
<br />
=== Show NAT ===<br />
<br />
will show you the nat rules in the order they are processed:<br />
<br />
show nat <br />
<br />
will give more detail including resolving the objects to IP addresses:<br />
<br />
show nat detail<br />
<br />
<br />
=== Write running config to Flash ===<br />
<br />
write mem<br />
<br />
<br />
== NAT / PAT ==<br />
<br />
yadda <br />
<br />
<br />
=== Types and Rules ===<br />
<br />
# Manual NAT Policies (Section 1)<br />
## These are manual NAT rules (BEFORE AUTO-Rules)<br />
# Auto NAT Policies (Section 2)<br />
## These are NAT rules created automatically by adding NAT to the 'network object' object<br />
# Manual NAT Policies (Section 3)<br />
## These are manual NAT rules (AFTER AUTO-Rules)<br />
<br />
<br />
<br />
=== Create NAT rules ===<br />
<br />
Create a (default) NAT Rule (BEFORE-AUTO)<br />
<br />
nat (guestwlan,dmz) source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
Create a (default) NAT Rule (BEFORE-AUTO) at a specific line number<br />
<br />
nat (guestwlan,dmz) '''9''' source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
Create an AUTO-NAT Rule<br/><br/><br />
<br />
1st of all create the 'network object' object (if not exists)<br />
<br />
network object YOUR_NAME_OF_OBJECT<br />
host 10.11.12.13<br />
exit<br />
<br />
<br />
Now edit the network object again and add the NAT entry directly to the object:<br />
<br />
network object YOUR_NAME_OF_OBJECT<br />
nat (dmz,outside) static 8.8.8.8<br />
exit<br />
<br />
This creates an AUTO-NAT Rule incomming from the 'dmz' interface and outgoing to the 'outside' interface,<br/><br />
which translates the internal IP 10.11.12.13 to the routable IP 8.8.8.8 before leaving the network towards the internat *lol*<br/><br />
Be aware that the network object is listed within the config on 2 seperate places. So if you grep for YOUR_NAME_OF_OBJECT in config you'll get it listed twice!<br/><br/><br />
<br />
<br />
Create a NAT Rule (AFTER-AUTO) (untested!)<br />
<br />
nat (guestwlan,dmz) '''after-auto''' source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
<br />
<br />
== IPSec ==<br />
<br />
yadda yadda<br />
<br />
=== IPSec Tunnel-Template ===<br />
<br />
<pre><br />
route outside-interface-name 192.168.160.0 255.255.255.0 <IP of outside-interface-name><br />
<br />
object network NET_FIRMNAME <br />
subnet 192.168.0.0 255.255.255.0<br />
<br />
object-group network GRP_FIRMNAME_REMOTE_ACCESS<br />
network-object object NET_10.0.0.0_24<br />
network-object object NET_DMZ<br />
network-object object NET_Server<br />
<br />
access-list DC_to_FIRMNAME_ENCDOM extended permit ip object-group GRP_FIRMNAME_REMOTE_ACCESS object NET_FIRMNAME<br />
access-list FIRMANEACL extended permit icmp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 3389<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 22<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 6556<br />
<br />
nat (inside,outside-telekom) source static GRP_FIRMNAME_REMOTE_ACCESS GRP_FIRMNAME_REMOTE_ACCESS destination static NET_FIRMNAME NET_FIRMNAME no-proxy-arp route-lookup<br />
nat (dmz,outside-telekom) source static GRP_FIRMNAME_REMOTE_ACCESS GRP_FIRMNAME_REMOTE_ACCESS destination static NET_FIRMNAME NET_FIRMNAME no-proxy-arp route-lookup<br />
<br />
group-policy FIRMNAMEACCESSPOLICY internal<br />
group-policy FIRMNAMEACCESSPOLICY attributes<br />
vpn-filter value FIRMANEACL<br />
vpn-tunnel-protocol ikev1 ikev2<br />
<br />
tunnel-group 1.2.3.4 type ipsec-l2l<br />
tunnel-group 1.2.3.4 general-attributes<br />
default-group-policy FIRMNAMEACCESSPOLICY<br />
tunnel-group 1.2.3.4 ipsec-attributes<br />
ikev1 pre-shared-key <PSK><br />
ikev2 remote-authentication pre-shared-key <PSK><br />
ikev2 local-authentication pre-shared-key <PSK><br />
<br />
<br />
crypto map outside-telekom_map 40 match address DC_to_FIRMNAME_ENCDOM<br />
crypto map outside-telekom_map 40 set peer 1.2.3.4<br />
crypto map outside-telekom_map 40 set ikev1 transform-set ESP-AES-256-SHA<br />
crypto map outside-telekom_map 40 set ikev2 ipsec-proposal AES256<br />
crypto map outside-telekom_map 40 set pfs group5<br />
crypto map outside-telekom_map 40 set security-association lifetime kilobytes unlimited<br />
</pre><br />
<br />
<br />
Clear tunnel-group completely without previously deconfiguring general- and ipsec-attributes:<br />
<br />
clear configure tunnel-group 1.2.3.4<br />
<br />
=== IPSec debugging ===<br />
<br />
Basic <br/><br />
<br/> <br />
Show established isakmp sa's:<br />
<br />
show crypto isakmp sa<br />
show isakmp sa<br />
<br />
<br />
Show established ipsec sa's:<br />
<br />
show crypto ipsec sa<br />
show ipsec sa<br />
<br />
show ipsec sa peer a.b.c.d<br />
<br />
<br />
Start show/follow logs (Debuglevel = 100):<br />
<br />
debug crypto isakmp 100<br />
<br />
or<br />
<br />
debug crypto ipsec 100<br />
<br />
<br />
And stop logs:<br />
<br />
no debug crypto isakmp<br />
<br />
or<br />
<br />
no debug crypto ipsec<br />
<br />
<br />
==== Tear down tunnel ====<br />
<br />
Find session index:<br />
<br />
<pre><br />
# show vpn-sessiondb l2l<br />
<br />
Session Type: LAN-to-LAN<br />
<br />
Connection : 100.11.12.13<br />
Index : 7186 IP Addr : 100.11.12.13 <-- note index number<br />
Protocol : IKEv1<br />
Encryption : IKEv1: (1)AES256 Hashing : IKEv1: (1)SHA1<br />
Bytes Tx : 0 Bytes Rx : 0<br />
Login Time : 12:35:24 CEST Mon Apr 30 2018<br />
Duration : 1h:39m:56s<br />
</pre><br />
<br />
Kill session:<br />
<br />
(config)# vpn-sessiondb logoff index 7186<br />
<br />
<br />
==== Restart tunnel ====<br />
<br />
clear ipsec sa peer 100.11.12.13<br />
<br />
<br />
== SSL-VPN / Anyconnect ==<br />
<br />
yadda yadda<br />
<br />
<br />
=== SSL-VPN Client info ===<br />
<br />
shows overall stats for current/cumulative/peak connections:<br />
<br />
show vpn-sessiondb<br />
<br />
shows user info:<br />
<br />
show vpn-sessiondb anyconnect<br />
<br />
shows user info on 1 line so it’s useful for searching:<br />
<br />
show vpn-sessiondb full anyconnect<br />
<br />
<br />
== Certificate handling ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Certs ===<br />
<br />
show crypto ca certificate<br />
<br />
<br />
=== Import SSL/TLS Cert and Key ===<br />
<br />
Unfortionally you'll have to use a base64 encoded PKCS12 formatted file:<br />
<br />
<pre><br />
crypto ca import trustpoint-remote.domain.tld-2020 pkcs12 <password><br />
<br />
Enter the base 64 encoded pkcs12.<br />
End with the word "quit" on a line by itself:<br />
-----BEGIN PKCS12-----<br />
MIIVmQIBAzCCFV8GCSqGSIb3DQEHAaCCFVAEghVMMIIVSDCCD/8GCSqGSIb3DQEHBqCCD/Awgg/s<br />
AgEAMIIP5QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQI72fdKN6IkNECAggAgIIPuMXN/b7v<br />
<snip><br />
hTI1xlJM6sI+Axo3UwflV10Kc+KsGBfNjnlxQDElMCMGCSqGSIb3DQEJFTEWBBRrAoZRSm257M2O<br />
mu49GEiimnYqAjAxMCEwCQYFKw4DAhoFAAQUOmTsXE2LkxjxBKjPHWA9mizi+XkECGu5W+dQgEbq<br />
AgIIAA==<br />
-----END PKCS12-----<br />
quit<br />
% The CA cert is not self-signed.<br />
<br />
% Do you also want to create trustpoints for CAs higher in<br />
% the hierarchy? [yes/no]: yes<br />
INFO: Import PKCS12 operation completed successfully<br />
</pre><br />
<br />
<br />
Now activate the trustpoint on interface 'outside'<br />
<br />
ssl trust-point trustpoint-remote.domain.tld-2020 outside<br />
<br />
<br />
== SSL/TLS cipher handling ==<br />
<br />
yadda<br />
<br />
<br />
=== show ciphers ===<br />
<br />
All:<br />
<br />
# show ssl ciphers all<br />
These are the ciphers for the given cipher level; not all ciphers<br />
are supported by all versions of SSL/TLS.<br />
These names can be used to create a custom cipher list<br />
ECDHE-ECDSA-AES256-GCM-SHA384 (tlsv1.2)<br />
ECDHE-RSA-AES256-GCM-SHA384 (tlsv1.2)<br />
DHE-RSA-AES256-GCM-SHA384 (tlsv1.2)<br />
[...]<br />
<br />
Configured:<br />
<br />
# show running-config ssl<br />
<br />
<br />
=== set ciphers ===<br />
<br />
ssl cipher default custom "AES128-SHA:AES256-SHA"<br />
ssl cipher tlsv1 custom "AES128-SHA:AES256-SHA"<br />
ssl cipher tlsv1.2 custom "AES256-SHA:AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA"<br />
ssl cipher dtlsv1 custom "AES128-SHA:AES256-SHA"</div>
Cbs
https://schnallich.net/index.php?title=Cisco/CLI&diff=1753
Cisco/CLI
2022-11-09T13:17:55Z
<p>Cbs: /* Capture traffic */</p>
<hr />
<div><br />
== Firmware upgrade ==<br />
<br />
<br />
=== Copy (SCP) firmware to asa ===<br />
<br />
Be sure to explicitly name the file on the target or upload will fail.<br/><br />
ASA will not name the file the same like the sourcefile by its own.<br />
<br />
scp asa<VERSION>-<PATCH>-smp-k8.bin asa.domain.tld:disk0:/asa<VERSION>-<PATCH>-smp-k8.bin<br />
<br />
<br />
<br />
=== Upgrade firmware ===<br />
<br />
Upload new firmware to flash before starting.<br/><br />
<br />
<pre><br />
! Deactivate old boot image<br />
no boot system disk0:/asa963-1-smp-k8.bin<br />
<br />
! Add new image as primary boot with old as backup<br />
boot system disk0:/asa964-3-smp-k8.bin<br />
boot system disk0:/asa963-1-smp-k8.bin<br />
<br />
! Save changes to config<br />
write memory<br />
<br />
! This will cause the standby firewall to reload<br />
failover reload-standby<br />
<br />
! After getting messages that standby has rebooted, verify that failover is ready<br />
show failover<br />
<br />
! This forces active firewall to become standby, and standby to active<br />
no failover active<br />
<br />
! reload new standby firewall after failing over<br />
failover reload-standby<br />
</pre><br />
<br />
== Cheat Sheet ==<br />
<br />
Another thing you can do with the ASDM client is to enable command previews.<br/><br />
This allows you to configure things in the ASDM but before it sends them to the firewall it will show you the CLI that is being used.<br/><br />
This is enabled through the ASDM > Tools > Preferences > Preview commands before sending them to the device<br />
<br />
<br />
=== Show/Enable and Disable Logs in terminal ===<br />
<br />
Enable:<br />
<br />
terminal monitor<br />
<br />
Disable:<br />
<br />
terminal no monitor<br />
<br />
<br />
=== Disable pager ===<br />
<br />
terminal pager 0<br />
<br />
<br />
=== Show NAT/PAT translation table ===<br />
<br />
show xlate<br />
<br />
<br />
=== Show access-group ===<br />
<br />
will show you access lists bound to each interface:<br />
show running-config | include access-group <br />
<br />
<pre><br />
# sh run | incl access-gr<br />
access-group inside_to_outside_dmz in interface inside<br />
access-group stgoffice_to_inside_outside in interface stgoffice<br />
access-group dmz_to_inside_outside in interface dmz<br />
access-group guestwireless_to_inside_outside in interface guestwlan<br />
access-group bmw_to_inside_dmz in interface bmw<br />
access-group allowarius in interface outside-itenos<br />
access-group outside_to_inside_dmz in interface outside-telekom<br />
</pre><br />
<br />
<br />
=== Show access-list ===<br />
<br />
will show you the rules with all groups expanded and resolve names to IPs.<br/><br />
It also shows you the hit count of the rule so you can see if it’s not being used.<br/><br />
Lastly it shows you the access list sequence number if you need to put a rule in the middle of the ruleset:<br />
show access-list <access-list name><br />
<br />
<pre><br />
# sh access-list inside_to_outside_dmz<br />
access-list inside_to_outside_dmz; 381 elements; name hash: 0x9b447bd7<br />
access-list inside_to_outside_dmz line 1 remark Allow access to SHDEAGB<br />
access-list inside_to_outside_dmz line 2 extended permit ip object NET_RZ object SHDEAGB (hitcnt=0) 0xb3e4ce53<br />
access-list inside_to_outside_dmz line 2 extended permit ip 10.3.11.0 255.255.255.0 10.1.1.0 255.255.255.0 (hitcnt=0) 0xb3e4ce53<br />
access-list inside_to_outside_dmz line 3 remark Allow access to VPN clients<br />
access-list inside_to_outside_dmz line 4 extended permit ip object-group NET_RFC1918 object AnyConnect (hitcnt=1519518) 0xbacaa3e8<br />
access-list inside_to_outside_dmz line 4 extended permit ip 10.0.0.0 255.0.0.0 10.219.112.0 255.255.255.0 (hitcnt=1495910) 0x7e937191<br />
access-list inside_to_outside_dmz line 4 extended permit ip 192.168.0.0 255.255.0.0 10.219.112.0 255.255.255.0 (hitcnt=23461) 0x484233c3<br />
access-list inside_to_outside_dmz line 4 extended permit ip 172.16.0.0 255.240.0.0 10.219.112.0 255.255.255.0 (hitcnt=147) 0xda51da6b<br />
access-list inside_to_outside_dmz line 5 extended permit ip object-group NET_RFC1918 object NET_Stuttgart_Office (hitcnt=7856134) 0xcec84ac2<br />
access-list inside_to_outside_dmz line 5 extended permit ip 10.0.0.0 255.0.0.0 10.3.14.0 255.255.254.0 (hitcnt=7492424) 0x6f88731b<br />
access-list inside_to_outside_dmz line 5 extended permit ip 192.168.0.0 255.255.0.0 10.3.14.0 255.255.254.0 (hitcnt=363163) 0x6ba488f1<br />
access-list inside_to_outside_dmz line 5 extended permit ip 172.16.0.0 255.240.0.0 10.3.14.0 255.255.254.0 (hitcnt=547) 0x71ac3184<br />
</pre><br />
<br />
<br />
Show access-list beginning at a specific line:<br />
<br />
sh access-list dmz_to_inside_outside | beg line 71<br />
<br />
<br />
=== Show object (oneline) ===<br />
<br />
See objects on one line:<br />
show running-config object in-line<br />
<br />
<pre><br />
# show running-config object in-line | incl 11.89<br />
object network ADDR_STGMON001 host 192.168.11.89<br />
</pre><br />
<br />
<br />
=== Show object-group by name ===<br />
<br />
sh run object-group id <GRP_Name><br />
<br />
<br />
=== Show running config beginning from pattern ===<br />
<br />
# more system:running-config | beg tunnel-group 100.11.12.13<br />
<br />
=== Delete NAT/PAT table entry ===<br />
<br />
clear xlate lport 500 type dynamic local 1.2.3.4<br />
<br />
<br />
=== Packet tracer ===<br />
<br />
Test an access list:<br />
<br />
If you are trying to see what traffic would do when hitting an access list, you can use packet tracer. Here is the syntax:<br />
<br />
packet-tracer input <input interface name> <protocol> <source ip> <source port> <destination ip> <destination port><br />
<br />
<pre><br />
# packet-tracer input inside tcp 192.168.68.10 1234 8.8.8.8 80<br />
<br />
Phase: 1<br />
Type: ACCESS-LIST<br />
Subtype:<br />
Result: ALLOW<br />
Config:<br />
Implicit Rule<br />
Additional Information:<br />
MAC Access list<br />
<br />
Phase: 2<br />
Type: ROUTE-LOOKUP<br />
Subtype: Resolve Egress Interface<br />
Result: ALLOW<br />
Config:<br />
Additional Information:<br />
found next-hop 62.x.y.1 using egress ifc outside-telekom<br />
<br />
Phase: 3<br />
Type: ACCESS-LIST<br />
Subtype:<br />
Result: DROP<br />
Config:<br />
Implicit Rule<br />
Additional Information:<br />
<br />
Result:<br />
input-interface: inside<br />
input-status: up<br />
input-line-status: up<br />
output-interface: outside-telekom<br />
output-status: up<br />
output-line-status: up<br />
Action: drop<br />
Drop-reason: (acl-drop) Flow is denied by configured rule<br />
</pre><br />
<br />
<br />
==== accelerated security path filter tables ====<br />
<br />
This shows the detailed compiled filter list for an ACL (in/out)<br />
<br />
show asp table filter [access-list <acl-name>] [hits]<br />
<br />
<pre><br />
out id=0x7f6c84f1ccb0, priority=13, domain=filter-aaa, deny=false<br />
hits=0, user_data=0x7f6c6fcd8840, filter_id=0xf(CARANOACL), protocol=6<br />
src ip=192.168.160.0, mask=255.255.255.0, port=3389<br />
dst ip=10.219.106.60, mask=255.255.255.255, port=0<br />
out id=0x7f6c7df487e0, priority=13, domain=filter-aaa, deny=false<br />
hits=0, user_data=0x7f6c6fcd86c0, filter_id=0xf(CARANOACL), protocol=6<br />
src ip=10.219.106.60, mask=255.255.255.255, port=3389<br />
dst ip=192.168.160.0, mask=255.255.255.0, port=0<br />
</pre><br />
<br />
=== Capture traffic ===<br />
<br />
Create a packet capture<br />
If you want to capture traffic in real time, you can setup a trace on the firewall. Syntax:<br />
<br />
capture <cap> interface <intname> match <protocol> <source> <destination><br />
<br />
To start capture:<br />
<br />
# cap billcap inter outside-telekom match ip any host 8.8.8.8<br />
<br />
To view capture detail: <br />
<br />
show capture <capname><br />
<br />
To restart capture: <br />
<br />
clear capture <capname><br />
<br />
To remove capture: <br />
<br />
no capture <capname><br />
<br />
To view all running captures: <br />
<br />
show capture<br />
<br />
To download capture from firewall: <br />
<br />
https://<FWIP>/admin/capture/<capname>/pcap<br />
<br />
or if http(s) is not accessable<br />
<br />
copy /pcap capture:<capname> disk0:<capname><br />
<br />
from a client you have SSH access to the system do:<br />
<br />
scp user@asa:disk0:<capname> .//admin/capture<br />
<br />
=== Show NAT ===<br />
<br />
will show you the nat rules in the order they are processed:<br />
<br />
show nat <br />
<br />
will give more detail including resolving the objects to IP addresses:<br />
<br />
show nat detail<br />
<br />
<br />
=== Write running config to Flash ===<br />
<br />
write mem<br />
<br />
<br />
== NAT / PAT ==<br />
<br />
yadda <br />
<br />
<br />
=== Types and Rules ===<br />
<br />
# Manual NAT Policies (Section 1)<br />
## These are manual NAT rules (BEFORE AUTO-Rules)<br />
# Auto NAT Policies (Section 2)<br />
## These are NAT rules created automatically by adding NAT to the 'network object' object<br />
# Manual NAT Policies (Section 3)<br />
## These are manual NAT rules (AFTER AUTO-Rules)<br />
<br />
<br />
<br />
=== Create NAT rules ===<br />
<br />
Create a (default) NAT Rule (BEFORE-AUTO)<br />
<br />
nat (guestwlan,dmz) source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
Create a (default) NAT Rule (BEFORE-AUTO) at a specific line number<br />
<br />
nat (guestwlan,dmz) '''9''' source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
Create an AUTO-NAT Rule<br/><br/><br />
<br />
1st of all create the 'network object' object (if not exists)<br />
<br />
network object YOUR_NAME_OF_OBJECT<br />
host 10.11.12.13<br />
exit<br />
<br />
<br />
Now edit the network object again and add the NAT entry directly to the object:<br />
<br />
network object YOUR_NAME_OF_OBJECT<br />
nat (dmz,outside) static 8.8.8.8<br />
exit<br />
<br />
This creates an AUTO-NAT Rule incomming from the 'dmz' interface and outgoing to the 'outside' interface,<br/><br />
which translates the internal IP 10.11.12.13 to the routable IP 8.8.8.8 before leaving the network towards the internat *lol*<br/><br />
Be aware that the network object is listed within the config on 2 seperate places. So if you grep for YOUR_NAME_OF_OBJECT in config you'll get it listed twice!<br/><br/><br />
<br />
<br />
Create a NAT Rule (AFTER-AUTO) (untested!)<br />
<br />
nat (guestwlan,dmz) '''after-auto''' source static NET_GUESTWIRELESS NET_GUESTWIRELESS destination static ADDR_STGKEMPHADMZ_85_EXT ADDR_STGKEMPHADMZ_85 no-proxy-arp<br />
<br />
<br />
<br />
<br />
== IPSec ==<br />
<br />
yadda yadda<br />
<br />
=== IPSec Tunnel-Template ===<br />
<br />
<pre><br />
route outside-interface-name 192.168.160.0 255.255.255.0 <IP of outside-interface-name><br />
<br />
object network NET_FIRMNAME <br />
subnet 192.168.0.0 255.255.255.0<br />
<br />
object-group network GRP_FIRMNAME_REMOTE_ACCESS<br />
network-object object NET_10.0.0.0_24<br />
network-object object NET_DMZ<br />
network-object object NET_Server<br />
<br />
access-list DC_to_FIRMNAME_ENCDOM extended permit ip object-group GRP_FIRMNAME_REMOTE_ACCESS object NET_FIRMNAME<br />
access-list FIRMANEACL extended permit icmp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 3389<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 22<br />
access-list FIRMANEACL extended permit tcp object NET_FIRMNAME object-group GRP_FIRMNAME_REMOTE_ACCESS EQ 6556<br />
<br />
nat (inside,outside-telekom) source static GRP_FIRMNAME_REMOTE_ACCESS GRP_FIRMNAME_REMOTE_ACCESS destination static NET_FIRMNAME NET_FIRMNAME no-proxy-arp route-lookup<br />
nat (dmz,outside-telekom) source static GRP_FIRMNAME_REMOTE_ACCESS GRP_FIRMNAME_REMOTE_ACCESS destination static NET_FIRMNAME NET_FIRMNAME no-proxy-arp route-lookup<br />
<br />
group-policy FIRMNAMEACCESSPOLICY internal<br />
group-policy FIRMNAMEACCESSPOLICY attributes<br />
vpn-filter value FIRMANEACL<br />
vpn-tunnel-protocol ikev1 ikev2<br />
<br />
tunnel-group 1.2.3.4 type ipsec-l2l<br />
tunnel-group 1.2.3.4 general-attributes<br />
default-group-policy FIRMNAMEACCESSPOLICY<br />
tunnel-group 1.2.3.4 ipsec-attributes<br />
ikev1 pre-shared-key <PSK><br />
ikev2 remote-authentication pre-shared-key <PSK><br />
ikev2 local-authentication pre-shared-key <PSK><br />
<br />
<br />
crypto map outside-telekom_map 40 match address DC_to_FIRMNAME_ENCDOM<br />
crypto map outside-telekom_map 40 set peer 1.2.3.4<br />
crypto map outside-telekom_map 40 set ikev1 transform-set ESP-AES-256-SHA<br />
crypto map outside-telekom_map 40 set ikev2 ipsec-proposal AES256<br />
crypto map outside-telekom_map 40 set pfs group5<br />
crypto map outside-telekom_map 40 set security-association lifetime kilobytes unlimited<br />
</pre><br />
<br />
<br />
Clear tunnel-group completely without previously deconfiguring general- and ipsec-attributes:<br />
<br />
clear configure tunnel-group 1.2.3.4<br />
<br />
=== IPSec debugging ===<br />
<br />
Basic <br/><br />
<br/> <br />
Show established isakmp sa's:<br />
<br />
show crypto isakmp sa<br />
show isakmp sa<br />
<br />
<br />
Show established ipsec sa's:<br />
<br />
show crypto ipsec sa<br />
show ipsec sa<br />
<br />
show ipsec sa peer a.b.c.d<br />
<br />
<br />
Start show/follow logs (Debuglevel = 100):<br />
<br />
debug crypto isakmp 100<br />
<br />
or<br />
<br />
debug crypto ipsec 100<br />
<br />
<br />
And stop logs:<br />
<br />
no debug crypto isakmp<br />
<br />
or<br />
<br />
no debug crypto ipsec<br />
<br />
<br />
==== Tear down tunnel ====<br />
<br />
Find session index:<br />
<br />
<pre><br />
# show vpn-sessiondb l2l<br />
<br />
Session Type: LAN-to-LAN<br />
<br />
Connection : 100.11.12.13<br />
Index : 7186 IP Addr : 100.11.12.13 <-- note index number<br />
Protocol : IKEv1<br />
Encryption : IKEv1: (1)AES256 Hashing : IKEv1: (1)SHA1<br />
Bytes Tx : 0 Bytes Rx : 0<br />
Login Time : 12:35:24 CEST Mon Apr 30 2018<br />
Duration : 1h:39m:56s<br />
</pre><br />
<br />
Kill session:<br />
<br />
(config)# vpn-sessiondb logoff index 7186<br />
<br />
<br />
==== Restart tunnel ====<br />
<br />
clear ipsec sa peer 100.11.12.13<br />
<br />
<br />
== SSL-VPN / Anyconnect ==<br />
<br />
yadda yadda<br />
<br />
<br />
=== SSL-VPN Client info ===<br />
<br />
shows overall stats for current/cumulative/peak connections:<br />
<br />
show vpn-sessiondb<br />
<br />
shows user info:<br />
<br />
show vpn-sessiondb anyconnect<br />
<br />
shows user info on 1 line so it’s useful for searching:<br />
<br />
show vpn-sessiondb full anyconnect<br />
<br />
<br />
== Certificate handling ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Certs ===<br />
<br />
show crypto ca certificate<br />
<br />
<br />
=== Import SSL/TLS Cert and Key ===<br />
<br />
Unfortionally you'll have to use a base64 encoded PKCS12 formatted file:<br />
<br />
<pre><br />
crypto ca import trustpoint-remote.domain.tld-2020 pkcs12 <password><br />
<br />
Enter the base 64 encoded pkcs12.<br />
End with the word "quit" on a line by itself:<br />
-----BEGIN PKCS12-----<br />
MIIVmQIBAzCCFV8GCSqGSIb3DQEHAaCCFVAEghVMMIIVSDCCD/8GCSqGSIb3DQEHBqCCD/Awgg/s<br />
AgEAMIIP5QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQI72fdKN6IkNECAggAgIIPuMXN/b7v<br />
<snip><br />
hTI1xlJM6sI+Axo3UwflV10Kc+KsGBfNjnlxQDElMCMGCSqGSIb3DQEJFTEWBBRrAoZRSm257M2O<br />
mu49GEiimnYqAjAxMCEwCQYFKw4DAhoFAAQUOmTsXE2LkxjxBKjPHWA9mizi+XkECGu5W+dQgEbq<br />
AgIIAA==<br />
-----END PKCS12-----<br />
quit<br />
% The CA cert is not self-signed.<br />
<br />
% Do you also want to create trustpoints for CAs higher in<br />
% the hierarchy? [yes/no]: yes<br />
INFO: Import PKCS12 operation completed successfully<br />
</pre><br />
<br />
<br />
Now activate the trustpoint on interface 'outside'<br />
<br />
ssl trust-point trustpoint-remote.domain.tld-2020 outside<br />
<br />
<br />
== SSL/TLS cipher handling ==<br />
<br />
yadda<br />
<br />
<br />
=== show ciphers ===<br />
<br />
All:<br />
<br />
# show ssl ciphers all<br />
These are the ciphers for the given cipher level; not all ciphers<br />
are supported by all versions of SSL/TLS.<br />
These names can be used to create a custom cipher list<br />
ECDHE-ECDSA-AES256-GCM-SHA384 (tlsv1.2)<br />
ECDHE-RSA-AES256-GCM-SHA384 (tlsv1.2)<br />
DHE-RSA-AES256-GCM-SHA384 (tlsv1.2)<br />
[...]<br />
<br />
Configured:<br />
<br />
# show running-config ssl<br />
<br />
<br />
=== set ciphers ===<br />
<br />
ssl cipher default custom "AES128-SHA:AES256-SHA"<br />
ssl cipher tlsv1 custom "AES128-SHA:AES256-SHA"<br />
ssl cipher tlsv1.2 custom "AES256-SHA:AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA"<br />
ssl cipher dtlsv1 custom "AES128-SHA:AES256-SHA"</div>
Cbs
https://schnallich.net/index.php?title=OpenSSL&diff=1752
OpenSSL
2022-09-08T10:22:31Z
<p>Cbs: /* PKCS12/PFX conversion */</p>
<hr />
<div>==Optionale Parameter fuer die folgenden commandos==<br />
<br />
-config /path/to/own/my_openssl.cnf<br />
separate config-datei verwenden.<br />
<br />
-nodes<br />
verhindert das verschluesseln des key mit einem Passwort.<br/><br />
Die ist wichtig bei key's fuer serverdienste. oder das passwort<br/><br />
muss beim neustart des dienstes eingegeben werden.<br />
<br />
<br />
==Request (CSR) erstellen==<br />
<br />
openssl req -newkey rsa:2048 -out request.pem -keyout pub-sec-key.pem<br />
Generiert einen neuen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Passend dazu wird ein Request in der Datei request.pem erstellt.<br />
<br />
openssl req -new -out request.pem -key pub-sec-key.pem<br />
Wie zuvor, nur wird der Request zum bereits vorhandenen Schlüssel pub-sec-key.pem generiert.<br />
<br />
openssl req -text -noout -in request.pem<br />
Zeigt den Request request.pem an.<br />
<br />
openssl req -verify -noout -in request.pem<br />
Verifiziert die Selbstsignatur des Requests request.pem.<br />
<br />
openssl req -noout -modulus -in request.pem | openssl sha1 -c<br />
Generiert einen SHA1-Fingerabdruck vom Modulus des Schlüssels aus dem Request request.pem.<br />
<br />
openssl x509 -x509toreq -in self-signed-certificate.pem -signkey pub-sec-key.pem -out request.pem<br />
Erstellt neuen Request aus altem Selbstzertifikat.<br />
<br />
<br />
==Request (CSR) mit CA signieren==<br />
<br />
openssl ca -out certs/openVPN_Vorname.Nachname.crt -in openVPN_Vorname.Nachname.csr<br />
<br />
<br />
==Certificate (CRT) erstellen==<br />
<br />
openssl req -x509 -days 365 -newkey rsa:2048 \<br />
-out self-signed-certificate.pem -keyout pub-sec-key.pem<br />
Generiert einen 2048 Bit langen RSA-Schlüssel und legt ihn in der Datei pub-sec-key.pem ab. Es wird ein selbst signiertes Zertifikat erstellt und in der Datei self-signed-certificate.pem gespeichert. Das Zertifikat ist 365 Tag gültig und für simple Testzwecke gedacht.<br />
<br />
openssl req -x509 -days 365 -new -out self-signed-certificate.pem -key pub-sec-key.pem<br />
Wie zuvor, erstellt jedoch ein selbst signiertes Zertifikat aus einem vorhandenen Schlüssel pub-sec-key.pem.<br />
<br />
<br />
== Certifikate konvertieren, ausgeben, pruefen ==<br />
<br />
openssl x509 -text -noout -md5 -in self-signed-certificate.pem<br />
Gibt das Zertifikat self-signed-certificate.pem als Klartext aus.<br />
<br />
openssl x509 -fingerprint -noout -md5 -in self-signed-certificate.pem<br />
Gibt den Fingerabdruck des X.509 Zertifikats self-signed-certificate.pem aus. Der Algorithmus ist hier MD5, SHA1 kann<br />
verwendet werden, wenn -md5 durch -sha1 ersetzt wird.<br />
<br />
openssl verify -issuer_checks -CAfile self-signed-certificate.pem self-signed-certificate.pem<br />
Überprüft ein selbst signiertes Zertifikat.<br />
<br />
openssl s_client -showcerts -CAfile self-signed-certificate.pem -connect www.dfn-pca.de:443<br />
Baut eine OpenSSL-Verbindung unter Verwendung des Zertifikats self-signed-certificate.pem zum angegebenen Server auf. Es wird dabei die gesamte Zertifikatskette angezeigt.<br />
<br />
openssl crl -noout -text -CAfile self-signed-certificate.pem crl.pem<br />
Gibt die Zertifikats-Widerrufsliste crl.pem in Klartext aus.<br />
<br />
<br />
=== PKCS12/PFX conversion ===<br />
<br />
Create PKCS12 from PEM:<br />
<br />
openssl pkcs12 -export -in myCertificate.crt -inkey myCertificate.key -certfile cacert.pem -out myCertificate.pkcs12<br />
<br />
<br />
export pem's from pkcs12-files:<br />
<br />
openssl pkcs12 -in cert.p12 -clcerts -nokeys -nodes -out ./cert.pem<br />
openssl pkcs12 -in cert.p12 -cacerts -nokeys -nodes -out ./root-chain.pem<br />
openssl pkcs12 -in cert.p12 -nocerts -nodes -out ./key.pem<br />
<br />
=== PKCS7 conversion ===<br />
<br />
openssl pkcs7 -in cert.p7b -inform DER -print_certs -out cert.pem<br />
<br />
<br />
=== PEM to DER and DER 2 PEM ===<br />
<br />
Use the OpenSSL commands to convert between formats as follows:<br />
<br />
To convert a certificate from PEM to DER:<br />
openssl x509 -in input.crt -inform PEM –out output.crt -outform DER<br />
<br />
To convert a certificate from DER to PEM:<br />
openssl x509 -in input.crt -inform DER -out output.crt -outform PEM<br />
<br />
To convert a key from PEM to DER:<br />
openssl rsa -in input.key -inform PEM -out output.key -outform DER<br />
<br />
To convert a key from DER to PEM:<br />
openssl rsa -in input.key -inform DER -out output.key -outform PEM<br />
<br />
== Schluessel (KEY) bearbeiten ==<br />
<br />
veraenderungen an vorhandenen schluesseln vornehmen<br />
<br />
<br />
=== Schluessel (KEY) passwort aendern ===<br />
<br />
openssl rsa -in mykey.pem -des3 -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn unter verwendung eines anderen passwortes wieder ab.<br />
<br />
<br />
=== Schluessel (KEY) passwort entfernen ===<br />
<br />
openssl rsa -in mykey.pem -out mykey.pem.new<br />
<br />
oeffnet einen vorhandenen schluessel und speichert ihn OHNE neues passwort wieder ab. (unsicher!!)<br />
<br />
<br />
==CRLs==<br />
<br />
Die CRL ist eine Widerrufliste in der die ungültigen Zertifikate eingetragen<br />
sind und Zugänge aufgehoben werden können (z.B. beim Ausscheiden eines<br />
Mitarbeiters). Dazu wird periodisch eine gültige CRL erstellt. Einzelne<br />
Zertifikate können dann manuell entfernt werden. Die Sperrung erfolgt dann<br />
beim nächsten Anlegen der Liste. Daher sollte die Liste entweder sofort nach<br />
deaktivieren eines Zertifikats oder, je nach Dringlichkeit, täglich oder<br />
wöchentlich per Cronjob erstellt werden.<br />
<br />
<br />
===das Zertifikat von 'meier' entfernen===<br />
<br />
openssl ca -revoke meiercert.pem<br />
<br />
oder <br />
<br />
openssl ca -revoke ./newcerts/03.pem'<br />
<br />
<br />
===Nummern der gesperrten Zertifikate anzeigen===<br />
<br />
openssl crl -in crls/crl.pem -noout -text<br />
<br />
<br />
===gültige CRL erstellen===<br />
<br />
openssl ca -gencrl -out crls/crl.pem<br />
dies muss nach '''JEDEM''' widerruf von certifikaten gemacht werden!!!!<br />
<br />
<br />
===CRL in das binäre DER-Format umwandeln===<br />
<br />
openssl crl -in crls/crl.pem -outform der -out crls/cert.crl<br />
<br />
<br />
== Verifying ==<br />
<br />
=== That a Private Key Matches a Certificate ===<br />
<br />
openssl x509 -noout -text -in server.crt<br />
openssl rsa -noout -text -in server.key<br />
<br />
The `modulus' and the `public exponent' portions in the key and the Certificate must match. But since the public exponent is usually 65537 and it's bothering comparing long modulus you can use the following approach:<br />
<br />
<br />
openssl x509 -noout -modulus -in server.crt | openssl md5<br />
openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And then compare these really shorter numbers. With overwhelming probability they will differ if the keys are different. As a "one-liner":<br />
<br />
openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5<br />
<br />
And with auto-magic comparison (If more than one hash is displayed, they don't match):<br />
<br />
(openssl x509 -noout -modulus -in server.pem | openssl md5 ; openssl rsa -noout -modulus -in server.key | openssl md5) | uniq<br />
<br />
BTW, if I want to check to which key or certificate a particular CSR belongs you can compute<br />
<br />
$ openssl req -noout -modulus -in server.csr | openssl md5<br />
<br />
(Shamelessly stolen from [https://kb.wisc.edu/middleware/page.php?id=4064 here])<br />
<br />
<br />
=== That a cacert matches a server cert ===<br />
<br />
openssl verify -verbose -CAfile cacert.pem server.crt<br />
<br />
<br />
== Pinning / TLSA / etc. ==<br />
<br />
=== Get public key PIN ===<br />
<br />
Get PIN from CERT:<br />
<br />
openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from KEY:<br />
<br />
openssl rsa -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from ECC KEY:<br />
<br />
openssl ec -in privkey.pem -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
Get PIN from CSR:<br />
<br />
openssl req -in signing-request.csr -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64<br />
<br />
<br />
=== TLSA hash ===<br />
<br />
openssl x509 -in cert.pem -noout -fingerprint -sha256 | tr -d ":" | sed 's/SHA256 Fingerprint=//'</div>
Cbs
https://schnallich.net/index.php?title=Convert&diff=1751
Convert
2022-04-27T09:56:38Z
<p>Cbs: </p>
<hr />
<div>'''Source: [http://martin-thoma.com/converting-files-with-linux/ VIA]'''<br />
and extended by me... ;-)<br />
<br />
Converting Files with Linux<br />
September 21st, 2011 No Comments<br />
<br />
The following tipps work under a linux terminal:<br />
<br />
<br />
== Image Files ==<br />
<br />
If you want to change image files via terminal, ImageMagick is a good choice.<br />
<br />
<br />
=== Resize Images to a maximum resolution ===<br />
<br />
convert "YourOldPicture.jpg" -resize 1600x1600 "YourNewPicture.jpg"<br />
<br />
<br />
=== Create a Black-and-white picture and compress it ===<br />
<br />
djpeg "YourOldPicture.jpg" | ppmtopgm | cjpeg -qual 70 >"YourNewPicture.jpg"<br />
<br />
<br />
=== Rename Pictures ===<br />
<br />
rename -n ’s/\.jpg$/\.JPG/’ *.jpg<br />
<br />
<br />
== Audio Files ==<br />
<br />
<br />
=== flac2mp3 ===<br />
<br />
* Convert flac to mp3 audiofile: <pre>ffmpeg -i file.flac -ab 320k -ac 2 file.mp3</pre><br />
<br />
<br />
=== Normalize Audio ===<br />
<br />
Give all mp3 songs the same sound level (it’s called Audio normalization)<br />
<br />
mp3gain -a *.mp3<br />
<br />
<br />
=== Merge mp3 audio files to one ===<br />
<br />
mp3wrap merged.mp3 one.mp3 two.mp3<br />
<br />
<br />
=== fade in/out filter ===<br />
<br />
details see here: https://ffmpeg.org/ffmpeg-filters.html#afade<br/><br />
<br />
* Fade in first 15 seconds of audio:<br />
<br />
ffmpeg [...] -afade=t=in:ss=0:d=15 [...]<br />
<br />
* Fade out last 25 seconds of a 900 seconds audio: <br />
<br />
ffmpeg [...] -afade=t=out:ss=875:d=25 [...]<br />
<br />
or try sox:<br />
<br />
this command will<br />
<br />
* trim out from Position 45 sec. the next 30 seconds (0:45.0 30) and<br />
* fade the first 5 seconds (0:5) and the last 5 seconds (0 0:5) and<br />
* convert from wav to mp3<br />
<br />
sox infile.wav outfile.mp3 trim 0:45.0 30 fade h 0:5 0 0:5<br />
<br />
<br />
=== cut / crop audio ===<br />
<br />
try sox (see above) which strips, fades in and out in one command. <br /><br />
to strip the 1st 30 sec. of an audio file<br />
<br />
ffmpeg -ss 30 -acodec copy -i inputfile.mp3 outputfile.mp3<br />
<br />
to only get the 1st 30 sec. of an audio file<br />
<br />
ffmpeg -t 30 -acodec copy -i inputfile.mp3 outputfile.mp3<br />
<br />
<br />
=== wav2mp3 ===<br />
<br />
* Convert all *.wav-files in one folder two *.mp3-files and remove the *.wav-files: <pre>for i in *.wav;do lame "$i" "${i%wav}mp3"; rm "$i"; done</pre><br />
<br />
* Convert all *.wav-files in one folder two *.mp3-files and move mp3's to mp3-folder: <pre>for i in *.wav;do lame "$i" "${i%wav}mp3"; mkdir -p mp3; mv "${i%wav}mp3" mp3/; done</pre><br />
<br />
<br />
=== mp32wav ===<br />
<br />
convert mp3 to wav<br />
<br />
mpg123 -w output.wav input.mp3<br />
<br />
<br />
=== mp32ogg ===<br />
<br />
convert mp3 to ogg<br />
<br />
mpg123 -w - ./FILE.mp3 | oggenc -q 3.00 -o ./FILE.ogg -<br />
<br />
<br />
== Video Files ==<br />
<br />
For quite a lot purposes is the command line tool FFmpeg with its lots of options a good choice. For others might MEncoder be better.<br />
You might also want to install some codecs first:<br />
<br />
sudo apt-get install libavcodec-extra-52 libavdevice-extra-52 libavformat-extra-52 libavutil-extra-50 \<br />
libpostproc-extra-51 libswscale-extra-0 libavcodec-unstripped-52 ubuntu-restricted-extras<br />
<br />
<br />
=== DVD to mp4 ===<br />
<br />
If you have a DVD or DVD.iso file create a single .VOB file<br />
<br />
mplayer dvd://n -v -dumpstream -dumpfile /var/tmp/dvd.vob<br />
<br />
If 'dvd://n' detects the wrong stream locate longest stream and replace 'n' by stream number<br />
<br />
<pre><br />
$ lsdvd |grep Longest <br />
Longest track: 01<br />
</pre><br />
<br />
If it's an ISO file replace 'dvd://n' by: -dvd-device /path/to/dvdfile.iso <br/><br />
<br/><br />
Now convert .vob to mp4:<br />
<br />
cat /var/tmp/dvd.vob | ffmpeg -i - -codec:a copy -codec:v libx264 /var/tmp/dvd.mp4<br />
<br />
<br />
=== strip audio from video ===<br />
<br />
ffmpeg -i input_file.mp4 -vcodec copy -an output_file.mp4<br />
<br />
<br />
=== replace/add audio in/to a video ===<br />
<br />
1st of all get the streams<br />
<br />
<pre><br />
$ ffmpeg -i video-with-audio.avi -i audio.mp3<br />
[...]<br />
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video-with-audio.avi':<br />
Duration: 00:01:13.29, start: 0.000000, bitrate: 17022 kb/s<br />
Stream #0.0(eng): Video: h264, yuv420p, 1920x1080, 90k tbr, 90k tbn, 180k tbc<br />
Stream #0.1(eng): Audio: aac, 48000 Hz, stereo, s16<br />
Input #1, mp3, from 'audio.mp3':<br />
Duration: 00:00:46.52, start: 0.000000, bitrate: 192 kb/s<br />
Stream #1.0: Audio: mp3, 44100 Hz, stereo, s16, 192 kb/s<br />
At least one output file must be specified<br />
</pre><br />
<br />
now you can see:<br />
* '''stream 0.0''' video-stream in the avi<br />
* '''stream 0.1''' audio-stream in the avi<br />
* '''stream 1.0''' audio-stream (the mp3 file)<br />
<br />
now, to get the video with the mp3-file as audio, do:<br />
<br />
ffmpeg -i video-with-audio.avi -i audio.mp3 -map 0.0 -map 1.0 -acodec copy -vcodec copy output.avi<br />
<br />
here you tell ffmpeg to map streams 0.0 and 1.0 into the new output.avi<br />
<br />
<br />
=== Merge many video files to one ===<br />
<br />
cat One.mpg Two.mpg Three.mpg | ffmpeg -f mpeg -i - -vcodec copy -acodec copy "Merged.mpg"<br />
<br />
<br />
=== avi2mpg ===<br />
<br />
ffmpeg -i "Original.avi" "New.mpg"<br />
<br />
<br />
=== flv2mpeg ===<br />
<br />
* Convert FLV to MPG file: <pre>ffmpeg -i video.flv video.mpg</pre><br />
* Convert MPG to FLV file: <pre>ffmpeg -i video.mpg video.flv</pre><br />
this works for avi, too!<br />
<br />
<br />
=== flv2avi ===<br />
<br />
* Convert FLV to AVI file: <pre>ffmpeg -i video.flv -ar 22050 -b 2048k video.avi</pre><br />
* Convert AVI to FLV file: <pre>ffmpeg -i video.avi video.flv</pre><br />
<br />
<br />
=== avi2avi ===<br />
<br />
;-)<br />
<br />
==== xvid2divx ====<br />
<br />
relabel file from XviD to DivX 5<br/><br />
needs no recoding just re-label it as DivX<br />
<br />
cfourcc -u DX50 -d DX50 "$file"<br />
<br />
=== flv2mp3 ===<br />
<br />
* Convert FLV to mp3 audio file: <pre>ffmpeg -i video.flv -ab 192k output.mp3</pre><br />
<br />
<br />
=== *2flv ===<br />
<br />
to convert some format to flv <br/><br />
for webstreaming there is some more work to do, which i will describe here...<br/><br/><br />
<br />
flv streaming in apache:<br />
<br />
* get the apache module: [http://people.apache.org/~pquerna/modules/mod_flvx.c HERE]<br />
* compile with apxs2 (debian) btw. apxs (RH-related distros) <pre>apxs2 -i -c ./mod_flvx.c</pre><br />
* load into apache2: <br />
<pre><br />
cat /etc/apache2/mods-available/flvx.load<br />
<br />
# flv-streaming plugin<br />
# source: http://people.apache.org/%7Epquerna/modules/mod_flvx.c<br />
# build: apxs -c -i ./mod_flvx.c<br />
<br />
LoadModule flvx_module /usr/lib/apache2/modules/mod_flvx.so<br />
AddHandler flv-stream .flv<br />
</pre><br />
* enable module: <pre>a2enmod flvx</pre><br />
* restart apache<br />
* create flv: <pre>ffmpeg -i ~/any.supported.format.eg.mp4 -b 4000000 -r 25 -s 800x600 ~/output-file.flv</pre><br />
** perhaps try around with b-frames: '''-b_qfactor 4.0''' - see ''man ffmpeg''<br />
* Add pseudostreaming meta data to the file: <pre>flvtool2 -Up output-file.flv</pre><br />
** if you want to preserve a file WITHOUT meta data for webstreaming create a backup <br/>'''flvtool2 will inject metadata into actual file!'''<br />
<br />
<br />
=== swf2avi ===<br />
<br />
requires package: pyvnc2swf<br />
<br />
vnc2swf-edit -o output.flv input.swf<br />
ffmpeg -i input.flv output.avi<br />
<br />
<br />
=== mov2avi ===<br />
<br />
ffmpeg -i movie.mov -acodec copy -vcodec copy movie.avi<br />
<br />
<br />
=== mp42mpg === <br />
<br />
ffmpeg -i "Original.mp4" -target ntsc-vcd "New.mpg"<br />
<br />
<br />
=== mp42avi ===<br />
<br />
ffmpeg -i filename.mp4 -vcodec mpeg4 -acodec ac3 -ar 48000 -ab 192k output.avi<br />
<br />
or<br />
<br />
-acodec libmp3lame<br />
<br />
<br />
=== mp42mp3 ===<br />
=== mp42wav ===<br />
<br />
extracts audio from an mp4 video file<br />
<br />
mplayer source.mp4 -ao pcm:file=tmp.wav<br />
lame -b 128 -q 2 tmp.wav final.mp3<br />
<br />
<br />
=== mod2avi === <br />
?<br />
<br />
<br />
=== vcd2avi === <br />
<br />
mencoder vcd://2 -o "New.avi" -oac copy -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=2000<br />
<br />
=== dvd2avi ===<br />
<br />
to do this you will have to run the following command-tripple:<br />
<br />
# get the black border dimensions to cut them off<br />
# run pass 1 with mencoder to create the 'divx2pass.log', which is needed by pass 2 run<br />
# run pass 2<br />
<br />
1)<br />
<br />
play TRACK 1 (dvd://1), chapter 3<br />
<br />
mplayer dvd://1 [-dvd-device /path/to/dir or /dev/cdrom] -chapter 3 -vf cropdetect<br />
...<br />
[CROP] Crop area: X: 0..719 Y: 70..505 (-vf crop=720:432:0:72).0<br />
...<br />
<br />
2)<br />
do the 1st pass with mencoder<br/><br />
set '''-vf crop=''' to the value mplayer puts out to console <br/><br />
while running the 1st command<br />
<br />
mencoder dvd://1 [-dvd-device /path/to/dir or /dev/cdrom] \<br />
-vf crop=720:432:0:72,scale=704:304 -ovc xvid \<br />
-xvidencopts bvhq=1:chroma_opt:quant_type=mpeg:bitrate=658:pass=1 \<br />
-oac copy -o /dev/null<br />
<br />
* scale=704:304 ==> nice for 16:9<br/>if you change that, be sure the values both are dividable by 16!!<br />
* if you dont want to use CD (700MB) to backup that film '''try using a bitrate ob 1200 or 1400''' instead of 658<br />
** a bitrate of 1600 creates a 2GB file out of 4.6GB-DVD and has acceptable quality...<br />
<br />
3)<br />
<br />
2nd pass run...<br/><br />
be sure the divx2pass.log file is in CWD where you start mencoder...<br />
<br />
mencoder dvd://1 dvd://1 [-dvd-device /path/to/dir or /dev/cdrom] \<br />
-vf crop=720:416:0:80,scale=704:304 -ovc xvid \<br />
-xvidencopts bvhq=1:chroma_opt:quant_type=mpeg:bitrate=658:pass=2 \<br />
-alang de -oac mp3lame -lameopts br=96:cbr:vol=6 -o FILM.avi<br />
<br />
=== ogv2avi === <br />
<br />
mencoder "Original.ogv" -ovc xvid -oac mp3lame -xvidencopts pass=1 -o "New.avi"<br />
<br />
=== wmv2mpg === <br />
<br />
aspect=16/9 should eventually be changed to 4/3 or other aspects<br />
<br />
mencoder -of avi -ofps 25 \<br />
-oac mp3lame -lameopts cbr:br=112:aq=3:mode=0:vol=0 \<br />
-vf hqdn3d,softskip,harddup \<br />
-ovc xvid \<br />
-xvidencopts bitrate=501:max_key_interval=37:aspect=16/9:turbo:nochroma_me:notrellis:max_bframes=0:vhq=0 \<br />
Original.wmv \<br />
-o New.avi<br />
<br />
=== mkv2avi === <br />
<br />
mencoder "Original.mkv" -ovc lavc -lavcopts vcodec=mpeg4:vhq:vbitrate=6000 -oac mp3lame -lameopts vbr=3 -o "New.avi"<br />
<br />
or use ffmpeg<br />
<br />
ffmpeg -i INPUT_FILE -f mp4 -r 23.976 -vcodec libx264 -s 1280x720 \<br />
-b 3000kb -aspect 16:9 -flags +loop -cmp +chroma -deblockalpha 0 \<br />
-deblockbeta 0 -maxrate 3500k -bufsize 4M -bt 256k -refs 1 \<br />
-bf 3 -coder 1 -me_method umh -me_range 16 -subq 7 \<br />
-partitions +parti4x4+parti8x8+partp8x8+partb8x8 -g 250 \<br />
-keyint_min 25 -level 30 -qmin 10 -qmax 51 -qcomp 0.6 -trellis 2 \<br />
-sc_threshold 40 -i_qfactor 0.71 -acodec libfaac -ab 384kb -ar 48000 -ac 2 OUTPUT.MP4<br />
<br />
<br />
=== ts2avi ===<br />
<br />
mencoder SOURCE.ts -oac mp3lame -lameopts abr:br=128 -ovc lavc \<br />
-lavcopts vcodec=mpeg4:vhq:v4mv:vqmin=2:aspect=16/9:vbitrate=1267 \<br />
-vf pp=de,crop=0:0:0:0,scale=704:400 -ffourcc DX50 -o DESTINATION.avi<br />
<br />
== Siehe auch ==<br />
<br />
# [[Ffmpeg]]</div>
Cbs
https://schnallich.net/index.php?title=Hp/CLI&diff=1750
Hp/CLI
2022-03-02T12:59:06Z
<p>Cbs: /* Upgrade */</p>
<hr />
<div>== ProCurve Cheat Sheet ==<br />
<br />
see also: [[HP/ProCurve_CLI_CheatSheet]]<br />
<br />
<br />
== Reset to default config ==<br />
<br />
erase startup-config<br />
<br />
<br />
== reload after/at (critical changes) ==<br />
<br />
doing critical changes?<br/><br />
<br/><br />
beore you do your changes:<br />
<br />
reload after 15<br />
<br />
will reload the switch after 15 minutes<br />
<br />
reload at 21:30<br />
<br />
will reload the switch at 21:30<br />
<br />
show reload after <br />
<br />
or <br />
<br />
show reload at <br />
<br />
will show you if a reload is scheduled<br />
<br />
Do your changes now!<br/><br />
<br />
DO NOT(!!) do a 'write mem'<br />
<br />
Verify everything is working as expected.<br/><br />
If it is, stop the reload timer:<br />
<br />
no reload<br />
<br />
will cancel the scheduled reload<br />
<br />
write mem<br />
<br />
writes your running config to flash<br />
<br />
<br />
== Upgrade ==<br />
<br />
=== Single Management Module ===<br />
<br />
Enable SCP file transfers<br />
<br />
ip ssh filetransfer<br />
<br />
Show the current flash memory<br />
<br />
<pre><br />
# sh flash<br />
Image Size (bytes) Date Version <br />
----------------- ------------ -------- --------------<br />
Primary Image : 33104874 10/13/17 KB.16.04.0009 <br />
Secondary Image : 18499135 08/24/15 KB.15.17.0008 <br />
<br />
Boot ROM Version <br />
----------------<br />
Primary Boot ROM Version : KB.16.01.0006<br />
Secondary Boot ROM Version : KB.16.01.0006<br />
<br />
Default Boot Image : Primary<br />
Default Boot ROM : Primary<br />
</pre><br />
<br />
Copy your local image to the switch:<br/><br />
If you want to update the primary flash use path: /os/primary<br/><br />
primary and secondary are the actual filenames - No directories!!<br />
<br />
scp tmp/coresw/KB_16_09_0019.swi coresw2:/os/secondary<br />
<br />
Show the flash again and notice the new version on the image you upgraded:<br />
<pre><br />
sh flash<br />
Image Size (bytes) Date Version <br />
----------------- ------------ -------- --------------<br />
Primary Image : 33104874 10/13/17 KB.16.04.0009<br />
Secondary Image : 34246053 12/10/21 KB.16.09.0019<br />
<br />
Boot ROM Version <br />
----------------<br />
Primary Boot ROM Version : KB.16.01.0006<br />
Secondary Boot ROM Version : KB.16.01.0006<br />
<br />
Default Boot Image : Primary<br />
Default Boot ROM : Primary<br />
</pre><br />
<br />
Now check availability of multiple config files and <br/><br />
which one is used for each partition.<br />
<br />
<pre><br />
# !!!!!!!!!!!! This needs to be checked !!!!!!!!!!!!<br />
# Show the available config files as there might be more than one! <br />
# This will show you which config exists, is actually running (act), which will be started if booting <br />
# primary boot image (pri) and which one will be started if booting from secondary partition/image<br />
<br />
ff3coresw01# sh config files<br />
<br />
Configuration files:<br />
<br />
id | act pri sec | name<br />
---+-------------+------------------------------------------------<br />
1 | * * | config1<br />
2 | * | config2<br />
3 | |<br />
</pre><br />
<br />
As you can see above:<br />
# The current running-config is config1 and this is also used by default if booting the primary flash<br />
# The default config for booting the secondary flash image would be config2, which nobody knows what it does.<br />
# If needed list the configs by: '''show config config-filname'''<br />
# Change defaults for flash image 'secondary' to also use config1 by default.<br />
<br />
startup-default secondary config config1<br />
<br />
and check the result:<br />
<br />
<pre><br />
sh config files <br />
<br />
Configuration files:<br />
<br />
id | act pri sec | name<br />
---+-------------+------------------------------------------------<br />
1 | * * * | config1<br />
2 | | config2<br />
3 | |<br />
</pre><br />
<br />
As you can see: config1 will be used by default if booting from the secondary image now.<br/><br />
<br/><br />
Reboot system now:<br />
<br />
boot system flash secondary <br />
<br />
or specify the config to use with your reboot command:<br />
<br />
boot system flash secondary config config2<br />
<br />
Be careful as I assume that will not change any defaults and <br/><br />
might mess up your config on unexpected reboot!<br />
<br />
<br />
<br />
=== Redundant Management Modules ===<br />
<br />
Check Management Modules<br />
<br />
<pre><br />
# show redundancy <br />
<br />
Configured Mode: Nonstop Switching <br />
Current Mode : Nonstop Switching<br />
<br />
Rapid Switchover Stale Timer : 90<br />
Failovers : 0<br />
Last Failover : <br />
<br />
Slot Module Description State SW Version Boot Image<br />
---- ---------------------------------------- -------- ------------- ----------<br />
MM1 HP J9827A Management Module 5400Rzl2 Active KB.16.04.0009 Primary <br />
MM2 HP J9827A Management Module 5400Rzl2 Standby KB.16.04.0009 Primary<br />
</pre><br />
<br />
Copy the new firmware to whatever image partition you want.<br/><br />
See 'Single Management Modules' if you dont know how that works.<br/><br />
In this example I use the secondary.<br/><br/><br />
<br />
Change the default config for secondary partition:<br />
<br />
startup-default secondary config config1<br />
<br />
check the config file configuration:<br />
<br />
<pre><br />
# sh config file<br />
<br />
Configuration files:<br />
<br />
id | act pri sec | name<br />
---+-------------+------------------------------------------------<br />
1 | * * * | config1<br />
2 | |<br />
3 | |<br />
</pre><br />
<br />
Set the system to boot from partition 'secondary' by default<br />
<br />
boot set-default flash secondary<br />
<br />
Check if everything is as expected<br />
<br />
show flash<br />
show config files<br />
show redundancy<br />
<br />
Write the memory to disk<br />
<br />
wr mem<br />
<br />
Now reboot the '''standby''' management module<br/><br />
this will have no effect on the active running code version of the switch<br/><br />
as only the standby module reboots to the new code version.<br />
<br />
boot standby<br />
<br />
!!! wait for secondary management module to be restarted !!!<br/><br />
run:<br />
<br />
show redundancy<br />
<br />
Now failover to '''standby''' management module (!!! THIS is where outage occures !!!)<br />
<br />
redundancy switchover<br />
<br />
check lacp<br />
<br />
sh lacp<br />
<br />
ping some systems attached to the switches<br />
<br />
== Auth ==<br />
<br />
Set/Change Authorization<br />
<br />
(config)# no password manager<br />
Password protection for manager will be deleted, continue [y/n]? y<br />
<br />
password manager user-name <USERNAME> plaintext <PASSWORD><br />
<br />
<br />
== Interfaces ==<br />
<br />
<br />
=== reset counters ===<br />
<br />
clear statistics 26<br />
<br />
reset interface stats of interface 26<br />
<br />
<br />
=== find switchport of device ===<br />
<br />
# ping 192.168.251.2<br />
<br />
# show arp<br />
<br />
IP ARP table<br />
<br />
IP Address MAC Address Type Port<br />
--------------- ----------------- ------- ----<br />
192.168.251.1 e8b748-c757b0 dynamic 13<br />
192.168.251.2 005056-a61c1c dynamic 5 << It’s on port 5<br />
192.168.251.5 005056-a606d9 dynamic 7<br />
<br />
If you already know the MAC:<br />
<br />
# show mac-address 005056-a61c1c<br />
<br />
Status and Counters - Address Table - 005056-a61c1c<br />
<br />
Port<br />
-------<br />
5<br />
<br />
== oneLiners ==<br />
<br />
<br />
=== is VLAN X in use? ===<br />
<br />
This command will show if the switch learned any MAC addresses on VLAN 302<br />
<br />
sh mac-address | inc " 302"<br />
<br />
<br />
== sflow ==<br />
<br />
yadda<br />
<br />
<br />
=== Configuring sFlow ===<br />
<br />
[no] sflow <instance-Nr.> destination <ip-address> [udp-port-num]<br />
<br />
Enables an sFlow receiver/destination. The receiver-instance number must be a 1, 2, or 3.<br/><br />
By default, the udp destination port number is 6343.<br/><br />
To disable an sFlow receiver/destination, enter no sflow receiver-instance.<br/><br />
<br />
<br />
<br />
sflow <instance-Nr.> sampling <PORT-LIST> sampling <rate><br />
<br />
Once an sFlow receiver/destination has been enabled, this command enables flow sampling for that instance.<br/><br />
The receiver-instance number is 1, 2, or 3, and the sampling rate is the allowable non-zero skipcount for the specified port or ports.<br/><br />
A good starting point for sampling rate is 500 on high volume switches rais this value to 2000 or 5000. <br/><br />
<br/><br />
To disable flow-sampling for the specified <PORT-LIST> repeat the above command with a sampling rate of 0.<br />
<br />
<br />
sflow <instance-Nr.> polling <PORT-LIST> polling <interval><br />
<br />
Once an sFlow receiver/destination has been enabled, this command enables counter polling for that instance.<br/><br />
The receiver-instance number is 1, 2, or 3, and the polling interval may be set to an allowable non-zero value to enable polling on the specified port or ports.<br/><br />
A good starting point for polling interval is 20.<br/><br />
<br/><br />
To disable counter-polling for the specified <PORT-LIST>, repeat the above command with a polling interval of 0.<br />
<br />
<br />
<br />
=== Viewing sFlow Configuration and Status ===<br />
<br />
Show agent info:<br />
<br />
show sflow agent<br />
<br />
<br />
Show instance destination IP:<br />
<br />
show sflow <instance-Nr.> destination<br />
<br />
<br />
Show sampling/polling configuration:<br />
<br />
show sflow <instance-Nr.> sampling-polling <PORT-LIST/range><br />
<br />
<br />
=== sFlow on ProCurve 2610 ===<br />
<br />
Shamelessly stolen from: [https://thwack.solarwinds.com/thread/23881 https://thwack.solarwinds.com/thread/23881]<br />
<br />
<br />
For a HP Procurve 2610 sflow needs to be enabled. You do this by modifying mib variables.<br/><br />
Red items are variables you need to change. Notes on Red Items below<br/><br />
<br/><br />
<br />
<br />
The following needs to be run in config mode:<br />
<br />
<br />
<pre><br />
setmib sFlowRcvrAddress.1 -o c0a80001<br />
^---- The IP address of the receiver in HEX<br />
<br />
setmib sFlowRcvrPort.1 -i 2055<br />
^---- Listen-Port of the receiver server<br />
<br />
setmib sFlowRcvrOwner.1 -D OwnerName sFlowRcvrTimeout.1 -i 214748364<br />
<br />
<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.1.1 -i 37<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.2.1 -i 37<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.3.1 -i 37<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.4.1 -i 37<br />
^--- This one is the Switchport to set Sampling Rate on<br />
<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.1.1 -i 1<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.2.1 -i 1<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.3.1 -i 1<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.4.1 -i 1<br />
^---- This one is the Switchport to set the ENABLE Bit on<br />
</pre><br />
<br />
sFlowRcvrAddress is the hex IP address for the NetFlow Server.<br />
<br />
sFlowRcvrPort is the port that Netflow is received on on the NetFlow server. Note: 2055 is default.<br />
<br />
sFlowRcvrOwner is the owner tag in show sflow destination as far as I can tell it is simply descriptive.<br />
<br />
sFlowRcvrTimeout is the amount of time to transmit sflow data to the destination. sflow will stop after this timer runs out. 214748364 = ~6.8 years.<br />
<br />
The numbers highlighted in the mib variable strings are the ports that the variables are set on.<br />
<br />
sFlowFsPacketSamplingRate is the packet sampling rate the faster the sampling the more accurate the data (and likely the slower the packet transfer from the overhead).<br />
<br />
sFlowFsReceiver is the sflow enable bit.</div>
Cbs
https://schnallich.net/index.php?title=Hp/CLI&diff=1749
Hp/CLI
2022-02-28T12:02:13Z
<p>Cbs: </p>
<hr />
<div>== ProCurve Cheat Sheet ==<br />
<br />
see also: [[HP/ProCurve_CLI_CheatSheet]]<br />
<br />
<br />
== Reset to default config ==<br />
<br />
erase startup-config<br />
<br />
<br />
== reload after/at (critical changes) ==<br />
<br />
doing critical changes?<br/><br />
<br/><br />
beore you do your changes:<br />
<br />
reload after 15<br />
<br />
will reload the switch after 15 minutes<br />
<br />
reload at 21:30<br />
<br />
will reload the switch at 21:30<br />
<br />
show reload after <br />
<br />
or <br />
<br />
show reload at <br />
<br />
will show you if a reload is scheduled<br />
<br />
Do your changes now!<br/><br />
<br />
DO NOT(!!) do a 'write mem'<br />
<br />
Verify everything is working as expected.<br/><br />
If it is, stop the reload timer:<br />
<br />
no reload<br />
<br />
will cancel the scheduled reload<br />
<br />
write mem<br />
<br />
writes your running config to flash<br />
<br />
<br />
== Upgrade ==<br />
<br />
=== Single Management Module ===<br />
<br />
Enable SCP file transfers<br />
<br />
ip ssh filetransfer<br />
<br />
Show the current flash memory<br />
<br />
<pre><br />
# sh flash<br />
Image Size (bytes) Date Version <br />
----------------- ------------ -------- --------------<br />
Primary Image : 33104874 10/13/17 KB.16.04.0009 <br />
Secondary Image : 18499135 08/24/15 KB.15.17.0008 <br />
<br />
Boot ROM Version <br />
----------------<br />
Primary Boot ROM Version : KB.16.01.0006<br />
Secondary Boot ROM Version : KB.16.01.0006<br />
<br />
Default Boot Image : Primary<br />
Default Boot ROM : Primary<br />
</pre><br />
<br />
Copy your local image to the switch:<br/><br />
If you want to update the primary flash use path: /os/primary<br/><br />
primary and secondary are the actual filenames - No directories!!<br />
<br />
scp tmp/coresw/KB_16_09_0019.swi coresw2:/os/secondary<br />
<br />
Show the flash again and notice the new version on the image you upgraded:<br />
<pre><br />
sh flash<br />
Image Size (bytes) Date Version <br />
----------------- ------------ -------- --------------<br />
Primary Image : 33104874 10/13/17 KB.16.04.0009<br />
Secondary Image : 34246053 12/10/21 KB.16.09.0019<br />
<br />
Boot ROM Version <br />
----------------<br />
Primary Boot ROM Version : KB.16.01.0006<br />
Secondary Boot ROM Version : KB.16.01.0006<br />
<br />
Default Boot Image : Primary<br />
Default Boot ROM : Primary<br />
</pre><br />
<br />
Now check availability of multiple config files and <br/><br />
which one is used for each partition.<br />
<br />
<pre><br />
# !!!!!!!!!!!! This needs to be checked !!!!!!!!!!!!<br />
# Show the available config files as there might be more than one! <br />
# This will show you which config exists, is actually running (act), which will be started if booting <br />
# primary boot image (pri) and which one will be started if booting from secondary partition/image<br />
<br />
ff3coresw01# sh config files<br />
<br />
Configuration files:<br />
<br />
id | act pri sec | name<br />
---+-------------+------------------------------------------------<br />
1 | * * | config1<br />
2 | * | config2<br />
3 | |<br />
</pre><br />
<br />
As you can see above:<br />
# The current running-config is config1 and this is also used by default if booting the primary flash<br />
# The default config for booting the secondary flash image would be config2, which nobody knows what it does.<br />
# If needed list the configs by: '''show config config-filname'''<br />
# Change defaults for flash image 'secondary' to also use config1 by default.<br />
<br />
startup-default secondary config config1<br />
<br />
and check the result:<br />
<br />
<pre><br />
sh config files <br />
<br />
Configuration files:<br />
<br />
id | act pri sec | name<br />
---+-------------+------------------------------------------------<br />
1 | * * * | config1<br />
2 | | config2<br />
3 | |<br />
</pre><br />
<br />
As you can see: config1 will be used by default if booting from the secondary image now.<br/><br />
<br/><br />
Reboot system now:<br />
<br />
boot system flash secondary <br />
<br />
or specify the config to use with your reboot command:<br />
<br />
boot system flash secondary config config2<br />
<br />
Be careful as I assume that will not change any defaults and <br/><br />
might mess up your config on unexpected reboot!<br />
<br />
<br />
<br />
== Auth ==<br />
<br />
Set/Change Authorization<br />
<br />
(config)# no password manager<br />
Password protection for manager will be deleted, continue [y/n]? y<br />
<br />
password manager user-name <USERNAME> plaintext <PASSWORD><br />
<br />
<br />
== Interfaces ==<br />
<br />
<br />
=== reset counters ===<br />
<br />
clear statistics 26<br />
<br />
reset interface stats of interface 26<br />
<br />
<br />
=== find switchport of device ===<br />
<br />
# ping 192.168.251.2<br />
<br />
# show arp<br />
<br />
IP ARP table<br />
<br />
IP Address MAC Address Type Port<br />
--------------- ----------------- ------- ----<br />
192.168.251.1 e8b748-c757b0 dynamic 13<br />
192.168.251.2 005056-a61c1c dynamic 5 << It’s on port 5<br />
192.168.251.5 005056-a606d9 dynamic 7<br />
<br />
If you already know the MAC:<br />
<br />
# show mac-address 005056-a61c1c<br />
<br />
Status and Counters - Address Table - 005056-a61c1c<br />
<br />
Port<br />
-------<br />
5<br />
<br />
== oneLiners ==<br />
<br />
<br />
=== is VLAN X in use? ===<br />
<br />
This command will show if the switch learned any MAC addresses on VLAN 302<br />
<br />
sh mac-address | inc " 302"<br />
<br />
<br />
== sflow ==<br />
<br />
yadda<br />
<br />
<br />
=== Configuring sFlow ===<br />
<br />
[no] sflow <instance-Nr.> destination <ip-address> [udp-port-num]<br />
<br />
Enables an sFlow receiver/destination. The receiver-instance number must be a 1, 2, or 3.<br/><br />
By default, the udp destination port number is 6343.<br/><br />
To disable an sFlow receiver/destination, enter no sflow receiver-instance.<br/><br />
<br />
<br />
<br />
sflow <instance-Nr.> sampling <PORT-LIST> sampling <rate><br />
<br />
Once an sFlow receiver/destination has been enabled, this command enables flow sampling for that instance.<br/><br />
The receiver-instance number is 1, 2, or 3, and the sampling rate is the allowable non-zero skipcount for the specified port or ports.<br/><br />
A good starting point for sampling rate is 500 on high volume switches rais this value to 2000 or 5000. <br/><br />
<br/><br />
To disable flow-sampling for the specified <PORT-LIST> repeat the above command with a sampling rate of 0.<br />
<br />
<br />
sflow <instance-Nr.> polling <PORT-LIST> polling <interval><br />
<br />
Once an sFlow receiver/destination has been enabled, this command enables counter polling for that instance.<br/><br />
The receiver-instance number is 1, 2, or 3, and the polling interval may be set to an allowable non-zero value to enable polling on the specified port or ports.<br/><br />
A good starting point for polling interval is 20.<br/><br />
<br/><br />
To disable counter-polling for the specified <PORT-LIST>, repeat the above command with a polling interval of 0.<br />
<br />
<br />
<br />
=== Viewing sFlow Configuration and Status ===<br />
<br />
Show agent info:<br />
<br />
show sflow agent<br />
<br />
<br />
Show instance destination IP:<br />
<br />
show sflow <instance-Nr.> destination<br />
<br />
<br />
Show sampling/polling configuration:<br />
<br />
show sflow <instance-Nr.> sampling-polling <PORT-LIST/range><br />
<br />
<br />
=== sFlow on ProCurve 2610 ===<br />
<br />
Shamelessly stolen from: [https://thwack.solarwinds.com/thread/23881 https://thwack.solarwinds.com/thread/23881]<br />
<br />
<br />
For a HP Procurve 2610 sflow needs to be enabled. You do this by modifying mib variables.<br/><br />
Red items are variables you need to change. Notes on Red Items below<br/><br />
<br/><br />
<br />
<br />
The following needs to be run in config mode:<br />
<br />
<br />
<pre><br />
setmib sFlowRcvrAddress.1 -o c0a80001<br />
^---- The IP address of the receiver in HEX<br />
<br />
setmib sFlowRcvrPort.1 -i 2055<br />
^---- Listen-Port of the receiver server<br />
<br />
setmib sFlowRcvrOwner.1 -D OwnerName sFlowRcvrTimeout.1 -i 214748364<br />
<br />
<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.1.1 -i 37<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.2.1 -i 37<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.3.1 -i 37<br />
setmib sFlowFsPacketSamplingRate.11.1.3.6.1.2.1.2.2.1.1.4.1 -i 37<br />
^--- This one is the Switchport to set Sampling Rate on<br />
<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.1.1 -i 1<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.2.1 -i 1<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.3.1 -i 1<br />
setmib sFlowFsReceiver.11.1.3.6.1.2.1.2.2.1.1.4.1 -i 1<br />
^---- This one is the Switchport to set the ENABLE Bit on<br />
</pre><br />
<br />
sFlowRcvrAddress is the hex IP address for the NetFlow Server.<br />
<br />
sFlowRcvrPort is the port that Netflow is received on on the NetFlow server. Note: 2055 is default.<br />
<br />
sFlowRcvrOwner is the owner tag in show sflow destination as far as I can tell it is simply descriptive.<br />
<br />
sFlowRcvrTimeout is the amount of time to transmit sflow data to the destination. sflow will stop after this timer runs out. 214748364 = ~6.8 years.<br />
<br />
The numbers highlighted in the mib variable strings are the ports that the variables are set on.<br />
<br />
sFlowFsPacketSamplingRate is the packet sampling rate the faster the sampling the more accurate the data (and likely the slower the packet transfer from the overhead).<br />
<br />
sFlowFsReceiver is the sflow enable bit.</div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1748
Windows/powershell
2021-09-15T08:29:28Z
<p>Cbs: /* Trigger Client Action */</p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== Change Drive Letter ==<br />
<br />
From D: to Z: in this example:<br />
<br />
Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'}<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Trigger Client Action ===<br />
<br />
<pre><br />
Cycle ID<br />
ApplicationDeployment Evaluation Cycle "{00000000-0000-0000-0000-000000000121}"<br />
DiscoveryData Collection Cycle "{00000000-0000-0000-0000-000000000003}"<br />
FileCollection Cycle "{00000000-0000-0000-0000-000000000010}"<br />
HardwareInventory Cycle "{00000000-0000-0000-0000-000000000001}"<br />
MachinePolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000021}"<br />
SoftwareInventory Cycle "{00000000-0000-0000-0000-000000000002}"<br />
SoftwareMetering Usage Report Cycle "{00000000-0000-0000-0000-000000000031}"<br />
SoftwareUpdate Deployment Evaluation Cycle "{00000000-0000-0000-0000-000000000114}"<br />
SoftwareUpdate Scan Cycle "{00000000-0000-0000-0000-000000000113}"<br />
StateMessage Refresh "{00000000-0000-0000-0000-000000000111}"<br />
UserPolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000026}"<br />
UserPolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000027}"<br />
WindowsInstallers Source List Update Cycle "{00000000-0000-0000-0000-000000000032}"<br />
MachinePolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000022}"<br />
</pre><br />
<br />
Run Cycle:<br />
<br />
Invoke-WMIMethod -Namespace root\ccm -Class SMS_CLIENT -Name TriggerSchedule "{00000000-0000-0000-0000-000000000121}"<br />
<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1747
Windows/powershell
2021-09-15T08:29:15Z
<p>Cbs: /* SCCM Related */</p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== Change Drive Letter ==<br />
<br />
From D: to Z: in this example:<br />
<br />
Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'}<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Trigger Client Action ===<br />
<br />
<pre><br />
Cycle ID<br />
ApplicationDeployment Evaluation Cycle "{00000000-0000-0000-0000-000000000121}"<br />
DiscoveryData Collection Cycle "{00000000-0000-0000-0000-000000000003}"<br />
FileCollection Cycle "{00000000-0000-0000-0000-000000000010}"<br />
HardwareInventory Cycle "{00000000-0000-0000-0000-000000000001}"<br />
MachinePolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000021}"<br />
SoftwareInventory Cycle "{00000000-0000-0000-0000-000000000002}"<br />
SoftwareMetering Usage Report Cycle "{00000000-0000-0000-0000-000000000031}"<br />
SoftwareUpdate Deployment Evaluation Cycle "{00000000-0000-0000-0000-000000000114}"<br />
SoftwareUpdate Scan Cycle "{00000000-0000-0000-0000-000000000113}"<br />
StateMessage Refresh "{00000000-0000-0000-0000-000000000111}"<br />
UserPolicy Retrieval Cycle "{00000000-0000-0000-0000-000000000026}"<br />
UserPolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000027}"<br />
WindowsInstallers Source List Update Cycle "{00000000-0000-0000-0000-000000000032}"<br />
MachinePolicy Evaluation Cycle "{00000000-0000-0000-0000-000000000022}"<br />
</pte><br />
<br />
Run Cycle:<br />
<br />
Invoke-WMIMethod -Namespace root\ccm -Class SMS_CLIENT -Name TriggerSchedule "{00000000-0000-0000-0000-000000000121}"<br />
<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1746
Windows/powershell
2021-09-08T08:05:26Z
<p>Cbs: </p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== Change Drive Letter ==<br />
<br />
From D: to Z: in this example:<br />
<br />
Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'}<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1745
Windows/powershell
2021-09-08T07:58:07Z
<p>Cbs: </p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== Change Drive Letter ==<br />
<br />
From D: to Z:<br />
<br />
Set-WmiInstance -InputObject ( Get-WmiObject -Class Win32_volume -Filter "DriveLetter = 'd:'" ) -Arguments @{DriveLetter='Z:'}<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Pulseaudio&diff=1744
Pulseaudio
2021-07-27T13:03:47Z
<p>Cbs: /* KDE Phonon Device Preference */</p>
<hr />
<div>== KDE Phonon Device Preference ==<br />
<br />
If you're using KDE and did restart the Pulseaudio daemon, it's most likely <br/><br />
that KDE Phonon is broken and only shows 'Pulseaudio Daemon' so you can't <br/><br />
select different devices for Notifications, Music, Communication and so on.<br/><br/><br />
<br />
Reason is that a module isn't loaded, that would be loaded as part of the login process.<br/><br />
Just run the following as the user which is logged into the desktop:<br />
<br />
pactl load-module module-device-manager "do_routing=1"</div>
Cbs
https://schnallich.net/index.php?title=Pulseaudio&diff=1743
Pulseaudio
2021-07-27T13:03:05Z
<p>Cbs: Die Seite wurde neu angelegt: „== KDE Phonon Device Preference == If you're using KDE and did restart the Pulseaudio daemon, it's most likely <br/> that KDE Phonon is broken and only shows…“</p>
<hr />
<div>== KDE Phonon Device Preference ==<br />
<br />
If you're using KDE and did restart the Pulseaudio daemon, it's most likely <br/><br />
that KDE Phonon is broken and only shows 'Pulseaudio Daemon' so you can't <br/><br />
select different devices Notifications, Music, Communication and so on.<br/><br/><br />
<br />
Reason is that a module isn't loaded, that would be loaded as part of the login process.<br/><br />
Just run the following as the user which is logged into the desktop:<br />
<br />
pactl load-module module-device-manager "do_routing=1"</div>
Cbs
https://schnallich.net/index.php?title=Yum&diff=1742
Yum
2021-07-02T09:44:19Z
<p>Cbs: </p>
<hr />
<div>Yum-Repo management<br />
<br />
[[Nc24:YUM-Repo]]<br />
<br />
<br />
== Cheat sheet ==<br />
<br />
=== YUM QUERIES ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
help Display yum commands and options<br />
yum help<br />
Show yum subcommands and options<br />
<br />
Individual packages<br />
<br />
list List package names from repositories<br />
yum list available<br />
List all available packages<br />
yum list installed<br />
List all installed packages<br />
yum list all<br />
List installed and available packages<br />
yum list kernel<br />
List installed and available kernel packages<br />
<br />
info Display information about a package<br />
yum info vsftpd<br />
List info about vsftpd package<br />
<br />
deplist Display dependencies for a package<br />
yum deplist nfs-utils<br />
List dependencies and packages providing them<br />
<br />
provides Find packages that provide the queried file<br />
yum provides “*bin/top”<br />
Show package that contains top command<br />
yum provides “*/README.top”<br />
Show package containing README.top file<br />
<br />
search Search package names and descriptions for a term<br />
<br />
search nfs Find packages with 'nfs' in name or description<br />
<br />
updateinfo Get information about available package updates<br />
yum updateinfo security<br />
Get info on available security updates<br />
<br />
Groups of packages<br />
<br />
grouplist List names of installed and available package groups<br />
groupinfo Display description and contents of a package group<br />
yum groupinfo “Web Server”<br />
See packages in Web Server group<br />
<br />
check-update Query repositories for available package updates<br />
</pre><br />
<br />
<br />
=== MANAGE YUM REPOSITORIES ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
repolist Display enabled software repositories<br />
<br />
repoinfo Display information about enabled yum repositories *<br />
yum repoinfo rhel-7-server-rpms<br />
See info on rhel-7-server-rpms repo<br />
<br />
repo-pkgs Work with packages in a particular repository *<br />
yum repo-pkgs my-rpms list<br />
List packages from my-rpms repo<br />
yum repo-pkgs my-rpms install<br />
Install all packages from my-rpms repo<br />
yum repo-pkgs my-rpms remove<br />
Remove all packages from my-rpms repo<br />
<br />
makecache Download yum repository data to cache<br />
</pre><br />
<br />
<br />
=== INSTALL, REMOVE AND UPGRADE PACKAGES WITH YUM ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
install Install a package from a repository to your system<br />
yum install vsftpd<br />
Install the vsftpd package<br />
<br />
update Update one or all packages on your system<br />
yum update<br />
Update all packages with available updates<br />
yum update httpd<br />
Update the httpd package (if available)<br />
yum update --security<br />
Apply security-related package updates<br />
<br />
update-to Update one or all packages to a particular version<br />
<br />
upgrade Update packages taking obsoletes into account<br />
<br />
localinstall Install a package from a local file, http, or ftp<br />
yum localinstall abc-1-1.i686.rpm<br />
Install abc package from local directory<br />
yum localinstall http://myrepo/abc-1-1.i686.rpm<br />
Install abc from FTP site<br />
<br />
downgrade Downgrade a package to an earlier version<br />
yum downgrade abc<br />
Downgrade the abc package to an earlier version<br />
<br />
reinstall Reinstall the current version of a package<br />
yum reinstall util-linux<br />
Reinstall util-linux (to replace any deleted files)<br />
<br />
swap Remove one package and install another<br />
yum swap ftp lftp<br />
Remove ftp package and install lftp package<br />
<br />
erase Erase a package (and possibly dependencies) from<br />
your system<br />
yum remove vsftpd<br />
Remove the vsftpd package and dependencies<br />
<br />
remove Same as erase<br />
<br />
autoremove Same as erase, plus removes additional unneeded packages *<br />
yum autoremove httpd<br />
Remove httpd and other unneeded packages<br />
<br />
groupinstall Install all packages in the selected group<br />
yum groupinstall “Web server”<br />
Install Web Server packages<br />
</pre><br />
<br />
<br />
=== TROUBLESHOOT AND MAINTAIN YUM ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
check Check the local RPM database for problems (runs for a long time)<br />
<br />
history View and use yum transactions<br />
yum history list<br />
List all yum install, update and erase actions<br />
yum history info 3<br />
Show details of yum transaction 3<br />
yum history undo 3<br />
Undo the yum action from transaction 3<br />
yum history redo 3<br />
Redo the undone yum action from transaction 3<br />
<br />
clean Clear out cached package data<br />
yum clean packages<br />
Delete packages saved in cache<br />
yum clean all<br />
Clean out all packages and meta data from cache<br />
<br />
fssnapshot List LVM stapshots (helps roll back after package updates)<br />
<br />
fs Act on filesystem (prevent doc or language file install<br />
on minimal systems)<br />
yum fs filters<br />
List enabled filesystem filters<br />
yum fs documentation<br />
Filters all docs from being installed (careful!)<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Yum&diff=1741
Yum
2021-07-02T09:39:51Z
<p>Cbs: </p>
<hr />
<div>Yum-Repo management<br />
<br />
[[Nc24:YUM-Repo]]<br />
<br />
<br />
== Cheat sheet ==<br />
<br />
=== YUM QUERIES ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
help Display yum commands and options<br />
yum help<br />
Show yum subcommands and options<br />
<br />
Individual packages<br />
<br />
list List package names from repositories<br />
yum list available<br />
List all available packages<br />
yum list installed<br />
List all installed packages<br />
yum list all<br />
List installed and available packages<br />
yum list kernel<br />
List installed and available kernel packages<br />
<br />
info Display information about a package<br />
yum info vsftpd<br />
List info about vsftpd package<br />
<br />
deplist Display dependencies for a package<br />
yum deplist nfs-utils<br />
List dependencies and packages providing them<br />
<br />
provides Find packages that provide the queried file<br />
yum provides “*bin/top”<br />
Show package that contains top command<br />
yum provides “*/README.top”<br />
Show package containing README.top file<br />
<br />
search Search package names and descriptions for a term<br />
<br />
search nfs Find packages with 'nfs' in name or description<br />
<br />
updateinfo Get information about available package updates<br />
yum updateinfo security<br />
Get info on available security updates<br />
<br />
Groups of packages<br />
<br />
grouplist List names of installed and available package groups<br />
groupinfo Display description and contents of a package group<br />
yum groupinfo “Web Server”<br />
See packages in Web Server group<br />
<br />
check-update Query repositories for available package updates<br />
</pre><br />
<br />
<br />
=== MANAGE YUM REPOSITORIES ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
repolist Display enabled software repositories<br />
<br />
repoinfo Display information about enabled yum repositories *<br />
yum repoinfo rhel-7-server-rpms<br />
See info on rhel-7-server-rpms repo<br />
<br />
repo-pkgs Work with packages in a particular repository *<br />
yum repo-pkgs my-rpms list<br />
List packages from my-rpms repo<br />
yum repo-pkgs my-rpms install<br />
Install all packages from my-rpms repo<br />
yum repo-pkgs my-rpms remove<br />
Remove all packages from my-rpms repo<br />
<br />
makecache Download yum repository data to cache<br />
</pre><br />
<br />
<br />
=== INSTALL, REMOVE AND UPGRADE PACKAGES WITH YUM ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
install Install a package from a repository to your system<br />
yum install vsftpd<br />
Install the vsftpd package<br />
<br />
update Update one or all packages on your system<br />
yum update<br />
Update all packages with available updates<br />
yum update httpd<br />
Update the httpd package (if available)<br />
yum update --security<br />
Apply security-related package updates<br />
<br />
update-to Update one or all packages to a particular version<br />
<br />
upgrade Update packages taking obsoletes into account<br />
<br />
localinstall Install a package from a local file, http, or ftp<br />
yum localinstall abc-1-1.i686.rpm<br />
Install abc package from local directory<br />
yum localinstall http://myrepo/abc-1-1.i686.rpm<br />
Install abc from FTP site<br />
<br />
downgrade Downgrade a package to an earlier version<br />
yum downgrade abc<br />
Downgrade the abc package to an earlier version<br />
<br />
reinstall Reinstall the current version of a package<br />
yum reinstall util-linux<br />
Reinstall util-linux (to replace any deleted files)<br />
<br />
swap Remove one package and install another<br />
yum swap ftp lftp<br />
Remove ftp package and install lftp package<br />
<br />
erase Erase a package (and possibly dependencies) from<br />
your system<br />
yum remove vsftpd<br />
Remove the vsftpd package and dependencies<br />
<br />
remove Same as erase<br />
<br />
autoremove Same as erase, plus removes additional unneeded packages *<br />
yum autoremove httpd<br />
Remove httpd and other unneeded packages<br />
<br />
groupinstall Install all packages in the selected group<br />
yum groupinstall “Web server”<br />
Install Web Server packages<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Yum&diff=1740
Yum
2021-07-02T09:31:42Z
<p>Cbs: </p>
<hr />
<div>Yum-Repo management<br />
<br />
[[Nc24:YUM-Repo]]<br />
<br />
<br />
== Cheat sheet ==<br />
<br />
=== YUM QUERIES ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
help Display yum commands and options<br />
yum help<br />
Show yum subcommands and options<br />
<br />
Individual packages<br />
<br />
list List package names from repositories<br />
yum list available<br />
List all available packages<br />
yum list installed<br />
List all installed packages<br />
yum list all<br />
List installed and available packages<br />
yum list kernel<br />
List installed and available kernel packages<br />
<br />
info Display information about a package<br />
yum info vsftpd<br />
List info about vsftpd package<br />
<br />
deplist Display dependencies for a package<br />
yum deplist nfs-utils<br />
List dependencies and packages providing them<br />
<br />
provides Find packages that provide the queried file<br />
yum provides “*bin/top”<br />
Show package that contains top command<br />
yum provides “*/README.top”<br />
Show package containing README.top file<br />
<br />
search Search package names and descriptions for a term<br />
<br />
search nfs Find packages with 'nfs' in name or description<br />
<br />
updateinfo Get information about available package updates<br />
yum updateinfo security<br />
Get info on available security updates<br />
<br />
Groups of packages<br />
<br />
grouplist List names of installed and available package groups<br />
groupinfo Display description and contents of a package group<br />
yum groupinfo “Web Server”<br />
See packages in Web Server group<br />
<br />
check-update Query repositories for available package updates<br />
</pre><br />
<br />
<br />
=== MANAGE YUM REPOSITORIES ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
repolist Display enabled software repositories<br />
<br />
repoinfo Display information about enabled yum repositories *<br />
yum repoinfo rhel-7-server-rpms<br />
See info on rhel-7-server-rpms repo<br />
<br />
repo-pkgs Work with packages in a particular repository *<br />
yum repo-pkgs my-rpms list<br />
List packages from my-rpms repo<br />
yum repo-pkgs my-rpms install<br />
Install all packages from my-rpms repo<br />
yum repo-pkgs my-rpms remove<br />
Remove all packages from my-rpms repo<br />
<br />
makecache Download yum repository data to cache<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Yum&diff=1739
Yum
2021-07-02T09:24:23Z
<p>Cbs: Die Seite wurde neu angelegt: „Yum-Repo management Nc24:YUM-Repo == Cheat sheet == === YUM QUERIES === <pre> SUBCOMMAND DESCRIPTIONS AND TASKS help Display yum commands and o…“</p>
<hr />
<div>Yum-Repo management<br />
<br />
[[Nc24:YUM-Repo]]<br />
<br />
<br />
== Cheat sheet ==<br />
<br />
=== YUM QUERIES ===<br />
<br />
<pre><br />
SUBCOMMAND DESCRIPTIONS AND TASKS<br />
<br />
help Display yum commands and options<br />
yum help<br />
Show yum subcommands and options<br />
<br />
Individual packages<br />
<br />
list List package names from repositories<br />
yum list available<br />
List all available packages<br />
yum list installed<br />
List all installed packages<br />
yum list all<br />
List installed and available packages<br />
yum list kernel<br />
List installed and available kernel packages<br />
<br />
info Display information about a package<br />
yum info vsftpd<br />
List info about vsftpd package<br />
<br />
deplist Display dependencies for a package<br />
yum deplist nfs-utils<br />
List dependencies and packages providing them<br />
<br />
provides Find packages that provide the queried file<br />
yum provides “*bin/top”<br />
Show package that contains top command<br />
yum provides “*/README.top”<br />
Show package containing README.top file<br />
<br />
search Search package names and descriptions for a term<br />
<br />
search nfs Find packages with 'nfs' in name or description<br />
<br />
updateinfo Get information about available package updates<br />
yum updateinfo security<br />
Get info on available security updates<br />
<br />
Groups of packages<br />
<br />
grouplist List names of installed and available package groups<br />
groupinfo Display description and contents of a package group<br />
yum groupinfo “Web Server”<br />
See packages in Web Server group<br />
<br />
check-update Query repositories for available package updates<br />
</pre><br />
<br />
<br />
=== MANAGE YUM REPOSITORIES ===<br />
<br />
<pre><br />
yadda<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1738
Windows/powershell
2021-06-23T12:36:26Z
<p>Cbs: /* setspn */</p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
<br />
setspn -S MsSQLsvr/<server> <server><br />
<br />
and <br />
<br />
setspn -S MsSQLsvr/<server>:1433 <server><br />
<br />
It will register MsSQLsrv SPN. (You need to register both <server> and <server>:1433<br />
<br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1737
Vmware
2021-06-11T09:07:11Z
<p>Cbs: </p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Run SCCM Tasks<br />
8) Run winlogbeat tasks<br />
9) Configure network / Connect NIC<br />
10) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
=== SCCM Tasks ===<br />
<br />
<pre><br />
$scriptblock = {<br />
net stop CCMEXEC<br />
del C:\Windows\SMSCFG.INI<br />
certutil -delstore SMS SMS<br />
C:\Windows\ccmsetup\ccmsetup.exe /uninstall<br />
C:\ITutils\Setup\ClientHealth\ccmsetup.exe SMSSITECODE=ARI DNSSUFFIX=Arifleet.com<br />
}<br />
</pre><br />
And then:<br />
<br />
<pre><br />
foreach( $vm in (get-vm *dev-v0001*).name ) {<br />
echo "Trying $vm"<br />
Invoke-Command -ComputerName $vm -ScriptBlock $scriptblock<br />
echo ""<br />
}<br />
</pre><br />
<br />
=== Winlogbeat Tasks ===<br />
<br />
rm C:\ProgramData\winlogbeat\meta.json<br />
<br />
<br />
<br />
== Snippets ==<br />
<br />
=== Get network interface connection state ===<br />
<br />
<pre><br />
get-vm | %{<br />
$strVMName = $_.Name; Get-NetworkAdapter -VM $_ |<br />
select @{n="VMName"; e={$strVMName}},Name,NetworkName,ConnectionState<br />
} | ?{$_.ConnectionState.StartConnected -eq $false}<br />
<br />
VMName Name NetworkName ConnectionState<br />
------ ---- ----------- ---------------<br />
51KOBDEV-V00017_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
51KOBDEV-V00027_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
51KOBDEV-V00016_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
</pre><br />
<br />
Set StartConnected:<br />
<br />
<pre><br />
get-vm | %{ Get-NetworkAdapter -VM $_ } | ?{$_.ConnectionState.StartConnected -eq $false} | Set-NetworkAdapter -StartConnected $true -confirm:$false<br />
</pre><br />
<br />
<br />
=== Get performance counters ===<br />
<br />
$allCounters = get-vm 51KOBDEV-V0* | get-stat -Stat cpu.usagemhz.average -Start 01.05.2021<br />
<br />
use cpu.usage.average above to get % values<br />
<br />
$allCounters | Measure-Object "Value" -Sum | %{ $($_.Sum)/$($_.Count) }<br />
2187,85404221426<br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
</pre><br />
<br />
<br />
Run this script in ESXi 6.x to obtain the driver version and Firmware for all HBAs in the system:<br/><br />
<br />
<pre><br />
for name in `vmkchdev -l | grep vmhba | awk '{print$5}'`;do echo $name ; echo "VID :DID SVID:SDID"; vmkchdev -l | grep $name | awk '{print $2 , $3}';printf "Driver: ";echo `esxcfg-scsidevs -a | grep $name |awk '{print $2}'`;vmkload_mod -s `esxcfg-scsidevs -a | grep $name|awk '{print $2}'` |grep -i version;echo `lspci -vvv | grep $name | awk '{print $1=$NF="",$0}'`;printf "\n";done<br />
</pre><br />
<br />
<br />
=== list interfaces ===<br />
esxcli network ip interface list<br />
<br />
<br />
<br />
== Shrink VCenter Server Disks ==<br />
<br />
Create a Clone of your running VCenter server (just in case!)<br />
<br />
SSH root@vcenter-server<br />
<br />
# service-control --stop --all<br />
<br />
<br />
List disks - We want to reduce 'seat' partition<br />
<br />
<pre><br />
# df -h<br />
Filesystem Size Used Avail Use% Mounted on<br />
devtmpfs 4.9G 0 4.9G 0% /dev<br />
tmpfs 4.9G 588K 4.9G 1% /dev/shm<br />
tmpfs 4.9G 696K 4.9G 1% /run<br />
tmpfs 4.9G 0 4.9G 0% /sys/fs/cgroup<br />
/dev/sda3 11G 4.4G 5.7G 44% /<br />
tmpfs 4.9G 1.6M 4.9G 1% /tmp<br />
/dev/sda1 120M 34M 78M 31% /boot<br />
/dev/mapper/core_vg-core 25G 44M 24G 1% /storage/core<br />
/dev/mapper/log_vg-log 9.8G 72M 9.2G 1% /storage/log<br />
/dev/mapper/db_vg-db 9.8G 101M 9.1G 2% /storage/db<br />
/dev/mapper/dblog_vg-dblog 15G 86M 14G 1% /storage/dblog<br />
/dev/mapper/seat_vg-seat 296G 67M 283G 1% /storage/seat <br />
[...]<br />
</pre><br />
<br />
<br />
UnMount the disk<br />
<br />
# umount /storage/seat<br />
<br />
<br />
Check Filesystem<br />
<br />
# e2fsck -f /dev/mapper/seat_vg-seat<br />
<br />
<br />
Resize the filesystem - We want 20GB disk as result.<br/><br />
(resize filesystem to <disk size>-2GB = 18GB)<br />
<br />
# resize2fs /dev/mapper/seat_vg-seat 18G<br />
<br />
<br />
Resize logical volume to <disk size>-1GB = 19GB<br />
<br />
# lvreduce -L 19G /dev/seat_vg/seat<br />
<br />
<br />
At this point login to the VMHost (were vcenter is located on)<br/><br />
and add a new 20GB disk to VCenter server.<br />
<br />
Trigger SCSI rescan:<br />
<br />
# echo "- - -" > /sys/class/scsi_host/host<X>/scan<br />
<br />
If you want to figure out the host adapter that is in use for virtual disks, run "lsscsi".<br />
<br />
<br />
Get name of new disk:<br />
<br />
# dmesg | grep -i scsi<br />
...<br />
[58915.572852] scsi 3:0:2:0: Direct-Access VMware Virtual disk 1.0 PQ: 0 ANSI: 2<br />
[58915.573970] sd 3:0:1:0: [sdn] Attached SCSI disk<br />
...<br />
<br />
<br />
Put new disk to VG and remove the old (big) disk:<br />
<br />
# pvcreate /dev/sdn<br />
<br />
# vgextend seat_vg /dev/sdn<br />
<br />
<br />
Now check both disks belong to the VG:<br />
<br />
<pre><br />
# pvs |grep seat_vg<br />
/dev/sdh seat_vg lvm2 a-- 299.99g 279.99g<br />
/dev/sdn seat_vg lvm2 a-- 24.99g 24.99g<br />
</pre><br />
<br />
<br />
Move physical allocation from old (big) disk to new disk:<br />
<br />
# pvmove /dev/sdh /dev/sdn<br />
<br />
<br />
Verify /dev/sdh is empty:<br />
<br />
<pre><br />
# pvdisplay -m /dev/sdh<br />
--- Physical volume ---<br />
PV Name /dev/sdh<br />
VG Name seat_vg<br />
PV Size 300.00 GiB / not usable 7.00 MiB<br />
Allocatable yes<br />
PE Size 8.00 MiB<br />
Total PE 38399<br />
Free PE 38399<br />
Allocated PE 0 <---- Alloc needs to be '0'<br />
PV UUID V7lkDg-Fxyr-qX4x-d3oi-KhNO-XZyT-EHgibI<br />
<br />
--- Physical Segments ---<br />
Physical extent 0 to 38398:<br />
FREE<br />
</pre><br />
<br />
<br />
Remove old big disk now:<br />
<br />
<pre><br />
# vgreduce seat_vg /dev/sdh<br />
<br />
# pvremove /dev/sdh<br />
</pre><br />
<br />
<br />
Resize all volumes to virtual disk size:<br />
<br />
# /usr/lib/applmgmt/support/scripts/autogrow.sh<br />
<br />
<br />
Delete Disk from vcenter (make sure you delete the correct disk!!!)<br />
<br />
# lsscsi |grep sdh<br />
[2:0:8:0] disk VMware Virtual disk 1.0 /dev/sdh<br />
<br />
Controller0-Disk8: [2:'''0:8''':0]<br/><br />
Delete SCSI Disk 0:8 from VMWare - Reboot VCenter<br />
<br />
Delete the VCenter clone</div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1736
Windows/powershell
2021-05-20T11:07:00Z
<p>Cbs: </p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
=== Filter log by EventID ===<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
=== Get reboot source/reason ===<br />
<br />
Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074} | Format-Table -wrap<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1735
Vmware
2021-05-18T09:17:58Z
<p>Cbs: /* Snippets */</p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Run SCCM Tasks<br />
8) Run winlogbeat tasks<br />
9) Configure network / Connect NIC<br />
10) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
=== SCCM Tasks ===<br />
<br />
<pre><br />
$scriptblock = {<br />
net stop CCMEXEC<br />
del C:\Windows\SMSCFG.INI<br />
certutil -delstore SMS SMS<br />
C:\Windows\ccmsetup\ccmsetup.exe /uninstall<br />
C:\ITutils\Setup\ClientHealth\ccmsetup.exe SMSSITECODE=ARI DNSSUFFIX=Arifleet.com<br />
}<br />
</pre><br />
And then:<br />
<br />
<pre><br />
foreach( $vm in (get-vm *dev-v0001*).name ) {<br />
echo "Trying $vm"<br />
Invoke-Command -ComputerName $vm -ScriptBlock $scriptblock<br />
echo ""<br />
}<br />
</pre><br />
<br />
=== Winlogbeat Tasks ===<br />
<br />
rm C:\ProgramData\winlogbeat\meta.json<br />
<br />
<br />
<br />
== Snippets ==<br />
<br />
=== Get network interface connection state ===<br />
<br />
<pre><br />
get-vm | %{<br />
$strVMName = $_.Name; Get-NetworkAdapter -VM $_ |<br />
select @{n="VMName"; e={$strVMName}},Name,NetworkName,ConnectionState<br />
} | ?{$_.ConnectionState.StartConnected -eq $false}<br />
<br />
VMName Name NetworkName ConnectionState<br />
------ ---- ----------- ---------------<br />
51KOBDEV-V00017_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
51KOBDEV-V00027_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
51KOBDEV-V00016_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
</pre><br />
<br />
Set StartConnected:<br />
<br />
<pre><br />
get-vm | %{ Get-NetworkAdapter -VM $_ } | ?{$_.ConnectionState.StartConnected -eq $false} | Set-NetworkAdapter -StartConnected $true -confirm:$false<br />
</pre><br />
<br />
<br />
=== Get performance counters ===<br />
<br />
$allCounters = get-vm 51KOBDEV-V0* | get-stat -Stat cpu.usagemhz.average -Start 01.05.2021<br />
<br />
use cpu.usage.average above to get % values<br />
<br />
$allCounters | Measure-Object "Value" -Sum | %{ $($_.Sum)/$($_.Count) }<br />
2187,85404221426<br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
</pre><br />
<br />
<br />
Run this script in ESXi 6.x to obtain the driver version and Firmware for all HBAs in the system:<br/><br />
<br />
<pre><br />
for name in `vmkchdev -l | grep vmhba | awk '{print$5}'`;do echo $name ; echo "VID :DID SVID:SDID"; vmkchdev -l | grep $name | awk '{print $2 , $3}';printf "Driver: ";echo `esxcfg-scsidevs -a | grep $name |awk '{print $2}'`;vmkload_mod -s `esxcfg-scsidevs -a | grep $name|awk '{print $2}'` |grep -i version;echo `lspci -vvv | grep $name | awk '{print $1=$NF="",$0}'`;printf "\n";done<br />
</pre><br />
<br />
<br />
=== list interfaces ===<br />
esxcli network ip interface list</div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1734
Vmware
2021-05-18T08:03:17Z
<p>Cbs: </p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Run SCCM Tasks<br />
8) Run winlogbeat tasks<br />
9) Configure network / Connect NIC<br />
10) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
=== SCCM Tasks ===<br />
<br />
<pre><br />
$scriptblock = {<br />
net stop CCMEXEC<br />
del C:\Windows\SMSCFG.INI<br />
certutil -delstore SMS SMS<br />
C:\Windows\ccmsetup\ccmsetup.exe /uninstall<br />
C:\ITutils\Setup\ClientHealth\ccmsetup.exe SMSSITECODE=ARI DNSSUFFIX=Arifleet.com<br />
}<br />
</pre><br />
And then:<br />
<br />
<pre><br />
foreach( $vm in (get-vm *dev-v0001*).name ) {<br />
echo "Trying $vm"<br />
Invoke-Command -ComputerName $vm -ScriptBlock $scriptblock<br />
echo ""<br />
}<br />
</pre><br />
<br />
=== Winlogbeat Tasks ===<br />
<br />
rm C:\ProgramData\winlogbeat\meta.json<br />
<br />
<br />
<br />
== Snippets ==<br />
<br />
=== Get connection state ===<br />
<br />
<pre><br />
get-vm | %{<br />
$strVMName = $_.Name; Get-NetworkAdapter -VM $_ |<br />
select @{n="VMName"; e={$strVMName}},Name,NetworkName,ConnectionState<br />
} | ?{$_.ConnectionState.StartConnected -eq $false}<br />
<br />
VMName Name NetworkName ConnectionState<br />
------ ---- ----------- ---------------<br />
51KOBDEV-V00017_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
51KOBDEV-V00027_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
51KOBDEV-V00016_replica Network adapter 1 10.219.106.0_24 Connected, GuestControl, NoStartConnected<br />
</pre><br />
<br />
Set StartConnected:<br />
<br />
<pre><br />
get-vm | %{ Get-NetworkAdapter -VM $_ } | ?{$_.ConnectionState.StartConnected -eq $false} | Set-NetworkAdapter -StartConnected $true -confirm:$false<br />
</pre><br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
</pre><br />
<br />
<br />
Run this script in ESXi 6.x to obtain the driver version and Firmware for all HBAs in the system:<br/><br />
<br />
<pre><br />
for name in `vmkchdev -l | grep vmhba | awk '{print$5}'`;do echo $name ; echo "VID :DID SVID:SDID"; vmkchdev -l | grep $name | awk '{print $2 , $3}';printf "Driver: ";echo `esxcfg-scsidevs -a | grep $name |awk '{print $2}'`;vmkload_mod -s `esxcfg-scsidevs -a | grep $name|awk '{print $2}'` |grep -i version;echo `lspci -vvv | grep $name | awk '{print $1=$NF="",$0}'`;printf "\n";done<br />
</pre><br />
<br />
<br />
=== list interfaces ===<br />
esxcli network ip interface list</div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1733
Vmware
2021-05-10T08:53:02Z
<p>Cbs: /* SCCM Tasks */</p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Run SCCM Tasks<br />
8) Run winlogbeat tasks<br />
9) Configure network / Connect NIC<br />
10) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
=== SCCM Tasks ===<br />
<br />
<pre><br />
$scriptblock = {<br />
net stop CCMEXEC<br />
del C:\Windows\SMSCFG.INI<br />
certutil -delstore SMS SMS<br />
C:\Windows\ccmsetup\ccmsetup.exe /uninstall<br />
C:\ITutils\Setup\ClientHealth\ccmsetup.exe SMSSITECODE=ARI DNSSUFFIX=Arifleet.com<br />
}<br />
</pre><br />
And then:<br />
<br />
<pre><br />
foreach( $vm in (get-vm *dev-v0001*).name ) {<br />
echo "Trying $vm"<br />
Invoke-Command -ComputerName $vm -ScriptBlock $scriptblock<br />
echo ""<br />
}<br />
</pre><br />
<br />
=== Winlogbeat Tasks ===<br />
<br />
rm C:\ProgramData\winlogbeat\meta.json<br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
</pre><br />
<br />
<br />
Run this script in ESXi 6.x to obtain the driver version and Firmware for all HBAs in the system:<br/><br />
<br />
<pre><br />
for name in `vmkchdev -l | grep vmhba | awk '{print$5}'`;do echo $name ; echo "VID :DID SVID:SDID"; vmkchdev -l | grep $name | awk '{print $2 , $3}';printf "Driver: ";echo `esxcfg-scsidevs -a | grep $name |awk '{print $2}'`;vmkload_mod -s `esxcfg-scsidevs -a | grep $name|awk '{print $2}'` |grep -i version;echo `lspci -vvv | grep $name | awk '{print $1=$NF="",$0}'`;printf "\n";done<br />
</pre><br />
<br />
<br />
=== list interfaces ===<br />
esxcli network ip interface list</div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1732
Vmware
2021-05-10T08:50:50Z
<p>Cbs: /* Clone System */</p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Run SCCM Tasks<br />
8) Run winlogbeat tasks<br />
9) Configure network / Connect NIC<br />
10) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
=== SCCM Tasks ===<br />
<br />
$scriptblock = {<br />
net stop CCMEXEC<br />
del C:\Windows\SMSCFG.INI<br />
certutil -delstore SMS SMS<br />
C:\Windows\ccmsetup\ccmsetup.exe /uninstall<br />
C:\ITutils\Setup\ClientHealth\ccmsetup.exe SMSSITECODE=ARI DNSSUFFIX=Arifleet.com<br />
}<br />
<br />
And then:<br />
<br />
foreach( $vm in (get-vm *dev-v0001*).name ) {<br />
echo "Trying $vm"<br />
Invoke-Command -ComputerName $vm -ScriptBlock $scriptblock<br />
echo ""<br />
}<br />
<br />
<br />
=== Winlogbeat Tasks ===<br />
<br />
rm C:\ProgramData\winlogbeat\meta.json<br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
</pre><br />
<br />
<br />
Run this script in ESXi 6.x to obtain the driver version and Firmware for all HBAs in the system:<br/><br />
<br />
<pre><br />
for name in `vmkchdev -l | grep vmhba | awk '{print$5}'`;do echo $name ; echo "VID :DID SVID:SDID"; vmkchdev -l | grep $name | awk '{print $2 , $3}';printf "Driver: ";echo `esxcfg-scsidevs -a | grep $name |awk '{print $2}'`;vmkload_mod -s `esxcfg-scsidevs -a | grep $name|awk '{print $2}'` |grep -i version;echo `lspci -vvv | grep $name | awk '{print $1=$NF="",$0}'`;printf "\n";done<br />
</pre><br />
<br />
<br />
=== list interfaces ===<br />
esxcli network ip interface list</div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1731
Vmware
2021-05-03T07:10:31Z
<p>Cbs: /* ESXi upgrade */</p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Configure network / Connect NIC<br />
8) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
</pre><br />
<br />
<br />
Run this script in ESXi 6.x to obtain the driver version and Firmware for all HBAs in the system:<br/><br />
<br />
<pre><br />
for name in `vmkchdev -l | grep vmhba | awk '{print$5}'`;do echo $name ; echo "VID :DID SVID:SDID"; vmkchdev -l | grep $name | awk '{print $2 , $3}';printf "Driver: ";echo `esxcfg-scsidevs -a | grep $name |awk '{print $2}'`;vmkload_mod -s `esxcfg-scsidevs -a | grep $name|awk '{print $2}'` |grep -i version;echo `lspci -vvv | grep $name | awk '{print $1=$NF="",$0}'`;printf "\n";done<br />
</pre><br />
<br />
<br />
=== list interfaces ===<br />
esxcli network ip interface list</div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1730
Vmware
2021-04-22T10:35:00Z
<p>Cbs: /* ESXi upgrade */</p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Configure network / Connect NIC<br />
8) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
</pre><br />
<br />
<br />
Run this script in ESXi 6.x to obtain the driver version and Firmware for all HBAs in the system:<br/><br />
<br />
<pre><br />
for name in `vmkchdev -l | grep vmhba | awk '{print$5}'`;do echo $name ; echo "VID :DID SVID:SDID"; vmkchdev -l | grep $name | awk '{print $2 , $3}';printf "Driver: ";echo `esxcfg-scsidevs -a | grep $name |awk '{print $2}'`;vmkload_mod -s `esxcfg-scsidevs -a | grep $name|awk '{print $2}'` |grep -i version;echo `lspci -vvv | grep $name | awk '{print $1=$NF="",$0}'`;printf "\n";done<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Vmware&diff=1729
Vmware
2021-04-19T07:56:54Z
<p>Cbs: </p>
<hr />
<div><br />
<br />
== Clone System ==<br />
<br />
<pre><br />
1) Shut down the VM<br />
2) Clone the VM<br />
3) Disconnect the NIC<br />
4) Bring up the VM<br />
Win10) Run uninstall.ps1 script below, to uninstall unprovisioned AppStore Apps<br />
5) Run sysprep /generalize<br />
cd %WINDIR%\system32\sysprep; ./sysprep /generalize<br />
6) Assign new workstation name / admin pw<br />
7) Configure network / Connect NIC<br />
8) Join to domain<br />
</pre><br />
<br />
=== Uninstall.ps1 ===<br />
<br />
<pre><br />
# Get the list of provisioned packages<br />
$provisioned = Get-AppxProvisionedPackage -online<br />
<br />
# Check each installed app<br />
$count = 0<br />
<br />
for ($i=1; $i -ile 2; $i++) {<br />
# Check each app (two loops just in case there are dependencies that can't be removed until the<br />
# main app is removed)<br />
Get-AppxPackage | ? {$_.SignatureKind -ne 'System'} | ForEach-Object {<br />
$current = $_<br />
$found = $provisioned | ? {$_.DisplayName -eq $current.Name -and $_.Version -eq $current.Version}<br />
if ($found.Count -eq 0)<br />
{<br />
Write-Host "$($current.Name) version $($current.Version) is not provisioned, removing."<br />
Remove-AppxPackage -Package $current.PackageFullName<br />
$count++<br />
}<br />
}<br />
}<br />
</pre><br />
<br />
<br />
== ESXi upgrade ==<br />
<br />
=== Get list of storage adapters ===<br />
<br />
<pre><br />
esxcli storage core adapter list<br />
<br />
HBA Name Driver Link State UID Capabilities <br />
-------- ---------- ---------- -------------------------------------- ------------------<br />
vmhba0 nhpsa link-n/a sas.50014380361bab70 <br />
vmhba1 qlnativefc link-up fc.500143802318ab7b:500143802318ab7a Data Integrity, Se<br />
vmhba2 qlnativefc link-up fc.500143802318a82f:500143802318a82e Data Integrity, Se<br />
vmhba32 bnx2i unbound iscsi.vmhba32 Second Level Lun I<br />
vmhba33 bnx2i unbound iscsi.vmhba33 Second Level Lun I<br />
vmhba34 bnx2fc link-down fcoe.10003ca82a244d11:20003ca82a244d11 Second Level Lun I<br />
vmhba35 bnx2fc link-down fcoe.10003ca82a244d15:20003ca82a244d15 Second Level Lun I<br />
<br />
cat /proc/scsi/bnx2fc/7 | grep 'Host Device Name'<br />
Host Device Name vmhba34<br />
<br />
<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/exchange&diff=1728
Windows/exchange
2021-04-16T14:18:03Z
<p>Cbs: /* Search Mailbox content */</p>
<hr />
<div><br />
== PowerShell ==<br />
<br />
powershell commands<br />
<br />
<br />
=== possible access rights ===<br />
<br />
<pre><br />
The Access Rights parameters are as below:<br />
<br />
ReadItems: The user has the right to read items within the specified folder.<br />
CreateItems The user has the right to create items within the specified folder.<br />
EditOwnedItems The user has the right to edit the items that the user owns in the specified folder.<br />
DeleteOwnedItems The user has the right to delete items that the user owns in the specified folder.<br />
EditAllItems The user has the right to edit all items in the specified folder.<br />
DeleteAllItems The user has the right to delete all items in the specified folder.<br />
CreateSubfolders The user has the right to create subfolders in the specified folder.<br />
FolderOwner The user is the owner of the specified folder. The user has the right to view and move the folder and create subfolders. The user can’t read items, edit items, delete items, or create items.<br />
FolderContact The user is the contact for the specified public folder.<br />
FolderVisible The user can view the specified folder, but can’t read or edit items within the specified public folder.<br />
<br />
The Roles with which we can provide the access rights are as below:<br />
<br />
None FolderVisible<br />
Owner CreateItems, ReadItems, CreateSubfolders, FolderOwner, FolderContact, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingEditor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
Editor CreateItems, ReadItems, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingAuthor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
Author CreateItems, ReadItems, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
NonEditingAuthor CreateItems, ReadItems, FolderVisible<br />
Reviewer ReadItems, FolderVisible<br />
Contributor CreateItems, FolderVisible<br />
<br />
Ref: http://technet.microsoft.com/en-us/library/dd298062(v=exchg.150).aspx<br />
<br />
The following roles apply specifically to calendar folders:<br />
<br />
AvailabilityOnly View only availability data<br />
LimitedDetails View availability data with subject and location<br />
</pre><br />
<br />
<br />
=== create mailbox ===<br />
<br />
Create a new mailbox<br />
<br />
New-Mailbox -Name 'prospect NL' -Alias 'prospect.nl' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Rooms and Equipment' \<br />
-UserPrincipalName 'prospect.nl@arifleet.com' -SamAccountName 'prospect.nl' -FirstName 'prospect' -Initials '' -LastName 'NL' \<br />
-Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Stuttgart Mailbox DB One'<br />
<br />
<br />
=== create linked mailbox ===<br />
<br />
New-Mailbox -Name 'Koroch, Ernst' -Alias 'ekoroch' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Users' -UserPrincipalName \<br />
'ekoroch@arifleet.com' -SamAccountName 'ekoroch' -FirstName 'Ernst' -Initials '' -LastName 'Koroch' -Database 'Stuttgart Mailbox DB One' \<br />
-LinkedMasterAccount 'fleetservices\ekoroch' -LinkedDomainController 'dc03.fleetservices.intra' -LinkedCredential \<br />
'System.Management.Automation.PSCredential'<br />
<br />
<br />
=== Repair Mailbox ===<br />
<br />
see: [https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx]<br />
<br />
New-MailboxRepairRequest -Mailbox <Emailaddress> -CorruptionType SearchFolder,AggregateCounts,ProvisionedFolder,FolderView [-DetectOnly]<br />
<br />
<br />
=== Email-Enable AD Group ===<br />
<br />
Enable-DistributionGroup <ADGroupID> -PrimarySmtpAddress yadda@domain.tld<br />
<br />
<br />
=== Email-Enable AD User ===<br />
<br />
Enable-Mailbox <UserID> -PrimarySmtpAddress yadda@domain.tld -displayname "Yadda, Yadda"<br />
<br />
<br />
=== add mailbox permissions ===<br />
<br />
Add full access to mailbox 'mailbox@arifleet.de' for user 'DOMAIN\user': <br />
<br />
Add-MailboxPermission -Identity mailbox@arifleet.de -User DOMAIN\user -AccessRights Fullaccess -InheritanceType All<br />
<br />
-AccessRights <right> <br/><br />
where <right> may be<br />
<br />
FullAccess<br />
ExternalAccount<br />
DeleteItem<br />
ReadPermission<br />
ChangePermission<br />
ChangeOwner<br />
<br />
disable auto-mapping of <br />
<br />
-Automapping $false<br />
<br />
<br />
=== remove mailbox permissions ===<br />
<br />
remove-MailboxPermission -Identity mailbox@arifleet.de -user domari\user -AccessRights Fullaccess -inheritance all<br />
<br />
<br />
=== add/remove 'Send as' permissions ===<br />
<br />
Add-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
You can grant the permissions by using Active Directory Users & Computers. Simply open the properties of the group, switch to the Security tab, add the mailbox user or group, and then tick the Send As box and apply the change. After making this change you may notice that it does not take effect for up to 2 hours. This is due to caching on the Exchange servers. Though you can speed up the change by restarting the Information Store that is obviously not going to be practical in most production environments, so you’ll often find that you just need to wait.<br />
<br />
Remove-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
<br />
==== 'Send as'/'SendOnBehalf' Distributiongroups ====<br />
<br />
Set-DistributionGroup <DistributionGroupName> -GrantSendOnBehalfTo USER@arifleet.com<br />
<br />
and sendOnBehalf for Distributiongroups<br />
<br />
<br />
<br />
==== SentItem Configuration ====<br />
<br />
Until Exchange 2010:<br />
<br />
Set-MailboxSentItemsConfiguration <ALIAS> -SendAsItemsCopiedTo SenderAndFrom<br />
<br />
Exchange 2016:<br />
<br />
Set-Mailbox -identity <UPN> [-DomainController <HOSTNAME>] -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true<br />
<br />
<br />
=== add mailbox folder permissions ===<br />
<br />
Add-MailboxFolderPermission -Identity poolcar@netcar24.com:\Calendar -user csteidl@arifleet.com -AccessRights [[Windows/exchange#possible_access_rights|<see RIGHTS>]]<br />
<br />
Set default-rights for ressource mailboxes (to show up subjects a.s.o.):<br />
<br />
Set-MailboxFolderPermission meetingroom:\Calendar -User Default -AccessRights Reviewer<br />
<br />
=== get mailbox permissions ===<br />
<br />
get permissions of fhess on mailbox prospect.be<br />
<br />
Get-MailboxPermission -Identity prospect.be@arifleet.com -User "fhess"<br />
<br />
<br />
get folder permissions<br />
<br />
get-mailboxfolderpermission -identity fhess<br />
<br />
<br />
get UPN of users<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.User.ADRecipient.UserPrincipalName }<br />
<br />
<br />
get full user details<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.identity.adrecipient.identity }<br />
<br />
<br />
<br />
=== Find permissions granted to spec. users ===<br />
<br />
Get-Mailbox -RecipientType 'UserMailbox' -ResultSize Unlimited | Get-MailboxPermission | where { $_.user.tostring() -eq "DOMAIN\username" -and $_.IsInherited -eq $false }<br />
<br />
<br />
<br />
=== enable autoreply / vacation message ===<br />
<br />
set the message (optionally) and enable auto reply<br />
<br />
$message = get-content message.txt<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState enabled \<br />
-ExternalAudience <none/all/known> \<br />
-InternalMessage "$message" \<br />
-ExternalMessage "$message"<br />
<br />
<br />
=== disable auto-reply / vacation message ===<br />
<br />
disable auto reply<br />
<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState disabled<br />
<br />
<br />
=== Retention policies ===<br />
<br />
create server side retention policies<br />
<br />
<br />
==== Create Retention Policy Tag ====<br />
<br />
New-RetentionPolicyTag "ARI STG - Delete all 180 days" -Type All -Comment "Deletes all items older 180 days" -RetentionEnabled $true \<br />
-AgeLimitForRetention 180 -RetentionAction DeleteAndAllowRecovery<br />
<br />
RetentionAction: MoveToFolder, MoveToDeletedItems, DeleteAndAllowRecovery, PermanentlyDelete, MoveToArchive<br />
<br />
<br />
==== Create Retention Policy ====<br />
<br />
New-RetentionPolicy "ARI STG - Delete ALL items older 180 days" -RetentionPolicyTagLinks "ARI STG - Delete all 180 days"<br />
<br />
Activate policy by: Open Mailbox Properties --> Mailbox Settings --> Messaging Records Mgmt --> Apply Retention policy<br />
<br />
<br />
=== get distribution group members ===<br />
<br />
get-distributiongroupmember <group><br />
<br />
get-distributiongroupmember mailaddress@arifleet.de<br />
<br />
<br />
=== get users by filter and add to distributiongroup ===<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -ne 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -eq 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
<br />
<br />
=== Get Mailbox by ExchangeGuid/Mapi-session ===<br />
<br />
get-mailbox -ResultSize unlimited | where {$_.ExchangeGuid -eq "265182e3-a31c-4a9f-e38e-687f5a7c2d6b"}<br />
<br />
<br />
=== Get Mailbox by Ressource type ===<br />
<br />
<br />
Get-Mailbox -RecipientTypeDetails RoomMailbox<br />
<br />
Get-Mailbox -RecipientTypeDetails EquipmentMailbox<br />
<br />
<br />
=== Get Mail Public folder ===<br />
<br />
Get-MailPublicFolder helpdesk@sub.domain.com | Get-PublicFolder [| Select *]<br />
<br />
<br />
=== Logging ===<br />
<br />
further logfiles can be found here:<br />
<br />
C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\ProtocolLog<br />
<br />
<br />
==== Track accross multiple servers ====<br />
<br />
get-transportserver<br />
<br />
<br />
e.g. that to "get-messagetrackinglog":<br />
<br />
get-transportserver | get-messagetrackinglog<br />
<br />
<br />
==== message tracking ====<br />
<br />
get-messagetrackinglog -Sender 'user@arifleet.de' -Start "5/04/2015 5:00:00 AM" -End "5/15/2015 8:30:00 AM"<br />
<br />
get-transportserver | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
get-transportservice | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
-Start "6/01/2015 5:00:00 AM" \<br />
-End "6/01/2015 10:30:00 AM" \<br />
-resultsize unlimited | ft -Wrap<br />
<br />
<pre><br />
-MessageSubject <String><br />
-Recipients <String[]><br />
-Start/-End (get-date).AddHours(-1).toString()<br />
-ResultSize Unlimited<br />
</pre><br />
<br />
some more examples:<br />
<br />
get-messagetrackinglog -Recipients:recipient@email.be -Start "6/8/2015 4:42:00 AM" -End "6/9/2015 9:52:00 PM" | Select *,{$_.Recipients} | export-csv .\maillog.csv<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | \<br />
where-object {$_.Recipients -like “*@gmail.com, *@yahoo.com” -AND $_.EventId -eq “Send”} |ft -auto >>C:\External mails.txt<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | sort -property Timestamp<br />
<br />
=== repair mailbox ===<br />
<br />
New-MailboxRepairRequest -Mailbox schaden@arifleet.de -CorruptionType SearchFolder<br />
<br />
<br />
-CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview<br />
-Archive Prueft Mailbox _und_ Archive<br />
-DetectOnly Prueft nur, keine Reparatur!<br />
<br />
Ergebnisse der Prüfung werden im Anwendungs Event-Log des Servers protokolliert. Die Events tragen die folgenden Ereignis-IDs:<br />
<br />
10044,10045,10046,10047,10048,10049,10050,10051,10059,10062<br />
<br />
mit einem rechtsklick auf 'Application' laesst dich das eventlog nach diesen ID's filtern.<br />
<br />
<br />
=== move mailbox between exchange-databases ===<br />
<br />
Move Mailboxes between exchange >= 2010 servers <br/><br />
the output is piped into 'ft' (format table) to get complete output and not stripped it...<br />
<br />
New-MoveRequest -Identity mailbox@arifleet.de -TargetDatabase ‘Whatever Database-Name 001’ | ft -AutoSize -Wrap<br />
<br />
create a batch<br />
<br />
Get-Mailbox -Database "Stuttgart Mailbox DB One" | Where-Object { $_.alias -like "jira*" } | New-MoveRequest -TargetDatabase [...]<br />
<br />
Options:<br />
<br />
-BadItemLimit 0<br />
-Suspend <br />
-SuspendComment "Resume after 11:00 p.m. PST"<br />
-SuspendWhenReadyToComplete<br />
-BatchName "Some Name to identify the Batch-Moves"<br />
<br />
get moverequest status:<br />
<br />
Get-MoveRequestStatistics "sadg"<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics | select DisplayName,alias,Status,TotalMailboxSize,PercentComplete| ft<br />
<br />
<br />
=== get Mailbox sizes ===<br />
<br />
Get-MailboxDatabase | Where-Object { $_.Name -like "STG*" } | Get-MailboxStatistics | sort -property TotalItemSize -desc \<br />
| select DisplayName,ItemCount,TotalItemSize,TotalDeletedItemSize |ft<br />
<br />
<br />
=== get database size ===<br />
<br />
Get-MailboxDatabase -status | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Sort-Object DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Where-Object { $_.name -like "STG*" } | Sort -property DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
=== Export Mailbox (Folder) ===<br />
<br />
New-MailboxExportRequest -mailbox schaden \<br />
-includefolders "******@arifleet.de/00 UNFALLORDNER ab 1.3.2011/Storopack R+V (*.***@*******.com) TK 150 \/ keine VK RA Schmid" \<br />
-filepath "\\stgwpvinfEXC01\g$\Storopack R+V (*.***@*******.com) TK 150_keine VK RA Schmid.pst"<br />
<br />
# be sure to mask e.g. '/' characters in foldernames with '\'<br />
# leave out '''-includefolders''' to export the entire mailbox<br/><br />
## add a '.../*' to -includefolders to include subfolders<br />
<br />
=== Search Mailbox content ===<br />
<br />
This one searches for all messages between 1/1/2017 and 12/31/2018 and creates copies of it within the Mailbox of targetmailbox into targetfolder:<br />
<br />
Search-Mailbox -Identity <USER-ID> -SearchQuery "received>=01/01/2017 AND received<=12/31/2018" -targetmailbox "<TARGET-USER-ID>" -targetfolder "SearchResults"<br />
<br />
SearchQuery examples: <br/><br />
<br />
"Subject:Project Hamilton"<br/><br />
"election OR candidate OR vote" - all messages that contain one of the words in whole message<br/><br />
<br />
=== set thumbnail-image ===<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
<br />
=== Import/Acivate new Certificate ===<br />
<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path c:\certificates\YOUR_CERTIFICATE.cer -Encoding byte -ReadCount 0))<br />
<br />
In case of encrypted .pfx or something like that:<br />
<br />
$pass = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -Password $pass -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path Webmail.pfx -Encoding byte -ReadCount 0))<br />
<br />
activate:<br />
<br />
Enable-ExchangeCertificate -Thumbprint 1234ae0567a72fccb75b1d0198628675333d010e -Services POP,IMAP,SMTP,IIS<br />
<br />
=== DAG/Cluster stuff ===<br />
<br />
Check who's master:<br />
<br />
Get-ClusterGroup EU-DAG<br />
<br />
<br />
Get detailed DAG info:<br />
<br />
Get-DatabaseAvailabilityGroup STG-DAG -status | fl<br />
<br />
<br />
Test replication health (do so on all cluster members):<br />
<br />
Test-ReplicationHealth -server EXC02<br />
<br />
<br />
Get mount status, copy/reply queue, Index state<br />
<br />
Get-MailboxDatabaseCopyStatus -server exc01<br />
<br />
<br />
Check Queues:<br />
<br />
get-queue -server stgwpvinfexc02<br />
<br />
<br />
Move queued messages to other server:<br />
<br />
Redirect-Message -Server Mailbox01 -Target Mailbox02<br />
<br />
<br />
Check service health (do so on all cluster members):<br/><br />
(test whether all the Microsoft Windows services that Exchange requires on a server have started)<br />
<br />
Test-servicehealth –server EXC02<br />
<br />
<br />
Test MapiConnectivity (Note: this will only test if the DB’s are mounted/active copy on the specific server):<br />
<br />
Test-MapiConnectivity -server EXC02<br />
<br />
<br />
Test/view replication:<br />
<br />
Get-MailboxdatabaseCopystatus -server EXC02<br />
<br />
<br />
Failover Cluster:<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup <br />
<br />
This will failover the 2 node cluster to the other node<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup -node EXC01<br />
<br />
This will failover the cluster to the node EXC01<br />
<br />
<br />
Move Databases:<br />
<br />
Move-ActiveMailboxDatabase DB3 -ActivateOnServer MBX4<br />
<br />
This example performs a switchover of the database DB3 to the Mailbox server MBX4. When the command completes, MBX4 hosts the active copy of DB3. Because the MountDialOverride parameter isn't specified, MBX4 mounts the database using a database auto mount dial setting of Lossless.<br />
<br />
<br />
Get-MailboxDatabase stg-* | Move-ActiveMailboxDatabase -ActivateOnServer MBX4<br />
<br />
Same as above, but moves all databases starting with 'STG-*' to MBX04<br />
<br />
<br />
Move-ActiveMailboxDatabase DB1 -ActivateOnServer MBX3 -MountDialOverride:GoodAvailability<br />
<br />
This example performs a switchover of the database DB1 to the Mailbox server MBX3. When the command completes, MBX3 hosts the active copy of DB1. Because the MountDialOverride parameter is specified with a value of Good Availability, MBX3 mounts the database using a database auto mount dial setting of GoodAvailability.<br />
<br />
== Outlook stuff ==<br />
<br />
=== get all add-ins ===<br />
<br />
Be aware that HKCU can only be grabbed if running in the user context!<br />
<br />
$searchScopes = "HKCU:\SOFTWARE\Microsoft\Office\Outlook\Addins","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins"<br />
$searchScopes | % {Get-ChildItem -Path $_ | % {Get-ItemProperty -Path $_.PSPath} | Select-Object @{n="Name";e={Split-Path $_.PSPath -leaf}},FriendlyName,Description} | Sort-Object -Unique -Property name<br />
<br />
<br />
== Transport stuff ==<br />
<br />
some stuff i used the GUI for<br />
<br />
<br />
=== Relay Configuration (GUI) ===<br />
<br />
Go:<br />
Server-Configuration --> Hub Transport --> Receive Connectors (Tab)<br />
<br />
- Select a valuable connector which matches you needs or create a new.<br />
- for me there was 'Relay internal' which was to allow anonymous connects from spec. hosts/nets --> Double-Click<br />
- Switch to 'Network'-Tab --> Add IP or rage to lower box.<br />
<br />
<br />
<br />
=== Max connection from single IP ===<br />
<br />
set-ReceiveConnector -Identity "exc03\Application_Relay" -MaxInboundConnectionPerSource 50<br />
<br />
sets the max inbound connections per source IP to 50 (default 20)<br />
<br />
<br />
<br />
=== Create an anonymous Receive Connector ===<br />
<br />
after you created an receive connector by GUI you will have to run:<br />
<br />
Get-ReceiveConnector "STGWPVINFEXC02\Application_Relay_Intern" | \<br />
Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"</div>
Cbs
https://schnallich.net/index.php?title=Hp/3PAR&diff=1727
Hp/3PAR
2021-03-15T09:47:53Z
<p>Cbs: /* AO Config */</p>
<hr />
<div><br />
== Diag ==<br />
<br />
=== Infos for HP (creating Case) ===<br />
<br />
> showsys <br />
> showsys -d<br />
<br />
(System Information inclusing serial)<br />
<br />
<br />
> servicemag status <br />
<br />
(shows if any drive was already evacuated)<br />
<br />
<br />
> checkhealth pd<br />
<br />
(do healthcheck of physical disks)<br />
<br />
<br />
> showpd -s <br />
> showpd -state<br />
> showpd -s -failed<br />
> showpd -failed -degraded<br />
<br />
(show the state of all drives)<br />
<br />
<br />
> showpd -i <br />
<br />
(show the drive inventory including type and serial)<br />
<br />
<br />
> showport -sfp [-d]<br />
<br />
(show the SFP ports and their status [detailed list])<br />
<br />
=== showsys (System info) ===<br />
<br />
Help page<br />
<br />
<pre><br />
showsys - Show system information.<br />
<br />
SYNTAX<br />
showsys [options]<br />
<br />
DESCRIPTION<br />
The showsys command displays the HP 3PAR Storage system properties such as<br />
a system name, serial number, and system capacity information.<br />
<br />
AUTHORITY<br />
Any role in the system<br />
<br />
OPTIONS<br />
-d<br />
Specifies that more detailed information about the system is displayed.<br />
<br />
-param<br />
Specifies that the system parameters are displayed.<br />
<br />
-fan<br />
Displays the system fan information.<br />
<br />
-space<br />
Displays the system capacity information in MB (1024^2 bytes).<br />
<br />
-domainspace<br />
Displays the system capacity information broken down by domain in MB<br />
(1024^2 bytes).<br />
<br />
-desc<br />
Displays the system descriptor properties.<br />
<br />
-devtype FC|NL|SSD<br />
Displays the system capacity information where the disks must have a<br />
device type string matching the specified device type; either Fast<br />
Class (FC), Nearline (NL), Solid State Drive (SSD). This option can<br />
only be issued with the -space option.<br />
<br />
SPECIFIERS<br />
None.<br />
<br />
NOTES<br />
See setsys command for information on setting the threshold parameters<br />
indicated by the Value column in the output for showsys -param.<br />
<br />
In the output for showsys -param, (from configured settings) indicates that<br />
the system parameters displayed have been successfully read from the<br />
Persistent Repository (PR). If the PR is not available (most likely because<br />
of problems with the admin volume), the output reads (from default settings)<br />
and the values displayed would indicate the system defaults. When (from<br />
default settings) is displayed, system parameters cannot be updated.<br />
<br />
If the VVRetentionTimeMax is 0, then the volume retention time in the system<br />
is disabled.<br />
<br />
For the system capacity information, there might be some overlaps among<br />
Volumes, System, and Failed Capacities.<br />
<br />
EXAMPLES<br />
The following example displays the system descriptor properties of a HP 3PAR<br />
storage system:<br />
<br />
cli% showsys -desc<br />
------------System s36------------<br />
System Name : s36<br />
Location : Your Facility Address<br />
Owner : Your Company Name<br />
Contact : Joe Admin<br />
Comment : Your Notes<br />
<br />
The following example displays more detailed (-d option) information about<br />
the same storage server:<br />
<br />
cli% showsys -d<br />
------------General-------------<br />
System Name : S424<br />
System Model : HP_3PAR 7200<br />
Serial Number : 1600424<br />
System ID : 424<br />
Number of Nodes : 2<br />
Master Node : 0<br />
Nodes Online : 0,1<br />
Nodes in Cluster : 0,1<br />
<br />
-----System Capacity (MB)-----<br />
Total Capacity : 6277120<br />
Allocated Capacity : 687872<br />
Free Capacity : 5589248<br />
Failed Capacity : 0<br />
<br />
---------System Fan---------<br />
Primary Node ID : 0<br />
Secondary Node ID : 1<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
Primary Node ID : 1<br />
Secondary Node ID : 0<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
<br />
--------System Descriptors--------<br />
Location :<br />
Owner :<br />
Contact :<br />
Comment :<br />
</pre><br />
<br />
<br />
==== Space details ====<br />
<br />
> showsys -space<br />
<br />
<br />
=== Chech Hardware ===<br />
<br />
> admithw<br />
<br />
Check Hardware and try to fix issues. Initialize new disks<br />
<br />
<br />
=== IOPS Stats ===<br />
<br />
statvlun -ni -iter 1 -hostsum<br />
<br />
Output:<br />
<pre><br />
14:09:22 10/13/2018 r/w I/O per second KBytes per sec Svt ms IOSz KB <br />
Hostname Cur Avg Max Cur Avg Max Cur Avg Cur Avg Qlen<br />
FF1EPPINFVMH02 t 105 105 105 2278 2278 2278 0.42 0.42 21.7 21.7 0<br />
...<br />
</pre><br />
<br />
<br />
== Tuning ==<br />
<br />
=== Move VVs between CPGs ===<br />
<br />
[[Hp/3PAR#Move volume to another CPG using tunevv|Move volume to another CPG using tunevv]]<br />
<br />
<br />
=== Balance PDs ===<br />
<br />
If allocation of physical diskspace is not in balance through disks available.<br/><br />
Dry-Run:<br />
<br />
tunenodech -dr -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
NO Dry-Run:<br />
<br />
tunenodech -waittask -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
{{Achtung|Do this for all Nodes in your 3PAR environment after each other!! Just replace '-node 0' by '-node N'}}<br />
<br />
<br />
<br />
== CPGs ==<br />
<br />
=== Show CPGs ===<br />
<br />
<pre><br />
% showcpg<br />
----Volumes---- -Usage- -------------(MiB)-------------<br />
Id Name Warn% VVs TPVVs TDVVs Usr Snp Base Snp Free Total<br />
0 FC_r1 - 0 0 0 0 0 0 0 0 0<br />
1 FC_r5 - 35 35 0 35 34 3774976 14848 193536 3983360<br />
2 FC_r6 - 19 19 0 19 0 27048320 0 478208 27526528<br />
3 FC_Snap - 20 20 0 0 20 0 138752 51712 190464<br />
5 SSD_AO_R6 - 0 0 0 0 0 4998656 0 2560 5001216<br />
4 SSD_r5 - 0 0 0 0 0 2070144 0 37248 2107392<br />
--------------------------------------------------------------------------<br />
6 total 54 54 37892096 153600 763264 38808960<br />
</pre><br />
<br />
<br />
Show the Data Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sdg<br />
-----(MiB)------ <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 32768 -ssz 2 -ha cage -t r1 -p -devtype FC <br />
1 FC_r5 - - 32768 -ssz 6 -ha mag -t r5 -p -devtype FC <br />
2 FC_r6 - - 32768 -t r6 -ha mag -ssz 6 -ss 128 -p -devtype FC <br />
3 FC_Snap - - 32768 -t r6 -ha mag -ssz 8 -ss 64 -ch first -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -t r5 -ha mag -ssz 4 -ss 64 -ch first -p -devtype SSD<br />
4 SSD_r5 - - 8192 -t r5 -ha mag -ss 64 -p -devtype SSD<br />
</pre><br />
<br />
<br />
Show the Admin Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sag<br />
-----(MiB)----- <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 8192 -p -devtype FC -ha cage -p -devtype FC<br />
1 FC_r5 - - 8192 -p -devtype FC -p -devtype FC <br />
2 FC_r6 - - 8192 -ha mag -p -devtype FC <br />
3 FC_Snap - - 8192 -ha mag -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -ha mag -p -devtype SSD <br />
4 SSD_r5 - - 8192 -ha mag -p -devtype SSD<br />
</pre><br />
<br />
<br />
=== Create CPG ===<br />
<br />
% createcpg -t r6 -ha mag -sdgs 32G -ssz 8 -ss 128 -p -devtype FC <CPG_Name><br />
<br />
-t RAID Level<br/><br />
-ha HA Settings (port|cage|mag)<br/><br />
-sdgs Data-Growth Size<br/><br />
-ssz size_number_chunklets: 2 for RAID-1, 4 for RAID-5, and 8 for RAID-6<br/><br />
-p define a pattern / -devtype define a pattern for DevTypes to match<br/><br />
<br />
== Virtual Volumes ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Virtual Volumes ===<br />
<br />
showvv -listcols<br />
<br />
showvv -showcols Name,VV_WWN,SnpCPG<br />
<br />
<br />
=== Create Virtual Volume ===<br />
<br />
createvv -tpvv -pol zero_detect -snp_cpg FC_Snap FC_r6 FF3_VMW_AO_03 4194304<br />
<br />
<pre><br />
-Tpvv Thin provisions Virtual Volume<br />
-pol zero_detect I believe it is needed to thin luns<br />
-snp_cfg FC_Snap Where the writes will go for snapshots. HP refers to this as snap or copy space<br />
FF3_VMW_AO_03 Name: this is the lun name<br />
4194304 Size: This is the number to 4tb<br />
8388608 Size: 8tb<br />
</pre><br />
<br />
=== Move volume to another CPG using tunevv ===<br />
<br />
Assuming I want to move a virtual volume ('''VV12_AO''') to another new CPG ('''FC_r6'''):<br />
<br />
tunevv usr_cpg FC_r6 VV12_AO<br />
<br />
The logical disks used for user space are moved to CPG FC_r6 for virtual volume VV12_AO<br />
Keep in mind that this will destroy your current AO. If the Volume has been moved to some Tier0 storage, let's say SSD disks, <br/><br />
the AO optimization for the volume gets lost and it will have to wait for the next AO runs.<br/><br/><br />
<br />
If you want to move the VV regions that reside on Tier1 storage only, use:<br />
<br />
tunevv usr_cpg FC_r6 -src_cpg FC_r5 VV12_AO<br />
<br />
<br />
Assuming I want to move a volume ('''VV12_AO''') to another new SnapCPG ('''FC_Snap'''):<br />
<br />
tunevv snp_cpg FC_Snap VV12_AO<br />
<br />
Unfortunatly you will have to run both commands seperatly. As of the documentation they can't be combined.<br />
<br />
== AO Config ==<br />
<br />
<pre><br />
createaocfg -t0cpg SSD_AO_R6 -t1cpg FC_r6 -mode Performance -t0min 8T AO_CFG_FCR6<br />
setaocfg -t0min 10T AO_CFG_FCR6<br />
<br />
createsched "startao -btsecs -12h -etsecs -30m -maxrunh 12 -compact auto AO_CFG_FCR6" "0 18 * * 1-5" Task_AO-Run_FCR6<br />
<br />
startao -btsecs -6h -etsecs -1m -maxrunh 1 -compact auto AO_CFG_FCR6<br />
</pre><br />
<br />
== Auth LDAP ==<br />
<br />
yadda<br />
<br />
<br />
=== Set LDAP auth ===<br />
<br />
<pre><br />
setauthparam -f -clearall<br />
setauthparam -f ldap-server 10.30.111.112<br />
setauthparam -f ldap-server-hn STGWPVEURDC02.<DOMAIN>.<DOMAIN>.com<br />
setauthparam -f kerberos-realm <DOMAIN>.<DOMAIN>.com<br />
setauthparam -f binding sasl<br />
setauthparam -f sasl-mechanism GSSAPI<br />
setauthparam -f accounts-dn "OU=PrivilegedAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=com" <br />
setauthparam -f account-obj user<br />
setauthparam -f account-name-attr sAMAccountName <br />
setauthparam -f memberof-attr memberOf<br />
setauthparam -f super-map "CN=SAN_Admins,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
setauthparam -f browse-map "CN=SAN_ReadOnly,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
</pre><br />
<br />
Check that it works for you:<br />
<br />
checkpassword <LDAP-Username><br />
...<br />
...<br />
user <LDAP-Username> is authenticated and authorized<br />
<br />
=== Get LDAP auth config ===<br />
<br />
<pre><br />
% showauthparam<br />
Param --------------------------------------Value---------------------------------------<br />
ldap-server 10.30.111.106 <br />
ldap-server-hn DC05.<DOMAIN>.<TLD> <br />
kerberos-realm <DOMAIN>.<TLD> <br />
binding sasl <br />
sasl-mechanism GSSAPI<br />
[...]<br />
</pre><br />
<br />
<br />
== Network ==<br />
<br />
yadda<br />
<br />
<br />
=== get network settings ===<br />
<br />
<pre><br />
% shownet<br />
IP Address Netmask/PrefixLen Nodes Active Speed Duplex AutoNeg Status<br />
10.11.12.100 255.255.255.0 01 0 1000 Full Yes Active<br />
<br />
Default route : 10.11.12.1<br />
NTP server : 10.30.111.111<br />
DNS server : 10.11.12.42<br />
</pre><br />
<br />
<br />
=== set DNS server ===<br />
<br />
Add:<br />
<br />
setnet dns -add 10.30.111.111<br />
<br />
Remove:<br />
<br />
setnet dns -remove 10.30.111.111<br />
<br />
<br />
=== re-new expired certificates ===<br />
<br />
Show the actual cert:<br />
<br />
% showcert<br />
Service Commonname Type Enddate Fingerprint <br />
unified-server* HP_3PAR 8200-CZ3740W5MD cert Oct 16 15:36:12 2020 GMT bdae8ff911a32e50a65a81dbae656b46112fa992<br />
<br />
<br />
Renew the cert:<br />
<br />
<pre><br />
createcert unified-server -selfsigned -CN 3par.yadda.com -SAN DNS:3par-alias.yadda.com,DNS:10.12.13.14<br />
The following services will be restarted if currently running:<br />
cim: manages communications with SMI-S clients<br />
<br />
wsapi: Web Services API server<br />
<br />
Continue creating self-signed certificate (yes/no)? yes<br />
Self-signed certificate created.<br />
cimserver restarted<br />
The Web Services API server stopped successfully.<br />
<br />
The Web Services API Server will start shortly.<br />
</pre><br />
<br />
Done!<br />
<br />
<br />
== Full Command List ==<br />
<br />
<pre><br />
HP 3PAR CLI command list<br />
<br />
showalert - show status of system alerts<br />
showauthparam - show authentication parameters<br />
showbattery - show battery status information<br />
showblock - show block mapping info for vvs, lds, pds<br />
showcage - show disk cage information<br />
showcim - show the CIM server information<br />
showclienv - show CLI environment parameters<br />
showcpg - show Common Provisioning Groups (CPGs)<br />
showdate - show date and time on all system nodes<br />
showdomain - show domains in the system<br />
showdomainset - show sets of domains in the system<br />
showeeprom - show node eeprom information<br />
showeventlog - show event logs<br />
showfirmwaredb - show current database of firmware levels<br />
showhost - show host and host path information<br />
showhostset - show sets of hosts in the system<br />
showinventory - show hardware inventory<br />
showiscsisession - show iscsi sessions<br />
showld - show logical disks (LDs) in the system<br />
showldch - show LD to PD chunklet mapping<br />
showldmap - show LD to VV mapping<br />
showlicense - show installed license key<br />
shownet - show network configuration and status<br />
shownode - show node and its component information<br />
shownodeenv - show node environmental status (voltages,temperatures)<br />
showpatch - show what patches have been applied to the system<br />
showpd - show physical disks (PDs) in the system<br />
showpdata - show preserved data status<br />
showpdch - show status of selected chunklets of physical disks<br />
showpdvv - show PD to VV mapping<br />
showport - show Fibre Channel and iSCSI ports in the system<br />
showportarp - show ARP table for ports<br />
showportdev - show detailed information about devices on a Fibre Channel port<br />
showportisns - show iSNS host information for ports<br />
showportlesb - show Link Error Status Block information about devices on Fibre Channel port <br />
showrcopy - show remote copy configuration information<br />
showrctransport - show information about end-to-end transport for remote copy <br />
showrsv - show information about reservation and registration of VLUNs connected on a Fibre Channel port<br />
showsched - show scheduled tasks in the system<br />
showsnmppw - shows SNMP access passwords<br />
showsnmpmgr - show SNMP trap managers<br />
showspace - show estimated free space<br />
showspare - show information about spare and relocated chunklets<br />
showsshkey - show ssh public keys authorized by the current user<br />
showsys - show system information (system name, serial number etc.)<br />
showsysmgr - show system manager startup state<br />
showtarget - show unrecognized targets<br />
showtask - show information about tasks<br />
showtemplate - show templates<br />
showtoc - show system Table of Contents (TOC) summary<br />
showtocgen - show system Table of Contents (TOC) generation number<br />
showuser - show user accounts and SSH keys<br />
showuseracl - show user access control list<br />
showuserconn - show user connections<br />
showversion - show software versions<br />
showvlun - show virtual LUNs (VLUNs) in the system<br />
showvv - show virtual volumes (VVs) in the system<br />
showvvmap - show VV to LD mapping<br />
showvvpd - show VV distribution across PDs<br />
showvvset - show sets of VVs in the system<br />
checkhealth - perform checks to determine overall state of the system<br />
checkpassword - display authentication and authorization details<br />
checkport - perform loopback test on fc ports<br />
checkpd - perform surface scan or diagnostics on physical disks<br />
checkld - perform validity checks of data on logical disks<br />
checkvv - perform validity checks of virtual volume administrative information.<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/exchange&diff=1726
Windows/exchange
2021-03-12T12:03:07Z
<p>Cbs: </p>
<hr />
<div><br />
== PowerShell ==<br />
<br />
powershell commands<br />
<br />
<br />
=== possible access rights ===<br />
<br />
<pre><br />
The Access Rights parameters are as below:<br />
<br />
ReadItems: The user has the right to read items within the specified folder.<br />
CreateItems The user has the right to create items within the specified folder.<br />
EditOwnedItems The user has the right to edit the items that the user owns in the specified folder.<br />
DeleteOwnedItems The user has the right to delete items that the user owns in the specified folder.<br />
EditAllItems The user has the right to edit all items in the specified folder.<br />
DeleteAllItems The user has the right to delete all items in the specified folder.<br />
CreateSubfolders The user has the right to create subfolders in the specified folder.<br />
FolderOwner The user is the owner of the specified folder. The user has the right to view and move the folder and create subfolders. The user can’t read items, edit items, delete items, or create items.<br />
FolderContact The user is the contact for the specified public folder.<br />
FolderVisible The user can view the specified folder, but can’t read or edit items within the specified public folder.<br />
<br />
The Roles with which we can provide the access rights are as below:<br />
<br />
None FolderVisible<br />
Owner CreateItems, ReadItems, CreateSubfolders, FolderOwner, FolderContact, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingEditor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
Editor CreateItems, ReadItems, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingAuthor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
Author CreateItems, ReadItems, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
NonEditingAuthor CreateItems, ReadItems, FolderVisible<br />
Reviewer ReadItems, FolderVisible<br />
Contributor CreateItems, FolderVisible<br />
<br />
Ref: http://technet.microsoft.com/en-us/library/dd298062(v=exchg.150).aspx<br />
<br />
The following roles apply specifically to calendar folders:<br />
<br />
AvailabilityOnly View only availability data<br />
LimitedDetails View availability data with subject and location<br />
</pre><br />
<br />
<br />
=== create mailbox ===<br />
<br />
Create a new mailbox<br />
<br />
New-Mailbox -Name 'prospect NL' -Alias 'prospect.nl' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Rooms and Equipment' \<br />
-UserPrincipalName 'prospect.nl@arifleet.com' -SamAccountName 'prospect.nl' -FirstName 'prospect' -Initials '' -LastName 'NL' \<br />
-Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Stuttgart Mailbox DB One'<br />
<br />
<br />
=== create linked mailbox ===<br />
<br />
New-Mailbox -Name 'Koroch, Ernst' -Alias 'ekoroch' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Users' -UserPrincipalName \<br />
'ekoroch@arifleet.com' -SamAccountName 'ekoroch' -FirstName 'Ernst' -Initials '' -LastName 'Koroch' -Database 'Stuttgart Mailbox DB One' \<br />
-LinkedMasterAccount 'fleetservices\ekoroch' -LinkedDomainController 'dc03.fleetservices.intra' -LinkedCredential \<br />
'System.Management.Automation.PSCredential'<br />
<br />
<br />
=== Repair Mailbox ===<br />
<br />
see: [https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx]<br />
<br />
New-MailboxRepairRequest -Mailbox <Emailaddress> -CorruptionType SearchFolder,AggregateCounts,ProvisionedFolder,FolderView [-DetectOnly]<br />
<br />
<br />
=== Email-Enable AD Group ===<br />
<br />
Enable-DistributionGroup <ADGroupID> -PrimarySmtpAddress yadda@domain.tld<br />
<br />
<br />
=== Email-Enable AD User ===<br />
<br />
Enable-Mailbox <UserID> -PrimarySmtpAddress yadda@domain.tld -displayname "Yadda, Yadda"<br />
<br />
<br />
=== add mailbox permissions ===<br />
<br />
Add full access to mailbox 'mailbox@arifleet.de' for user 'DOMAIN\user': <br />
<br />
Add-MailboxPermission -Identity mailbox@arifleet.de -User DOMAIN\user -AccessRights Fullaccess -InheritanceType All<br />
<br />
-AccessRights <right> <br/><br />
where <right> may be<br />
<br />
FullAccess<br />
ExternalAccount<br />
DeleteItem<br />
ReadPermission<br />
ChangePermission<br />
ChangeOwner<br />
<br />
disable auto-mapping of <br />
<br />
-Automapping $false<br />
<br />
<br />
=== remove mailbox permissions ===<br />
<br />
remove-MailboxPermission -Identity mailbox@arifleet.de -user domari\user -AccessRights Fullaccess -inheritance all<br />
<br />
<br />
=== add/remove 'Send as' permissions ===<br />
<br />
Add-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
You can grant the permissions by using Active Directory Users & Computers. Simply open the properties of the group, switch to the Security tab, add the mailbox user or group, and then tick the Send As box and apply the change. After making this change you may notice that it does not take effect for up to 2 hours. This is due to caching on the Exchange servers. Though you can speed up the change by restarting the Information Store that is obviously not going to be practical in most production environments, so you’ll often find that you just need to wait.<br />
<br />
Remove-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
<br />
==== 'Send as'/'SendOnBehalf' Distributiongroups ====<br />
<br />
Set-DistributionGroup <DistributionGroupName> -GrantSendOnBehalfTo USER@arifleet.com<br />
<br />
and sendOnBehalf for Distributiongroups<br />
<br />
<br />
<br />
==== SentItem Configuration ====<br />
<br />
Until Exchange 2010:<br />
<br />
Set-MailboxSentItemsConfiguration <ALIAS> -SendAsItemsCopiedTo SenderAndFrom<br />
<br />
Exchange 2016:<br />
<br />
Set-Mailbox -identity <UPN> [-DomainController <HOSTNAME>] -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true<br />
<br />
<br />
=== add mailbox folder permissions ===<br />
<br />
Add-MailboxFolderPermission -Identity poolcar@netcar24.com:\Calendar -user csteidl@arifleet.com -AccessRights [[Windows/exchange#possible_access_rights|<see RIGHTS>]]<br />
<br />
Set default-rights for ressource mailboxes (to show up subjects a.s.o.):<br />
<br />
Set-MailboxFolderPermission meetingroom:\Calendar -User Default -AccessRights Reviewer<br />
<br />
=== get mailbox permissions ===<br />
<br />
get permissions of fhess on mailbox prospect.be<br />
<br />
Get-MailboxPermission -Identity prospect.be@arifleet.com -User "fhess"<br />
<br />
<br />
get folder permissions<br />
<br />
get-mailboxfolderpermission -identity fhess<br />
<br />
<br />
get UPN of users<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.User.ADRecipient.UserPrincipalName }<br />
<br />
<br />
get full user details<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.identity.adrecipient.identity }<br />
<br />
<br />
<br />
=== Find permissions granted to spec. users ===<br />
<br />
Get-Mailbox -RecipientType 'UserMailbox' -ResultSize Unlimited | Get-MailboxPermission | where { $_.user.tostring() -eq "DOMAIN\username" -and $_.IsInherited -eq $false }<br />
<br />
<br />
<br />
=== enable autoreply / vacation message ===<br />
<br />
set the message (optionally) and enable auto reply<br />
<br />
$message = get-content message.txt<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState enabled \<br />
-ExternalAudience <none/all/known> \<br />
-InternalMessage "$message" \<br />
-ExternalMessage "$message"<br />
<br />
<br />
=== disable auto-reply / vacation message ===<br />
<br />
disable auto reply<br />
<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState disabled<br />
<br />
<br />
=== Retention policies ===<br />
<br />
create server side retention policies<br />
<br />
<br />
==== Create Retention Policy Tag ====<br />
<br />
New-RetentionPolicyTag "ARI STG - Delete all 180 days" -Type All -Comment "Deletes all items older 180 days" -RetentionEnabled $true \<br />
-AgeLimitForRetention 180 -RetentionAction DeleteAndAllowRecovery<br />
<br />
RetentionAction: MoveToFolder, MoveToDeletedItems, DeleteAndAllowRecovery, PermanentlyDelete, MoveToArchive<br />
<br />
<br />
==== Create Retention Policy ====<br />
<br />
New-RetentionPolicy "ARI STG - Delete ALL items older 180 days" -RetentionPolicyTagLinks "ARI STG - Delete all 180 days"<br />
<br />
Activate policy by: Open Mailbox Properties --> Mailbox Settings --> Messaging Records Mgmt --> Apply Retention policy<br />
<br />
<br />
=== get distribution group members ===<br />
<br />
get-distributiongroupmember <group><br />
<br />
get-distributiongroupmember mailaddress@arifleet.de<br />
<br />
<br />
=== get users by filter and add to distributiongroup ===<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -ne 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -eq 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
<br />
<br />
=== Get Mailbox by ExchangeGuid/Mapi-session ===<br />
<br />
get-mailbox -ResultSize unlimited | where {$_.ExchangeGuid -eq "265182e3-a31c-4a9f-e38e-687f5a7c2d6b"}<br />
<br />
<br />
=== Get Mailbox by Ressource type ===<br />
<br />
<br />
Get-Mailbox -RecipientTypeDetails RoomMailbox<br />
<br />
Get-Mailbox -RecipientTypeDetails EquipmentMailbox<br />
<br />
<br />
=== Get Mail Public folder ===<br />
<br />
Get-MailPublicFolder helpdesk@sub.domain.com | Get-PublicFolder [| Select *]<br />
<br />
<br />
=== Logging ===<br />
<br />
further logfiles can be found here:<br />
<br />
C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\ProtocolLog<br />
<br />
<br />
==== Track accross multiple servers ====<br />
<br />
get-transportserver<br />
<br />
<br />
e.g. that to "get-messagetrackinglog":<br />
<br />
get-transportserver | get-messagetrackinglog<br />
<br />
<br />
==== message tracking ====<br />
<br />
get-messagetrackinglog -Sender 'user@arifleet.de' -Start "5/04/2015 5:00:00 AM" -End "5/15/2015 8:30:00 AM"<br />
<br />
get-transportserver | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
get-transportservice | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
-Start "6/01/2015 5:00:00 AM" \<br />
-End "6/01/2015 10:30:00 AM" \<br />
-resultsize unlimited | ft -Wrap<br />
<br />
<pre><br />
-MessageSubject <String><br />
-Recipients <String[]><br />
-Start/-End (get-date).AddHours(-1).toString()<br />
-ResultSize Unlimited<br />
</pre><br />
<br />
some more examples:<br />
<br />
get-messagetrackinglog -Recipients:recipient@email.be -Start "6/8/2015 4:42:00 AM" -End "6/9/2015 9:52:00 PM" | Select *,{$_.Recipients} | export-csv .\maillog.csv<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | \<br />
where-object {$_.Recipients -like “*@gmail.com, *@yahoo.com” -AND $_.EventId -eq “Send”} |ft -auto >>C:\External mails.txt<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | sort -property Timestamp<br />
<br />
=== repair mailbox ===<br />
<br />
New-MailboxRepairRequest -Mailbox schaden@arifleet.de -CorruptionType SearchFolder<br />
<br />
<br />
-CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview<br />
-Archive Prueft Mailbox _und_ Archive<br />
-DetectOnly Prueft nur, keine Reparatur!<br />
<br />
Ergebnisse der Prüfung werden im Anwendungs Event-Log des Servers protokolliert. Die Events tragen die folgenden Ereignis-IDs:<br />
<br />
10044,10045,10046,10047,10048,10049,10050,10051,10059,10062<br />
<br />
mit einem rechtsklick auf 'Application' laesst dich das eventlog nach diesen ID's filtern.<br />
<br />
<br />
=== move mailbox between exchange-databases ===<br />
<br />
Move Mailboxes between exchange >= 2010 servers <br/><br />
the output is piped into 'ft' (format table) to get complete output and not stripped it...<br />
<br />
New-MoveRequest -Identity mailbox@arifleet.de -TargetDatabase ‘Whatever Database-Name 001’ | ft -AutoSize -Wrap<br />
<br />
create a batch<br />
<br />
Get-Mailbox -Database "Stuttgart Mailbox DB One" | Where-Object { $_.alias -like "jira*" } | New-MoveRequest -TargetDatabase [...]<br />
<br />
Options:<br />
<br />
-BadItemLimit 0<br />
-Suspend <br />
-SuspendComment "Resume after 11:00 p.m. PST"<br />
-SuspendWhenReadyToComplete<br />
-BatchName "Some Name to identify the Batch-Moves"<br />
<br />
get moverequest status:<br />
<br />
Get-MoveRequestStatistics "sadg"<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics | select DisplayName,alias,Status,TotalMailboxSize,PercentComplete| ft<br />
<br />
<br />
=== get Mailbox sizes ===<br />
<br />
Get-MailboxDatabase | Where-Object { $_.Name -like "STG*" } | Get-MailboxStatistics | sort -property TotalItemSize -desc \<br />
| select DisplayName,ItemCount,TotalItemSize,TotalDeletedItemSize |ft<br />
<br />
<br />
=== get database size ===<br />
<br />
Get-MailboxDatabase -status | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Sort-Object DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Where-Object { $_.name -like "STG*" } | Sort -property DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
=== Export Mailbox (Folder) ===<br />
<br />
New-MailboxExportRequest -mailbox schaden \<br />
-includefolders "******@arifleet.de/00 UNFALLORDNER ab 1.3.2011/Storopack R+V (*.***@*******.com) TK 150 \/ keine VK RA Schmid" \<br />
-filepath "\\stgwpvinfEXC01\g$\Storopack R+V (*.***@*******.com) TK 150_keine VK RA Schmid.pst"<br />
<br />
# be sure to mask e.g. '/' characters in foldernames with '\'<br />
# leave out '''-includefolders''' to export the entire mailbox<br/><br />
## add a '.../*' to -includefolders to include subfolders<br />
<br />
=== Search Mailbox content ===<br />
<br />
This one searches for all messages between 1/1/2017 and 12/31/2018 and creates copies of it within the Mailbox of targetmailbox into targetfolder:<br />
<br />
Search-Mailbox -Identity <USER-ID> -SearchQuery "received>=01/01/2017 AND received<=12/31/2018" -targetmailbox "<TARGET-USER-ID>" -targetfolder "SearchResults"<br />
<br />
<br />
=== set thumbnail-image ===<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
<br />
=== Import/Acivate new Certificate ===<br />
<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path c:\certificates\YOUR_CERTIFICATE.cer -Encoding byte -ReadCount 0))<br />
<br />
In case of encrypted .pfx or something like that:<br />
<br />
$pass = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -Password $pass -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path Webmail.pfx -Encoding byte -ReadCount 0))<br />
<br />
activate:<br />
<br />
Enable-ExchangeCertificate -Thumbprint 1234ae0567a72fccb75b1d0198628675333d010e -Services POP,IMAP,SMTP,IIS<br />
<br />
=== DAG/Cluster stuff ===<br />
<br />
Check who's master:<br />
<br />
Get-ClusterGroup EU-DAG<br />
<br />
<br />
Get detailed DAG info:<br />
<br />
Get-DatabaseAvailabilityGroup STG-DAG -status | fl<br />
<br />
<br />
Test replication health (do so on all cluster members):<br />
<br />
Test-ReplicationHealth -server EXC02<br />
<br />
<br />
Get mount status, copy/reply queue, Index state<br />
<br />
Get-MailboxDatabaseCopyStatus -server exc01<br />
<br />
<br />
Check Queues:<br />
<br />
get-queue -server stgwpvinfexc02<br />
<br />
<br />
Move queued messages to other server:<br />
<br />
Redirect-Message -Server Mailbox01 -Target Mailbox02<br />
<br />
<br />
Check service health (do so on all cluster members):<br/><br />
(test whether all the Microsoft Windows services that Exchange requires on a server have started)<br />
<br />
Test-servicehealth –server EXC02<br />
<br />
<br />
Test MapiConnectivity (Note: this will only test if the DB’s are mounted/active copy on the specific server):<br />
<br />
Test-MapiConnectivity -server EXC02<br />
<br />
<br />
Test/view replication:<br />
<br />
Get-MailboxdatabaseCopystatus -server EXC02<br />
<br />
<br />
Failover Cluster:<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup <br />
<br />
This will failover the 2 node cluster to the other node<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup -node EXC01<br />
<br />
This will failover the cluster to the node EXC01<br />
<br />
<br />
Move Databases:<br />
<br />
Move-ActiveMailboxDatabase DB3 -ActivateOnServer MBX4<br />
<br />
This example performs a switchover of the database DB3 to the Mailbox server MBX4. When the command completes, MBX4 hosts the active copy of DB3. Because the MountDialOverride parameter isn't specified, MBX4 mounts the database using a database auto mount dial setting of Lossless.<br />
<br />
<br />
Get-MailboxDatabase stg-* | Move-ActiveMailboxDatabase -ActivateOnServer MBX4<br />
<br />
Same as above, but moves all databases starting with 'STG-*' to MBX04<br />
<br />
<br />
Move-ActiveMailboxDatabase DB1 -ActivateOnServer MBX3 -MountDialOverride:GoodAvailability<br />
<br />
This example performs a switchover of the database DB1 to the Mailbox server MBX3. When the command completes, MBX3 hosts the active copy of DB1. Because the MountDialOverride parameter is specified with a value of Good Availability, MBX3 mounts the database using a database auto mount dial setting of GoodAvailability.<br />
<br />
== Outlook stuff ==<br />
<br />
=== get all add-ins ===<br />
<br />
Be aware that HKCU can only be grabbed if running in the user context!<br />
<br />
$searchScopes = "HKCU:\SOFTWARE\Microsoft\Office\Outlook\Addins","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins"<br />
$searchScopes | % {Get-ChildItem -Path $_ | % {Get-ItemProperty -Path $_.PSPath} | Select-Object @{n="Name";e={Split-Path $_.PSPath -leaf}},FriendlyName,Description} | Sort-Object -Unique -Property name<br />
<br />
<br />
== Transport stuff ==<br />
<br />
some stuff i used the GUI for<br />
<br />
<br />
=== Relay Configuration (GUI) ===<br />
<br />
Go:<br />
Server-Configuration --> Hub Transport --> Receive Connectors (Tab)<br />
<br />
- Select a valuable connector which matches you needs or create a new.<br />
- for me there was 'Relay internal' which was to allow anonymous connects from spec. hosts/nets --> Double-Click<br />
- Switch to 'Network'-Tab --> Add IP or rage to lower box.<br />
<br />
<br />
<br />
=== Max connection from single IP ===<br />
<br />
set-ReceiveConnector -Identity "exc03\Application_Relay" -MaxInboundConnectionPerSource 50<br />
<br />
sets the max inbound connections per source IP to 50 (default 20)<br />
<br />
<br />
<br />
=== Create an anonymous Receive Connector ===<br />
<br />
after you created an receive connector by GUI you will have to run:<br />
<br />
Get-ReceiveConnector "STGWPVINFEXC02\Application_Relay_Intern" | \<br />
Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"</div>
Cbs
https://schnallich.net/index.php?title=Hp/3PAR&diff=1725
Hp/3PAR
2021-03-11T07:44:41Z
<p>Cbs: /* Move volume to another CPG using tunevv */</p>
<hr />
<div><br />
== Diag ==<br />
<br />
=== Infos for HP (creating Case) ===<br />
<br />
> showsys <br />
> showsys -d<br />
<br />
(System Information inclusing serial)<br />
<br />
<br />
> servicemag status <br />
<br />
(shows if any drive was already evacuated)<br />
<br />
<br />
> checkhealth pd<br />
<br />
(do healthcheck of physical disks)<br />
<br />
<br />
> showpd -s <br />
> showpd -state<br />
> showpd -s -failed<br />
> showpd -failed -degraded<br />
<br />
(show the state of all drives)<br />
<br />
<br />
> showpd -i <br />
<br />
(show the drive inventory including type and serial)<br />
<br />
<br />
> showport -sfp [-d]<br />
<br />
(show the SFP ports and their status [detailed list])<br />
<br />
=== showsys (System info) ===<br />
<br />
Help page<br />
<br />
<pre><br />
showsys - Show system information.<br />
<br />
SYNTAX<br />
showsys [options]<br />
<br />
DESCRIPTION<br />
The showsys command displays the HP 3PAR Storage system properties such as<br />
a system name, serial number, and system capacity information.<br />
<br />
AUTHORITY<br />
Any role in the system<br />
<br />
OPTIONS<br />
-d<br />
Specifies that more detailed information about the system is displayed.<br />
<br />
-param<br />
Specifies that the system parameters are displayed.<br />
<br />
-fan<br />
Displays the system fan information.<br />
<br />
-space<br />
Displays the system capacity information in MB (1024^2 bytes).<br />
<br />
-domainspace<br />
Displays the system capacity information broken down by domain in MB<br />
(1024^2 bytes).<br />
<br />
-desc<br />
Displays the system descriptor properties.<br />
<br />
-devtype FC|NL|SSD<br />
Displays the system capacity information where the disks must have a<br />
device type string matching the specified device type; either Fast<br />
Class (FC), Nearline (NL), Solid State Drive (SSD). This option can<br />
only be issued with the -space option.<br />
<br />
SPECIFIERS<br />
None.<br />
<br />
NOTES<br />
See setsys command for information on setting the threshold parameters<br />
indicated by the Value column in the output for showsys -param.<br />
<br />
In the output for showsys -param, (from configured settings) indicates that<br />
the system parameters displayed have been successfully read from the<br />
Persistent Repository (PR). If the PR is not available (most likely because<br />
of problems with the admin volume), the output reads (from default settings)<br />
and the values displayed would indicate the system defaults. When (from<br />
default settings) is displayed, system parameters cannot be updated.<br />
<br />
If the VVRetentionTimeMax is 0, then the volume retention time in the system<br />
is disabled.<br />
<br />
For the system capacity information, there might be some overlaps among<br />
Volumes, System, and Failed Capacities.<br />
<br />
EXAMPLES<br />
The following example displays the system descriptor properties of a HP 3PAR<br />
storage system:<br />
<br />
cli% showsys -desc<br />
------------System s36------------<br />
System Name : s36<br />
Location : Your Facility Address<br />
Owner : Your Company Name<br />
Contact : Joe Admin<br />
Comment : Your Notes<br />
<br />
The following example displays more detailed (-d option) information about<br />
the same storage server:<br />
<br />
cli% showsys -d<br />
------------General-------------<br />
System Name : S424<br />
System Model : HP_3PAR 7200<br />
Serial Number : 1600424<br />
System ID : 424<br />
Number of Nodes : 2<br />
Master Node : 0<br />
Nodes Online : 0,1<br />
Nodes in Cluster : 0,1<br />
<br />
-----System Capacity (MB)-----<br />
Total Capacity : 6277120<br />
Allocated Capacity : 687872<br />
Free Capacity : 5589248<br />
Failed Capacity : 0<br />
<br />
---------System Fan---------<br />
Primary Node ID : 0<br />
Secondary Node ID : 1<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
Primary Node ID : 1<br />
Secondary Node ID : 0<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
<br />
--------System Descriptors--------<br />
Location :<br />
Owner :<br />
Contact :<br />
Comment :<br />
</pre><br />
<br />
<br />
==== Space details ====<br />
<br />
> showsys -space<br />
<br />
<br />
=== Chech Hardware ===<br />
<br />
> admithw<br />
<br />
Check Hardware and try to fix issues. Initialize new disks<br />
<br />
<br />
=== IOPS Stats ===<br />
<br />
statvlun -ni -iter 1 -hostsum<br />
<br />
Output:<br />
<pre><br />
14:09:22 10/13/2018 r/w I/O per second KBytes per sec Svt ms IOSz KB <br />
Hostname Cur Avg Max Cur Avg Max Cur Avg Cur Avg Qlen<br />
FF1EPPINFVMH02 t 105 105 105 2278 2278 2278 0.42 0.42 21.7 21.7 0<br />
...<br />
</pre><br />
<br />
<br />
== Tuning ==<br />
<br />
=== Move VVs between CPGs ===<br />
<br />
[[Hp/3PAR#Move volume to another CPG using tunevv|Move volume to another CPG using tunevv]]<br />
<br />
<br />
=== Balance PDs ===<br />
<br />
If allocation of physical diskspace is not in balance through disks available.<br/><br />
Dry-Run:<br />
<br />
tunenodech -dr -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
NO Dry-Run:<br />
<br />
tunenodech -waittask -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
{{Achtung|Do this for all Nodes in your 3PAR environment after each other!! Just replace '-node 0' by '-node N'}}<br />
<br />
<br />
<br />
== CPGs ==<br />
<br />
=== Show CPGs ===<br />
<br />
<pre><br />
% showcpg<br />
----Volumes---- -Usage- -------------(MiB)-------------<br />
Id Name Warn% VVs TPVVs TDVVs Usr Snp Base Snp Free Total<br />
0 FC_r1 - 0 0 0 0 0 0 0 0 0<br />
1 FC_r5 - 35 35 0 35 34 3774976 14848 193536 3983360<br />
2 FC_r6 - 19 19 0 19 0 27048320 0 478208 27526528<br />
3 FC_Snap - 20 20 0 0 20 0 138752 51712 190464<br />
5 SSD_AO_R6 - 0 0 0 0 0 4998656 0 2560 5001216<br />
4 SSD_r5 - 0 0 0 0 0 2070144 0 37248 2107392<br />
--------------------------------------------------------------------------<br />
6 total 54 54 37892096 153600 763264 38808960<br />
</pre><br />
<br />
<br />
Show the Data Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sdg<br />
-----(MiB)------ <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 32768 -ssz 2 -ha cage -t r1 -p -devtype FC <br />
1 FC_r5 - - 32768 -ssz 6 -ha mag -t r5 -p -devtype FC <br />
2 FC_r6 - - 32768 -t r6 -ha mag -ssz 6 -ss 128 -p -devtype FC <br />
3 FC_Snap - - 32768 -t r6 -ha mag -ssz 8 -ss 64 -ch first -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -t r5 -ha mag -ssz 4 -ss 64 -ch first -p -devtype SSD<br />
4 SSD_r5 - - 8192 -t r5 -ha mag -ss 64 -p -devtype SSD<br />
</pre><br />
<br />
<br />
Show the Admin Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sag<br />
-----(MiB)----- <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 8192 -p -devtype FC -ha cage -p -devtype FC<br />
1 FC_r5 - - 8192 -p -devtype FC -p -devtype FC <br />
2 FC_r6 - - 8192 -ha mag -p -devtype FC <br />
3 FC_Snap - - 8192 -ha mag -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -ha mag -p -devtype SSD <br />
4 SSD_r5 - - 8192 -ha mag -p -devtype SSD<br />
</pre><br />
<br />
<br />
=== Create CPG ===<br />
<br />
% createcpg -t r6 -ha mag -sdgs 32G -ssz 8 -ss 128 -p -devtype FC <CPG_Name><br />
<br />
-t RAID Level<br/><br />
-ha HA Settings (port|cage|mag)<br/><br />
-sdgs Data-Growth Size<br/><br />
-ssz size_number_chunklets: 2 for RAID-1, 4 for RAID-5, and 8 for RAID-6<br/><br />
-p define a pattern / -devtype define a pattern for DevTypes to match<br/><br />
<br />
== Virtual Volumes ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Virtual Volumes ===<br />
<br />
showvv -listcols<br />
<br />
showvv -showcols Name,VV_WWN,SnpCPG<br />
<br />
<br />
=== Create Virtual Volume ===<br />
<br />
createvv -tpvv -pol zero_detect -snp_cpg FC_Snap FC_r6 FF3_VMW_AO_03 4194304<br />
<br />
<pre><br />
-Tpvv Thin provisions Virtual Volume<br />
-pol zero_detect I believe it is needed to thin luns<br />
-snp_cfg FC_Snap Where the writes will go for snapshots. HP refers to this as snap or copy space<br />
FF3_VMW_AO_03 Name: this is the lun name<br />
4194304 Size: This is the number to 4tb<br />
8388608 Size: 8tb<br />
</pre><br />
<br />
=== Move volume to another CPG using tunevv ===<br />
<br />
Assuming I want to move a virtual volume ('''VV12_AO''') to another new CPG ('''FC_r6'''):<br />
<br />
tunevv usr_cpg FC_r6 VV12_AO<br />
<br />
The logical disks used for user space are moved to CPG FC_r6 for virtual volume VV12_AO<br />
Keep in mind that this will destroy your current AO. If the Volume has been moved to some Tier0 storage, let's say SSD disks, <br/><br />
the AO optimization for the volume gets lost and it will have to wait for the next AO runs.<br/><br/><br />
<br />
If you want to move the VV regions that reside on Tier1 storage only, use:<br />
<br />
tunevv usr_cpg FC_r6 -src_cpg FC_r5 VV12_AO<br />
<br />
<br />
Assuming I want to move a volume ('''VV12_AO''') to another new SnapCPG ('''FC_Snap'''):<br />
<br />
tunevv snp_cpg FC_Snap VV12_AO<br />
<br />
Unfortunatly you will have to run both commands seperatly. As of the documentation they can't be combined.<br />
<br />
== AO Config ==<br />
<br />
<pre><br />
createaocfg -t0cpg SSD_AO_R6 -t1cpg FC_r6 -mode performance -t0min 8T AO_CFG_FCR6<br />
setaocfg -t0min 10T AO_CFG_FCR6<br />
<br />
createsched "startao -btsecs -12h -etsecs -30m -maxrunh 12 -compact auto AO_CFG_FCR6" "0 18 * * 1-5" Task_AO-Run_FCR6<br />
<br />
startao -btsecs -6h -etsecs -1m -maxrunh 1 -compact auto AO_CFG_FCR6<br />
</pre><br />
<br />
== Auth LDAP ==<br />
<br />
yadda<br />
<br />
<br />
=== Set LDAP auth ===<br />
<br />
<pre><br />
setauthparam -f -clearall<br />
setauthparam -f ldap-server 10.30.111.112<br />
setauthparam -f ldap-server-hn STGWPVEURDC02.<DOMAIN>.<DOMAIN>.com<br />
setauthparam -f kerberos-realm <DOMAIN>.<DOMAIN>.com<br />
setauthparam -f binding sasl<br />
setauthparam -f sasl-mechanism GSSAPI<br />
setauthparam -f accounts-dn "OU=PrivilegedAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=com" <br />
setauthparam -f account-obj user<br />
setauthparam -f account-name-attr sAMAccountName <br />
setauthparam -f memberof-attr memberOf<br />
setauthparam -f super-map "CN=SAN_Admins,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
setauthparam -f browse-map "CN=SAN_ReadOnly,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
</pre><br />
<br />
Check that it works for you:<br />
<br />
checkpassword <LDAP-Username><br />
...<br />
...<br />
user <LDAP-Username> is authenticated and authorized<br />
<br />
=== Get LDAP auth config ===<br />
<br />
<pre><br />
% showauthparam<br />
Param --------------------------------------Value---------------------------------------<br />
ldap-server 10.30.111.106 <br />
ldap-server-hn DC05.<DOMAIN>.<TLD> <br />
kerberos-realm <DOMAIN>.<TLD> <br />
binding sasl <br />
sasl-mechanism GSSAPI<br />
[...]<br />
</pre><br />
<br />
<br />
== Network ==<br />
<br />
yadda<br />
<br />
<br />
=== get network settings ===<br />
<br />
<pre><br />
% shownet<br />
IP Address Netmask/PrefixLen Nodes Active Speed Duplex AutoNeg Status<br />
10.11.12.100 255.255.255.0 01 0 1000 Full Yes Active<br />
<br />
Default route : 10.11.12.1<br />
NTP server : 10.30.111.111<br />
DNS server : 10.11.12.42<br />
</pre><br />
<br />
<br />
=== set DNS server ===<br />
<br />
Add:<br />
<br />
setnet dns -add 10.30.111.111<br />
<br />
Remove:<br />
<br />
setnet dns -remove 10.30.111.111<br />
<br />
<br />
=== re-new expired certificates ===<br />
<br />
Show the actual cert:<br />
<br />
% showcert<br />
Service Commonname Type Enddate Fingerprint <br />
unified-server* HP_3PAR 8200-CZ3740W5MD cert Oct 16 15:36:12 2020 GMT bdae8ff911a32e50a65a81dbae656b46112fa992<br />
<br />
<br />
Renew the cert:<br />
<br />
<pre><br />
createcert unified-server -selfsigned -CN 3par.yadda.com -SAN DNS:3par-alias.yadda.com,DNS:10.12.13.14<br />
The following services will be restarted if currently running:<br />
cim: manages communications with SMI-S clients<br />
<br />
wsapi: Web Services API server<br />
<br />
Continue creating self-signed certificate (yes/no)? yes<br />
Self-signed certificate created.<br />
cimserver restarted<br />
The Web Services API server stopped successfully.<br />
<br />
The Web Services API Server will start shortly.<br />
</pre><br />
<br />
Done!<br />
<br />
<br />
== Full Command List ==<br />
<br />
<pre><br />
HP 3PAR CLI command list<br />
<br />
showalert - show status of system alerts<br />
showauthparam - show authentication parameters<br />
showbattery - show battery status information<br />
showblock - show block mapping info for vvs, lds, pds<br />
showcage - show disk cage information<br />
showcim - show the CIM server information<br />
showclienv - show CLI environment parameters<br />
showcpg - show Common Provisioning Groups (CPGs)<br />
showdate - show date and time on all system nodes<br />
showdomain - show domains in the system<br />
showdomainset - show sets of domains in the system<br />
showeeprom - show node eeprom information<br />
showeventlog - show event logs<br />
showfirmwaredb - show current database of firmware levels<br />
showhost - show host and host path information<br />
showhostset - show sets of hosts in the system<br />
showinventory - show hardware inventory<br />
showiscsisession - show iscsi sessions<br />
showld - show logical disks (LDs) in the system<br />
showldch - show LD to PD chunklet mapping<br />
showldmap - show LD to VV mapping<br />
showlicense - show installed license key<br />
shownet - show network configuration and status<br />
shownode - show node and its component information<br />
shownodeenv - show node environmental status (voltages,temperatures)<br />
showpatch - show what patches have been applied to the system<br />
showpd - show physical disks (PDs) in the system<br />
showpdata - show preserved data status<br />
showpdch - show status of selected chunklets of physical disks<br />
showpdvv - show PD to VV mapping<br />
showport - show Fibre Channel and iSCSI ports in the system<br />
showportarp - show ARP table for ports<br />
showportdev - show detailed information about devices on a Fibre Channel port<br />
showportisns - show iSNS host information for ports<br />
showportlesb - show Link Error Status Block information about devices on Fibre Channel port <br />
showrcopy - show remote copy configuration information<br />
showrctransport - show information about end-to-end transport for remote copy <br />
showrsv - show information about reservation and registration of VLUNs connected on a Fibre Channel port<br />
showsched - show scheduled tasks in the system<br />
showsnmppw - shows SNMP access passwords<br />
showsnmpmgr - show SNMP trap managers<br />
showspace - show estimated free space<br />
showspare - show information about spare and relocated chunklets<br />
showsshkey - show ssh public keys authorized by the current user<br />
showsys - show system information (system name, serial number etc.)<br />
showsysmgr - show system manager startup state<br />
showtarget - show unrecognized targets<br />
showtask - show information about tasks<br />
showtemplate - show templates<br />
showtoc - show system Table of Contents (TOC) summary<br />
showtocgen - show system Table of Contents (TOC) generation number<br />
showuser - show user accounts and SSH keys<br />
showuseracl - show user access control list<br />
showuserconn - show user connections<br />
showversion - show software versions<br />
showvlun - show virtual LUNs (VLUNs) in the system<br />
showvv - show virtual volumes (VVs) in the system<br />
showvvmap - show VV to LD mapping<br />
showvvpd - show VV distribution across PDs<br />
showvvset - show sets of VVs in the system<br />
checkhealth - perform checks to determine overall state of the system<br />
checkpassword - display authentication and authorization details<br />
checkport - perform loopback test on fc ports<br />
checkpd - perform surface scan or diagnostics on physical disks<br />
checkld - perform validity checks of data on logical disks<br />
checkvv - perform validity checks of virtual volume administrative information.<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/exchange&diff=1724
Windows/exchange
2021-03-04T12:49:26Z
<p>Cbs: /* DAG/Cluster stuff */</p>
<hr />
<div><br />
== PowerShell ==<br />
<br />
powershell commands<br />
<br />
<br />
=== possible access rights ===<br />
<br />
<pre><br />
The Access Rights parameters are as below:<br />
<br />
ReadItems: The user has the right to read items within the specified folder.<br />
CreateItems The user has the right to create items within the specified folder.<br />
EditOwnedItems The user has the right to edit the items that the user owns in the specified folder.<br />
DeleteOwnedItems The user has the right to delete items that the user owns in the specified folder.<br />
EditAllItems The user has the right to edit all items in the specified folder.<br />
DeleteAllItems The user has the right to delete all items in the specified folder.<br />
CreateSubfolders The user has the right to create subfolders in the specified folder.<br />
FolderOwner The user is the owner of the specified folder. The user has the right to view and move the folder and create subfolders. The user can’t read items, edit items, delete items, or create items.<br />
FolderContact The user is the contact for the specified public folder.<br />
FolderVisible The user can view the specified folder, but can’t read or edit items within the specified public folder.<br />
<br />
The Roles with which we can provide the access rights are as below:<br />
<br />
None FolderVisible<br />
Owner CreateItems, ReadItems, CreateSubfolders, FolderOwner, FolderContact, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingEditor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
Editor CreateItems, ReadItems, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingAuthor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
Author CreateItems, ReadItems, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
NonEditingAuthor CreateItems, ReadItems, FolderVisible<br />
Reviewer ReadItems, FolderVisible<br />
Contributor CreateItems, FolderVisible<br />
<br />
Ref: http://technet.microsoft.com/en-us/library/dd298062(v=exchg.150).aspx<br />
<br />
The following roles apply specifically to calendar folders:<br />
<br />
AvailabilityOnly View only availability data<br />
LimitedDetails View availability data with subject and location<br />
</pre><br />
<br />
<br />
=== create mailbox ===<br />
<br />
Create a new mailbox<br />
<br />
New-Mailbox -Name 'prospect NL' -Alias 'prospect.nl' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Rooms and Equipment' \<br />
-UserPrincipalName 'prospect.nl@arifleet.com' -SamAccountName 'prospect.nl' -FirstName 'prospect' -Initials '' -LastName 'NL' \<br />
-Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Stuttgart Mailbox DB One'<br />
<br />
<br />
=== create linked mailbox ===<br />
<br />
New-Mailbox -Name 'Koroch, Ernst' -Alias 'ekoroch' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Users' -UserPrincipalName \<br />
'ekoroch@arifleet.com' -SamAccountName 'ekoroch' -FirstName 'Ernst' -Initials '' -LastName 'Koroch' -Database 'Stuttgart Mailbox DB One' \<br />
-LinkedMasterAccount 'fleetservices\ekoroch' -LinkedDomainController 'dc03.fleetservices.intra' -LinkedCredential \<br />
'System.Management.Automation.PSCredential'<br />
<br />
<br />
=== Repair Mailbox ===<br />
<br />
see: [https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx]<br />
<br />
New-MailboxRepairRequest -Mailbox <Emailaddress> -CorruptionType SearchFolder,AggregateCounts,ProvisionedFolder,FolderView [-DetectOnly]<br />
<br />
<br />
=== Email-Enable AD Group ===<br />
<br />
Enable-DistributionGroup <ADGroupID> -PrimarySmtpAddress yadda@domain.tld<br />
<br />
<br />
=== add mailbox permissions ===<br />
<br />
Add full access to mailbox 'mailbox@arifleet.de' for user 'DOMAIN\user': <br />
<br />
Add-MailboxPermission -Identity mailbox@arifleet.de -User DOMAIN\user -AccessRights Fullaccess -InheritanceType All<br />
<br />
-AccessRights <right> <br/><br />
where <right> may be<br />
<br />
FullAccess<br />
ExternalAccount<br />
DeleteItem<br />
ReadPermission<br />
ChangePermission<br />
ChangeOwner<br />
<br />
disable auto-mapping of <br />
<br />
-Automapping $false<br />
<br />
<br />
=== remove mailbox permissions ===<br />
<br />
remove-MailboxPermission -Identity mailbox@arifleet.de -user domari\user -AccessRights Fullaccess -inheritance all<br />
<br />
<br />
=== add/remove 'Send as' permissions ===<br />
<br />
Add-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
You can grant the permissions by using Active Directory Users & Computers. Simply open the properties of the group, switch to the Security tab, add the mailbox user or group, and then tick the Send As box and apply the change. After making this change you may notice that it does not take effect for up to 2 hours. This is due to caching on the Exchange servers. Though you can speed up the change by restarting the Information Store that is obviously not going to be practical in most production environments, so you’ll often find that you just need to wait.<br />
<br />
Remove-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
<br />
==== 'Send as'/'SendOnBehalf' Distributiongroups ====<br />
<br />
Set-DistributionGroup <DistributionGroupName> -GrantSendOnBehalfTo USER@arifleet.com<br />
<br />
and sendOnBehalf for Distributiongroups<br />
<br />
<br />
<br />
==== SentItem Configuration ====<br />
<br />
Until Exchange 2010:<br />
<br />
Set-MailboxSentItemsConfiguration <ALIAS> -SendAsItemsCopiedTo SenderAndFrom<br />
<br />
Exchange 2016:<br />
<br />
Set-Mailbox -identity <UPN> [-DomainController <HOSTNAME>] -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true<br />
<br />
<br />
=== add mailbox folder permissions ===<br />
<br />
Add-MailboxFolderPermission -Identity poolcar@netcar24.com:\Calendar -user csteidl@arifleet.com -AccessRights [[Windows/exchange#possible_access_rights|<see RIGHTS>]]<br />
<br />
Set default-rights for ressource mailboxes (to show up subjects a.s.o.):<br />
<br />
Set-MailboxFolderPermission meetingroom:\Calendar -User Default -AccessRights Reviewer<br />
<br />
=== get mailbox permissions ===<br />
<br />
get permissions of fhess on mailbox prospect.be<br />
<br />
Get-MailboxPermission -Identity prospect.be@arifleet.com -User "fhess"<br />
<br />
<br />
get folder permissions<br />
<br />
get-mailboxfolderpermission -identity fhess<br />
<br />
<br />
get UPN of users<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.User.ADRecipient.UserPrincipalName }<br />
<br />
<br />
get full user details<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.identity.adrecipient.identity }<br />
<br />
<br />
<br />
=== Find permissions granted to spec. users ===<br />
<br />
Get-Mailbox -RecipientType 'UserMailbox' -ResultSize Unlimited | Get-MailboxPermission | where { $_.user.tostring() -eq "DOMAIN\username" -and $_.IsInherited -eq $false }<br />
<br />
<br />
<br />
=== enable autoreply / vacation message ===<br />
<br />
set the message (optionally) and enable auto reply<br />
<br />
$message = get-content message.txt<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState enabled \<br />
-ExternalAudience <none/all/known> \<br />
-InternalMessage "$message" \<br />
-ExternalMessage "$message"<br />
<br />
<br />
=== disable auto-reply / vacation message ===<br />
<br />
disable auto reply<br />
<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState disabled<br />
<br />
<br />
=== Retention policies ===<br />
<br />
create server side retention policies<br />
<br />
<br />
==== Create Retention Policy Tag ====<br />
<br />
New-RetentionPolicyTag "ARI STG - Delete all 180 days" -Type All -Comment "Deletes all items older 180 days" -RetentionEnabled $true \<br />
-AgeLimitForRetention 180 -RetentionAction DeleteAndAllowRecovery<br />
<br />
RetentionAction: MoveToFolder, MoveToDeletedItems, DeleteAndAllowRecovery, PermanentlyDelete, MoveToArchive<br />
<br />
<br />
==== Create Retention Policy ====<br />
<br />
New-RetentionPolicy "ARI STG - Delete ALL items older 180 days" -RetentionPolicyTagLinks "ARI STG - Delete all 180 days"<br />
<br />
Activate policy by: Open Mailbox Properties --> Mailbox Settings --> Messaging Records Mgmt --> Apply Retention policy<br />
<br />
<br />
=== get distribution group members ===<br />
<br />
get-distributiongroupmember <group><br />
<br />
get-distributiongroupmember mailaddress@arifleet.de<br />
<br />
<br />
=== get users by filter and add to distributiongroup ===<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -ne 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -eq 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
<br />
<br />
=== Get Mailbox by ExchangeGuid/Mapi-session ===<br />
<br />
get-mailbox -ResultSize unlimited | where {$_.ExchangeGuid -eq "265182e3-a31c-4a9f-e38e-687f5a7c2d6b"}<br />
<br />
<br />
=== Get Mailbox by Ressource type ===<br />
<br />
<br />
Get-Mailbox -RecipientTypeDetails RoomMailbox<br />
<br />
Get-Mailbox -RecipientTypeDetails EquipmentMailbox<br />
<br />
<br />
=== Get Mail Public folder ===<br />
<br />
Get-MailPublicFolder helpdesk@sub.domain.com | Get-PublicFolder [| Select *]<br />
<br />
<br />
=== Logging ===<br />
<br />
further logfiles can be found here:<br />
<br />
C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\ProtocolLog<br />
<br />
<br />
==== Track accross multiple servers ====<br />
<br />
get-transportserver<br />
<br />
<br />
e.g. that to "get-messagetrackinglog":<br />
<br />
get-transportserver | get-messagetrackinglog<br />
<br />
<br />
==== message tracking ====<br />
<br />
get-messagetrackinglog -Sender 'user@arifleet.de' -Start "5/04/2015 5:00:00 AM" -End "5/15/2015 8:30:00 AM"<br />
<br />
get-transportserver | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
get-transportservice | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
-Start "6/01/2015 5:00:00 AM" \<br />
-End "6/01/2015 10:30:00 AM" \<br />
-resultsize unlimited | ft -Wrap<br />
<br />
<pre><br />
-MessageSubject <String><br />
-Recipients <String[]><br />
-Start/-End (get-date).AddHours(-1).toString()<br />
-ResultSize Unlimited<br />
</pre><br />
<br />
some more examples:<br />
<br />
get-messagetrackinglog -Recipients:recipient@email.be -Start "6/8/2015 4:42:00 AM" -End "6/9/2015 9:52:00 PM" | Select *,{$_.Recipients} | export-csv .\maillog.csv<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | \<br />
where-object {$_.Recipients -like “*@gmail.com, *@yahoo.com” -AND $_.EventId -eq “Send”} |ft -auto >>C:\External mails.txt<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | sort -property Timestamp<br />
<br />
=== repair mailbox ===<br />
<br />
New-MailboxRepairRequest -Mailbox schaden@arifleet.de -CorruptionType SearchFolder<br />
<br />
<br />
-CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview<br />
-Archive Prueft Mailbox _und_ Archive<br />
-DetectOnly Prueft nur, keine Reparatur!<br />
<br />
Ergebnisse der Prüfung werden im Anwendungs Event-Log des Servers protokolliert. Die Events tragen die folgenden Ereignis-IDs:<br />
<br />
10044,10045,10046,10047,10048,10049,10050,10051,10059,10062<br />
<br />
mit einem rechtsklick auf 'Application' laesst dich das eventlog nach diesen ID's filtern.<br />
<br />
<br />
=== move mailbox between exchange-databases ===<br />
<br />
Move Mailboxes between exchange >= 2010 servers <br/><br />
the output is piped into 'ft' (format table) to get complete output and not stripped it...<br />
<br />
New-MoveRequest -Identity mailbox@arifleet.de -TargetDatabase ‘Whatever Database-Name 001’ | ft -AutoSize -Wrap<br />
<br />
create a batch<br />
<br />
Get-Mailbox -Database "Stuttgart Mailbox DB One" | Where-Object { $_.alias -like "jira*" } | New-MoveRequest -TargetDatabase [...]<br />
<br />
Options:<br />
<br />
-BadItemLimit 0<br />
-Suspend <br />
-SuspendComment "Resume after 11:00 p.m. PST"<br />
-SuspendWhenReadyToComplete<br />
-BatchName "Some Name to identify the Batch-Moves"<br />
<br />
get moverequest status:<br />
<br />
Get-MoveRequestStatistics "sadg"<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics | select DisplayName,alias,Status,TotalMailboxSize,PercentComplete| ft<br />
<br />
<br />
=== get Mailbox sizes ===<br />
<br />
Get-MailboxDatabase | Where-Object { $_.Name -like "STG*" } | Get-MailboxStatistics | sort -property TotalItemSize -desc \<br />
| select DisplayName,ItemCount,TotalItemSize,TotalDeletedItemSize |ft<br />
<br />
<br />
=== get database size ===<br />
<br />
Get-MailboxDatabase -status | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Sort-Object DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Where-Object { $_.name -like "STG*" } | Sort -property DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
=== Export Mailbox (Folder) ===<br />
<br />
New-MailboxExportRequest -mailbox schaden \<br />
-includefolders "******@arifleet.de/00 UNFALLORDNER ab 1.3.2011/Storopack R+V (*.***@*******.com) TK 150 \/ keine VK RA Schmid" \<br />
-filepath "\\stgwpvinfEXC01\g$\Storopack R+V (*.***@*******.com) TK 150_keine VK RA Schmid.pst"<br />
<br />
# be sure to mask e.g. '/' characters in foldernames with '\'<br />
# leave out '''-includefolders''' to export the entire mailbox<br/><br />
## add a '.../*' to -includefolders to include subfolders<br />
<br />
=== Search Mailbox content ===<br />
<br />
This one searches for all messages between 1/1/2017 and 12/31/2018 and creates copies of it within the Mailbox of targetmailbox into targetfolder:<br />
<br />
Search-Mailbox -Identity <USER-ID> -SearchQuery "received>=01/01/2017 AND received<=12/31/2018" -targetmailbox "<TARGET-USER-ID>" -targetfolder "SearchResults"<br />
<br />
<br />
=== set thumbnail-image ===<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
<br />
=== Import/Acivate new Certificate ===<br />
<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path c:\certificates\YOUR_CERTIFICATE.cer -Encoding byte -ReadCount 0))<br />
<br />
In case of encrypted .pfx or something like that:<br />
<br />
$pass = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -Password $pass -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path Webmail.pfx -Encoding byte -ReadCount 0))<br />
<br />
activate:<br />
<br />
Enable-ExchangeCertificate -Thumbprint 1234ae0567a72fccb75b1d0198628675333d010e -Services POP,IMAP,SMTP,IIS<br />
<br />
=== DAG/Cluster stuff ===<br />
<br />
Check who's master:<br />
<br />
Get-ClusterGroup EU-DAG<br />
<br />
<br />
Get detailed DAG info:<br />
<br />
Get-DatabaseAvailabilityGroup STG-DAG -status | fl<br />
<br />
<br />
Test replication health (do so on all cluster members):<br />
<br />
Test-ReplicationHealth -server EXC02<br />
<br />
<br />
Get mount status, copy/reply queue, Index state<br />
<br />
Get-MailboxDatabaseCopyStatus -server exc01<br />
<br />
<br />
Check Queues:<br />
<br />
get-queue -server stgwpvinfexc02<br />
<br />
<br />
Move queued messages to other server:<br />
<br />
Redirect-Message -Server Mailbox01 -Target Mailbox02<br />
<br />
<br />
Check service health (do so on all cluster members):<br/><br />
(test whether all the Microsoft Windows services that Exchange requires on a server have started)<br />
<br />
Test-servicehealth –server EXC02<br />
<br />
<br />
Test MapiConnectivity (Note: this will only test if the DB’s are mounted/active copy on the specific server):<br />
<br />
Test-MapiConnectivity -server EXC02<br />
<br />
<br />
Test/view replication:<br />
<br />
Get-MailboxdatabaseCopystatus -server EXC02<br />
<br />
<br />
Failover Cluster:<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup <br />
<br />
This will failover the 2 node cluster to the other node<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup -node EXC01<br />
<br />
This will failover the cluster to the node EXC01<br />
<br />
<br />
Move Databases:<br />
<br />
Move-ActiveMailboxDatabase DB3 -ActivateOnServer MBX4<br />
<br />
This example performs a switchover of the database DB3 to the Mailbox server MBX4. When the command completes, MBX4 hosts the active copy of DB3. Because the MountDialOverride parameter isn't specified, MBX4 mounts the database using a database auto mount dial setting of Lossless.<br />
<br />
<br />
Get-MailboxDatabase stg-* | Move-ActiveMailboxDatabase -ActivateOnServer MBX4<br />
<br />
Same as above, but moves all databases starting with 'STG-*' to MBX04<br />
<br />
<br />
Move-ActiveMailboxDatabase DB1 -ActivateOnServer MBX3 -MountDialOverride:GoodAvailability<br />
<br />
This example performs a switchover of the database DB1 to the Mailbox server MBX3. When the command completes, MBX3 hosts the active copy of DB1. Because the MountDialOverride parameter is specified with a value of Good Availability, MBX3 mounts the database using a database auto mount dial setting of GoodAvailability.<br />
<br />
== Outlook stuff ==<br />
<br />
=== get all add-ins ===<br />
<br />
Be aware that HKCU can only be grabbed if running in the user context!<br />
<br />
$searchScopes = "HKCU:\SOFTWARE\Microsoft\Office\Outlook\Addins","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins"<br />
$searchScopes | % {Get-ChildItem -Path $_ | % {Get-ItemProperty -Path $_.PSPath} | Select-Object @{n="Name";e={Split-Path $_.PSPath -leaf}},FriendlyName,Description} | Sort-Object -Unique -Property name<br />
<br />
<br />
== Transport stuff ==<br />
<br />
some stuff i used the GUI for<br />
<br />
<br />
=== Relay Configuration (GUI) ===<br />
<br />
Go:<br />
Server-Configuration --> Hub Transport --> Receive Connectors (Tab)<br />
<br />
- Select a valuable connector which matches you needs or create a new.<br />
- for me there was 'Relay internal' which was to allow anonymous connects from spec. hosts/nets --> Double-Click<br />
- Switch to 'Network'-Tab --> Add IP or rage to lower box.<br />
<br />
<br />
<br />
=== Max connection from single IP ===<br />
<br />
set-ReceiveConnector -Identity "exc03\Application_Relay" -MaxInboundConnectionPerSource 50<br />
<br />
sets the max inbound connections per source IP to 50 (default 20)<br />
<br />
<br />
<br />
=== Create an anonymous Receive Connector ===<br />
<br />
after you created an receive connector by GUI you will have to run:<br />
<br />
Get-ReceiveConnector "STGWPVINFEXC02\Application_Relay_Intern" | \<br />
Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"</div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1723
Windows/powershell
2021-03-02T14:49:04Z
<p>Cbs: /* Pull pending updates and install */</p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
Filter log by EventID:<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = $env:computername<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Hp/3PAR&diff=1722
Hp/3PAR
2021-02-26T12:01:40Z
<p>Cbs: </p>
<hr />
<div><br />
== Diag ==<br />
<br />
=== Infos for HP (creating Case) ===<br />
<br />
> showsys <br />
> showsys -d<br />
<br />
(System Information inclusing serial)<br />
<br />
<br />
> servicemag status <br />
<br />
(shows if any drive was already evacuated)<br />
<br />
<br />
> checkhealth pd<br />
<br />
(do healthcheck of physical disks)<br />
<br />
<br />
> showpd -s <br />
> showpd -state<br />
> showpd -s -failed<br />
> showpd -failed -degraded<br />
<br />
(show the state of all drives)<br />
<br />
<br />
> showpd -i <br />
<br />
(show the drive inventory including type and serial)<br />
<br />
<br />
> showport -sfp [-d]<br />
<br />
(show the SFP ports and their status [detailed list])<br />
<br />
=== showsys (System info) ===<br />
<br />
Help page<br />
<br />
<pre><br />
showsys - Show system information.<br />
<br />
SYNTAX<br />
showsys [options]<br />
<br />
DESCRIPTION<br />
The showsys command displays the HP 3PAR Storage system properties such as<br />
a system name, serial number, and system capacity information.<br />
<br />
AUTHORITY<br />
Any role in the system<br />
<br />
OPTIONS<br />
-d<br />
Specifies that more detailed information about the system is displayed.<br />
<br />
-param<br />
Specifies that the system parameters are displayed.<br />
<br />
-fan<br />
Displays the system fan information.<br />
<br />
-space<br />
Displays the system capacity information in MB (1024^2 bytes).<br />
<br />
-domainspace<br />
Displays the system capacity information broken down by domain in MB<br />
(1024^2 bytes).<br />
<br />
-desc<br />
Displays the system descriptor properties.<br />
<br />
-devtype FC|NL|SSD<br />
Displays the system capacity information where the disks must have a<br />
device type string matching the specified device type; either Fast<br />
Class (FC), Nearline (NL), Solid State Drive (SSD). This option can<br />
only be issued with the -space option.<br />
<br />
SPECIFIERS<br />
None.<br />
<br />
NOTES<br />
See setsys command for information on setting the threshold parameters<br />
indicated by the Value column in the output for showsys -param.<br />
<br />
In the output for showsys -param, (from configured settings) indicates that<br />
the system parameters displayed have been successfully read from the<br />
Persistent Repository (PR). If the PR is not available (most likely because<br />
of problems with the admin volume), the output reads (from default settings)<br />
and the values displayed would indicate the system defaults. When (from<br />
default settings) is displayed, system parameters cannot be updated.<br />
<br />
If the VVRetentionTimeMax is 0, then the volume retention time in the system<br />
is disabled.<br />
<br />
For the system capacity information, there might be some overlaps among<br />
Volumes, System, and Failed Capacities.<br />
<br />
EXAMPLES<br />
The following example displays the system descriptor properties of a HP 3PAR<br />
storage system:<br />
<br />
cli% showsys -desc<br />
------------System s36------------<br />
System Name : s36<br />
Location : Your Facility Address<br />
Owner : Your Company Name<br />
Contact : Joe Admin<br />
Comment : Your Notes<br />
<br />
The following example displays more detailed (-d option) information about<br />
the same storage server:<br />
<br />
cli% showsys -d<br />
------------General-------------<br />
System Name : S424<br />
System Model : HP_3PAR 7200<br />
Serial Number : 1600424<br />
System ID : 424<br />
Number of Nodes : 2<br />
Master Node : 0<br />
Nodes Online : 0,1<br />
Nodes in Cluster : 0,1<br />
<br />
-----System Capacity (MB)-----<br />
Total Capacity : 6277120<br />
Allocated Capacity : 687872<br />
Free Capacity : 5589248<br />
Failed Capacity : 0<br />
<br />
---------System Fan---------<br />
Primary Node ID : 0<br />
Secondary Node ID : 1<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
Primary Node ID : 1<br />
Secondary Node ID : 0<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
<br />
--------System Descriptors--------<br />
Location :<br />
Owner :<br />
Contact :<br />
Comment :<br />
</pre><br />
<br />
<br />
==== Space details ====<br />
<br />
> showsys -space<br />
<br />
<br />
=== Chech Hardware ===<br />
<br />
> admithw<br />
<br />
Check Hardware and try to fix issues. Initialize new disks<br />
<br />
<br />
=== IOPS Stats ===<br />
<br />
statvlun -ni -iter 1 -hostsum<br />
<br />
Output:<br />
<pre><br />
14:09:22 10/13/2018 r/w I/O per second KBytes per sec Svt ms IOSz KB <br />
Hostname Cur Avg Max Cur Avg Max Cur Avg Cur Avg Qlen<br />
FF1EPPINFVMH02 t 105 105 105 2278 2278 2278 0.42 0.42 21.7 21.7 0<br />
...<br />
</pre><br />
<br />
<br />
== Tuning ==<br />
<br />
=== Move VVs between CPGs ===<br />
<br />
[[Hp/3PAR#Move volume to another CPG using tunevv|Move volume to another CPG using tunevv]]<br />
<br />
<br />
=== Balance PDs ===<br />
<br />
If allocation of physical diskspace is not in balance through disks available.<br/><br />
Dry-Run:<br />
<br />
tunenodech -dr -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
NO Dry-Run:<br />
<br />
tunenodech -waittask -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
{{Achtung|Do this for all Nodes in your 3PAR environment after each other!! Just replace '-node 0' by '-node N'}}<br />
<br />
<br />
<br />
== CPGs ==<br />
<br />
=== Show CPGs ===<br />
<br />
<pre><br />
% showcpg<br />
----Volumes---- -Usage- -------------(MiB)-------------<br />
Id Name Warn% VVs TPVVs TDVVs Usr Snp Base Snp Free Total<br />
0 FC_r1 - 0 0 0 0 0 0 0 0 0<br />
1 FC_r5 - 35 35 0 35 34 3774976 14848 193536 3983360<br />
2 FC_r6 - 19 19 0 19 0 27048320 0 478208 27526528<br />
3 FC_Snap - 20 20 0 0 20 0 138752 51712 190464<br />
5 SSD_AO_R6 - 0 0 0 0 0 4998656 0 2560 5001216<br />
4 SSD_r5 - 0 0 0 0 0 2070144 0 37248 2107392<br />
--------------------------------------------------------------------------<br />
6 total 54 54 37892096 153600 763264 38808960<br />
</pre><br />
<br />
<br />
Show the Data Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sdg<br />
-----(MiB)------ <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 32768 -ssz 2 -ha cage -t r1 -p -devtype FC <br />
1 FC_r5 - - 32768 -ssz 6 -ha mag -t r5 -p -devtype FC <br />
2 FC_r6 - - 32768 -t r6 -ha mag -ssz 6 -ss 128 -p -devtype FC <br />
3 FC_Snap - - 32768 -t r6 -ha mag -ssz 8 -ss 64 -ch first -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -t r5 -ha mag -ssz 4 -ss 64 -ch first -p -devtype SSD<br />
4 SSD_r5 - - 8192 -t r5 -ha mag -ss 64 -p -devtype SSD<br />
</pre><br />
<br />
<br />
Show the Admin Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sag<br />
-----(MiB)----- <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 8192 -p -devtype FC -ha cage -p -devtype FC<br />
1 FC_r5 - - 8192 -p -devtype FC -p -devtype FC <br />
2 FC_r6 - - 8192 -ha mag -p -devtype FC <br />
3 FC_Snap - - 8192 -ha mag -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -ha mag -p -devtype SSD <br />
4 SSD_r5 - - 8192 -ha mag -p -devtype SSD<br />
</pre><br />
<br />
<br />
=== Create CPG ===<br />
<br />
% createcpg -t r6 -ha mag -sdgs 32G -ssz 8 -ss 128 -p -devtype FC <CPG_Name><br />
<br />
-t RAID Level<br/><br />
-ha HA Settings (port|cage|mag)<br/><br />
-sdgs Data-Growth Size<br/><br />
-ssz size_number_chunklets: 2 for RAID-1, 4 for RAID-5, and 8 for RAID-6<br/><br />
-p define a pattern / -devtype define a pattern for DevTypes to match<br/><br />
<br />
== Virtual Volumes ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Virtual Volumes ===<br />
<br />
showvv -listcols<br />
<br />
showvv -showcols Name,VV_WWN,SnpCPG<br />
<br />
<br />
=== Create Virtual Volume ===<br />
<br />
createvv -tpvv -pol zero_detect -snp_cpg FC_Snap FC_r6 FF3_VMW_AO_03 4194304<br />
<br />
<pre><br />
-Tpvv Thin provisions Virtual Volume<br />
-pol zero_detect I believe it is needed to thin luns<br />
-snp_cfg FC_Snap Where the writes will go for snapshots. HP refers to this as snap or copy space<br />
FF3_VMW_AO_03 Name: this is the lun name<br />
4194304 Size: This is the number to 4tb<br />
8388608 Size: 8tb<br />
</pre><br />
<br />
=== Move volume to another CPG using tunevv ===<br />
<br />
Assuming I want to move a virtual volume ('''VV12_AO''') to another new CPG ('''FC_r6'''):<br />
<br />
tunevv usr_cpg FC_r6 VV12_AO<br />
<br />
The logical disks used for user space are moved to CPG FC_r6 for virtual volume VV12_AO<br />
If you want to move the VV regions only use:<br />
<br />
tunevv usr_cpg FC_r6 -src_cpg FC_r5 VV12_AO<br />
<br />
<br />
Assuming I want to move a snapshot volume ('''VV12_AO''') to another new SnapCPG ('''FC_Snap'''):<br />
<br />
tunevv snp_cpg FC_Snap VV12_AO<br />
<br />
Unfortunatly you will have to run both commands seperatly. As of the documentation they can't be combined.<br />
<br />
<br />
== AO Config ==<br />
<br />
<pre><br />
createaocfg -t0cpg SSD_AO_R6 -t1cpg FC_r6 -mode performance -t0min 8T AO_CFG_FCR6<br />
setaocfg -t0min 10T AO_CFG_FCR6<br />
<br />
createsched "startao -btsecs -12h -etsecs -30m -maxrunh 12 -compact auto AO_CFG_FCR6" "0 18 * * 1-5" Task_AO-Run_FCR6<br />
<br />
startao -btsecs -6h -etsecs -1m -maxrunh 1 -compact auto AO_CFG_FCR6<br />
</pre><br />
<br />
== Auth LDAP ==<br />
<br />
yadda<br />
<br />
<br />
=== Set LDAP auth ===<br />
<br />
<pre><br />
setauthparam -f -clearall<br />
setauthparam -f ldap-server 10.30.111.112<br />
setauthparam -f ldap-server-hn STGWPVEURDC02.<DOMAIN>.<DOMAIN>.com<br />
setauthparam -f kerberos-realm <DOMAIN>.<DOMAIN>.com<br />
setauthparam -f binding sasl<br />
setauthparam -f sasl-mechanism GSSAPI<br />
setauthparam -f accounts-dn "OU=PrivilegedAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=com" <br />
setauthparam -f account-obj user<br />
setauthparam -f account-name-attr sAMAccountName <br />
setauthparam -f memberof-attr memberOf<br />
setauthparam -f super-map "CN=SAN_Admins,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
setauthparam -f browse-map "CN=SAN_ReadOnly,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
</pre><br />
<br />
Check that it works for you:<br />
<br />
checkpassword <LDAP-Username><br />
...<br />
...<br />
user <LDAP-Username> is authenticated and authorized<br />
<br />
=== Get LDAP auth config ===<br />
<br />
<pre><br />
% showauthparam<br />
Param --------------------------------------Value---------------------------------------<br />
ldap-server 10.30.111.106 <br />
ldap-server-hn DC05.<DOMAIN>.<TLD> <br />
kerberos-realm <DOMAIN>.<TLD> <br />
binding sasl <br />
sasl-mechanism GSSAPI<br />
[...]<br />
</pre><br />
<br />
<br />
== Network ==<br />
<br />
yadda<br />
<br />
<br />
=== get network settings ===<br />
<br />
<pre><br />
% shownet<br />
IP Address Netmask/PrefixLen Nodes Active Speed Duplex AutoNeg Status<br />
10.11.12.100 255.255.255.0 01 0 1000 Full Yes Active<br />
<br />
Default route : 10.11.12.1<br />
NTP server : 10.30.111.111<br />
DNS server : 10.11.12.42<br />
</pre><br />
<br />
<br />
=== set DNS server ===<br />
<br />
Add:<br />
<br />
setnet dns -add 10.30.111.111<br />
<br />
Remove:<br />
<br />
setnet dns -remove 10.30.111.111<br />
<br />
<br />
=== re-new expired certificates ===<br />
<br />
Show the actual cert:<br />
<br />
% showcert<br />
Service Commonname Type Enddate Fingerprint <br />
unified-server* HP_3PAR 8200-CZ3740W5MD cert Oct 16 15:36:12 2020 GMT bdae8ff911a32e50a65a81dbae656b46112fa992<br />
<br />
<br />
Renew the cert:<br />
<br />
<pre><br />
createcert unified-server -selfsigned -CN 3par.yadda.com -SAN DNS:3par-alias.yadda.com,DNS:10.12.13.14<br />
The following services will be restarted if currently running:<br />
cim: manages communications with SMI-S clients<br />
<br />
wsapi: Web Services API server<br />
<br />
Continue creating self-signed certificate (yes/no)? yes<br />
Self-signed certificate created.<br />
cimserver restarted<br />
The Web Services API server stopped successfully.<br />
<br />
The Web Services API Server will start shortly.<br />
</pre><br />
<br />
Done!<br />
<br />
<br />
== Full Command List ==<br />
<br />
<pre><br />
HP 3PAR CLI command list<br />
<br />
showalert - show status of system alerts<br />
showauthparam - show authentication parameters<br />
showbattery - show battery status information<br />
showblock - show block mapping info for vvs, lds, pds<br />
showcage - show disk cage information<br />
showcim - show the CIM server information<br />
showclienv - show CLI environment parameters<br />
showcpg - show Common Provisioning Groups (CPGs)<br />
showdate - show date and time on all system nodes<br />
showdomain - show domains in the system<br />
showdomainset - show sets of domains in the system<br />
showeeprom - show node eeprom information<br />
showeventlog - show event logs<br />
showfirmwaredb - show current database of firmware levels<br />
showhost - show host and host path information<br />
showhostset - show sets of hosts in the system<br />
showinventory - show hardware inventory<br />
showiscsisession - show iscsi sessions<br />
showld - show logical disks (LDs) in the system<br />
showldch - show LD to PD chunklet mapping<br />
showldmap - show LD to VV mapping<br />
showlicense - show installed license key<br />
shownet - show network configuration and status<br />
shownode - show node and its component information<br />
shownodeenv - show node environmental status (voltages,temperatures)<br />
showpatch - show what patches have been applied to the system<br />
showpd - show physical disks (PDs) in the system<br />
showpdata - show preserved data status<br />
showpdch - show status of selected chunklets of physical disks<br />
showpdvv - show PD to VV mapping<br />
showport - show Fibre Channel and iSCSI ports in the system<br />
showportarp - show ARP table for ports<br />
showportdev - show detailed information about devices on a Fibre Channel port<br />
showportisns - show iSNS host information for ports<br />
showportlesb - show Link Error Status Block information about devices on Fibre Channel port <br />
showrcopy - show remote copy configuration information<br />
showrctransport - show information about end-to-end transport for remote copy <br />
showrsv - show information about reservation and registration of VLUNs connected on a Fibre Channel port<br />
showsched - show scheduled tasks in the system<br />
showsnmppw - shows SNMP access passwords<br />
showsnmpmgr - show SNMP trap managers<br />
showspace - show estimated free space<br />
showspare - show information about spare and relocated chunklets<br />
showsshkey - show ssh public keys authorized by the current user<br />
showsys - show system information (system name, serial number etc.)<br />
showsysmgr - show system manager startup state<br />
showtarget - show unrecognized targets<br />
showtask - show information about tasks<br />
showtemplate - show templates<br />
showtoc - show system Table of Contents (TOC) summary<br />
showtocgen - show system Table of Contents (TOC) generation number<br />
showuser - show user accounts and SSH keys<br />
showuseracl - show user access control list<br />
showuserconn - show user connections<br />
showversion - show software versions<br />
showvlun - show virtual LUNs (VLUNs) in the system<br />
showvv - show virtual volumes (VVs) in the system<br />
showvvmap - show VV to LD mapping<br />
showvvpd - show VV distribution across PDs<br />
showvvset - show sets of VVs in the system<br />
checkhealth - perform checks to determine overall state of the system<br />
checkpassword - display authentication and authorization details<br />
checkport - perform loopback test on fc ports<br />
checkpd - perform surface scan or diagnostics on physical disks<br />
checkld - perform validity checks of data on logical disks<br />
checkvv - perform validity checks of virtual volume administrative information.<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/powershell&diff=1721
Windows/powershell
2021-02-22T13:27:12Z
<p>Cbs: </p>
<hr />
<div><br />
Snippets for powershell<br/><br />
Note that Exchange-related powershell commands should be listed [[Windows/exchange|here]]<br/><br />
<br />
== execution policy ==<br />
<br />
Set-ExecutionPolicy Unrestricted<br />
<br />
possible values:<br />
<br />
help about_Execution_Policies<br />
<br />
<br />
== external AD-snapin ==<br />
<br />
[http://software.dell.com/products/active-roles/powershell.aspx http://software.dell.com/products/active-roles/powershell.aspx]<br />
<br />
Nach der Installation dann mit folgendem command einbinden:<br />
<br />
Add-PSSnapin Quest.ActiveRoles.ADManagement<br />
<br />
Und damit kannst du dann tolle Sachen machen wie: <br />
<br />
Get-QADGroup -ContainsMember username<br />
<br />
<br />
<br />
== get loadable modules ==<br />
<br />
Get-Module -ListAvailable<br />
<br />
<br />
== import system modules ==<br />
<br />
ImportSystemModules<br />
<br />
<br />
=== VEEAM Snapin ===<br />
<br />
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue<br />
<br />
== Remoting ==<br />
<br />
Enter-PSSession -computername <computername><br />
[<computername>]: PS C:\><br />
<br />
<br />
== Set Systemvariables (persistent) ==<br />
<br />
[Environment]::SetEnvironmentVariable("CHRIS", "Yadda", "Machine")<br />
<br />
# Variable Name<br />
# Value<br />
# Scope: User or Machine<br />
<br />
To see such changes you need to start a new Powershell window<br/><br />
and enter:<br />
<br />
Get-ChildItem env:<br />
<br />
or<br />
<br />
Get-ChildItem env:CHRIS<br />
<br />
or<br />
<br />
Get-ChildItem env:CHR*<br />
<br />
<br />
== get/set registry keys ==<br />
<br />
get item(s):<br />
<br />
Get-ItemProperty 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\...' | fl<br />
<br />
new folder:<br />
<br />
New-Item -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create' -Force | Out-Null<br />
<br />
new item:<br />
<br />
New-ItemProperty -Path 'Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOME\Path\Create\' -Name MyVar -Value 1 -PropertyType DWORD -Force | Out-Null<br />
<br />
<br />
== set AD password ==<br />
<br />
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force)<br />
<br />
<br />
== Clean WinSxS folder ==<br />
<br />
to remove unneeded stuff from c:\windows\WinSxS\*.* <br/><br />
do the following:<br />
<br />
Get-WindowsFeature | where-object{$_.Installed -eq 0 -and $_.InstallState -eq 'Available'} | uninstall-windowsfeature -remove<br />
<br />
<br />
== get/set netconnectionprofile ==<br />
<br />
<pre><br />
PS C:\> Get-NetConnectionProfile<br />
<br />
Name : arifleet.com<br />
InterfaceAlias : Internal<br />
InterfaceIndex : 1<br />
NetworkCategory : DomainAuthenticated<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
Name : Network<br />
InterfaceAlias : Internet<br />
InterfaceIndex : 3<br />
NetworkCategory : Public<br />
IPv4Connectivity : LocalNetwork<br />
IPv6Connectivity : LocalNetwork<br />
<br />
PS C:\> Set-NetConnectionProfile -InterfaceIndex 3 -NetworkCategory Private<br />
</pre><br />
<br />
If a Domain Network (VPN interface or such) is detected as 'Private' instead of DomainAuthenticated,<br/><br />
restart the 'Network Location Awareness' Service: NlaSvc<br />
<br />
Get-Service *nlasvc* | Restart-Service -force<br />
<br />
== get primary DC (PDC) ==<br />
<br />
Netdom Query Fsmo<br />
<br />
Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br />
<br />
Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster<br />
<br />
== Logging ==<br />
<br />
Filter log by EventID:<br />
<br />
Get-EventLog -LogName "Directory Service" -after $startdate | where { $_.eventid -eq 2889 } | `<br />
select Source, EventID, InstanceId, Message | Export-Csv c:\eventID_2889.csv ";"<br />
<br />
<br />
== get last logon user ==<br />
<br />
RPC-Call:<br />
<br />
(Get-WmiObject -Class win32_process -ComputerName $c | Where-Object name -Match explorer).getowner().user<br />
<br />
<br />
== get currently logged on user ==<br />
<br />
query user /server:$env:computername<br />
<br />
== get uptime of system ==<br />
<br />
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime<br />
<br />
<br />
== timeserver settings ==<br />
<br />
query source servers:<br />
<br />
w32tm /query /source<br />
<br />
<br />
set source servers:<br />
<br />
<pre><br />
net stop w32time; <br />
w32tm /config /syncfromflags:manual /manualpeerlist:10.2.8.3;<br />
w32tm /config /reliable:yes;<br />
net start w32time;<br />
</pre><br />
<br />
Without stopping w32time:<br />
<br />
w32tm /config /syncfromflags:manual /manualpeerlist:"time.domain.tld time2.domain.tld" /reliable:yes /update<br />
<br />
Sync with timeservers:<br />
<br />
w32tm /resync /force<br />
<br />
== Get Service names ==<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Select name<br />
<br />
<br />
get services and run state:<br />
<br />
Get-Service | Where-Object {$_.displayName.contains("smartFIX ")}<br />
<br />
or (simulate case insensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.toLower().contains("smartfix ")}<br />
<br />
<br />
get list of services that start with watch* (case sensitive)<br />
<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Start-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Stop-Service<br />
Get-Service | Where-Object {$_.displayName.StartsWith("watch")} | Restart-Service<br />
<br />
<br />
== Bitlocker ==<br />
<br />
get-tpm<br />
<br />
Initialize-Tpm<br />
<br />
Get-BitLockerVolume<br />
<br />
Enable-BitLocker -TpmProtector C:<br />
<br />
Enable-BitLocker -RecoveryPasswordProtector C:<br />
<br />
<br />
== Software ==<br />
<br />
=== get software installed ===<br />
<br />
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize<br />
<br />
or<br />
<br />
Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
<br />
<br />
=== remove/uninstall software ===<br />
<br />
<pre><br />
$b = Get-WmiObject -Class win32_product [-ComputerName hvs00] -Filter "Name like '%symantec%'"<br />
$b.Uninstall()<br />
<br />
__GENUS : 2<br />
__CLASS : __PARAMETERS<br />
__SUPERCLASS :<br />
__DYNASTY : __PARAMETERS<br />
__RELPATH :<br />
__PROPERTY_COUNT : 1<br />
__DERIVATION : {}<br />
__SERVER :<br />
__NAMESPACE :<br />
__PATH :<br />
ReturnValue : 0 <-- Check ReturnValue is equal 0<br />
PSComputerName :<br />
</pre><br />
<br />
== get-pendingreboot ==<br />
<br />
Source: [[https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542 https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542]]<br />
<br />
<pre><br />
Function Get-PendingReboot<br />
{<br />
<#<br />
.SYNOPSIS<br />
Gets the pending reboot status on a local or remote computer.<br />
<br />
.DESCRIPTION<br />
This function will query the registry on a local or remote computer and determine if the<br />
system is pending a reboot, from Microsoft updates, Configuration Manager Client SDK, Pending Computer <br />
Rename, Domain Join or Pending File Rename Operations. For Windows 2008+ the function will query the <br />
CBS registry key as another factor in determining pending reboot state. "PendingFileRenameOperations" <br />
and "Auto Update\RebootRequired" are observed as being consistant across Windows Server 2003 & 2008.<br />
<br />
CBServicing = Component Based Servicing (Windows 2008+)<br />
WindowsUpdate = Windows Update / Auto Update (Windows 2003+)<br />
CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value<br />
PendComputerRename = Detects either a computer rename or domain join operation (Windows 2003+)<br />
PendFileRename = PendingFileRenameOperations (Windows 2003+)<br />
PendFileRenVal = PendingFilerenameOperations registry value; used to filter if need be, some Anti-<br />
Virus leverage this key for def/dat removal, giving a false positive PendingReboot<br />
<br />
.PARAMETER ComputerName<br />
A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).<br />
<br />
.PARAMETER ErrorLog<br />
A single path to send error data to a log file.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize<br />
<br />
Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending<br />
-------- ----------- ------------- ------------ -------------- -------------- -------------<br />
DC01 False False False False<br />
DC02 False False False False<br />
FS01 False False False False<br />
<br />
This example will capture the contents of C:\ServerList.txt and query the pending reboot<br />
information from the systems contained in the file and display the output in a table. The<br />
null values are by design, since these systems do not have the SCCM 2012 client installed,<br />
nor was the PendingFileRenameOperations value populated.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-PendingReboot<br />
<br />
Computer : WKS01<br />
CBServicing : False<br />
WindowsUpdate : True<br />
CCMClient : False<br />
PendComputerRename : False<br />
PendFileRename : False<br />
PendFileRenVal : <br />
RebootPending : True<br />
<br />
This example will query the local machine for pending reboot information.<br />
<br />
.EXAMPLE<br />
PS C:\> $Servers = Get-Content C:\Servers.txt<br />
PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation<br />
<br />
This example will create a report that contains pending reboot information.<br />
<br />
.LINK<br />
Component-Based Servicing:<br />
http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx<br />
<br />
PendingFileRename/Auto Update:<br />
http://support.microsoft.com/kb/2723674<br />
http://technet.microsoft.com/en-us/library/cc960241.aspx<br />
http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx<br />
<br />
SCCM 2012/CCM_ClientSDK:<br />
http://msdn.microsoft.com/en-us/library/jj902723.aspx<br />
<br />
.NOTES<br />
Author: Brian Wilhite<br />
Email: bcwilhite (at) live.com<br />
Date: 29AUG2012<br />
PSVer: 2.0/3.0/4.0/5.0<br />
Updated: 27JUL2015<br />
UpdNote: Added Domain Join detection to PendComputerRename, does not detect Workgroup Join/Change<br />
Fixed Bug where a computer rename was not detected in 2008 R2 and above if a domain join occurred at the same time.<br />
Fixed Bug where the CBServicing wasn't detected on Windows 10 and/or Windows Server Technical Preview (2016)<br />
Added CCMClient property - Used with SCCM 2012 Clients only<br />
Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter<br />
Removed $Data variable from the PSObject - it is not needed<br />
Bug with the way CCMClientSDK returned null value if it was false<br />
Removed unneeded variables<br />
Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry<br />
Removed .Net Registry connection, replaced with WMI StdRegProv<br />
Added ComputerPendingRename<br />
#><br />
<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]<br />
[Alias("CN","Computer")]<br />
[String[]]$ComputerName="$env:COMPUTERNAME",<br />
[String]$ErrorLog<br />
)<br />
<br />
Begin { }## End Begin Script Block<br />
Process {<br />
Foreach ($Computer in $ComputerName) {<br />
Try {<br />
## Setting pending values to false to cut down on the number of else statements<br />
$CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false<br />
<br />
## Setting CBSRebootPend to null since not all versions of Windows has this value<br />
$CBSRebootPend = $null<br />
<br />
## Querying WMI for build version<br />
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop<br />
<br />
## Making registry connection to the local/remote computer<br />
$HKLM = [UInt32] "0x80000002"<br />
$WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"<br />
<br />
## If Vista/2008 & Above query the CBS Reg Key<br />
If ([Int32]$WMI_OS.BuildNumber -ge 6001) {<br />
$RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")<br />
$CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"<br />
}<br />
<br />
## Query WUAU from the registry<br />
$RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")<br />
$WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"<br />
<br />
## Query PendingFileRenameOperations from the registry<br />
$RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")<br />
$RegValuePFRO = $RegSubKeySM.sValue<br />
<br />
## Query JoinDomain key from the registry - These keys are present if pending a reboot from a domain join operation<br />
$Netlogon = $WMI_Reg.EnumKey($HKLM,"SYSTEM\CurrentControlSet\Services\Netlogon").sNames<br />
$PendDomJoin = ($Netlogon -contains 'JoinDomain') -or ($Netlogon -contains 'AvoidSpnSet')<br />
<br />
## Query ComputerName and ActiveComputerName from the registry<br />
$ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName") <br />
$CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")<br />
<br />
If (($ActCompNm -ne $CompNm) -or $PendDomJoin) {<br />
$CompPendRen = $true<br />
}<br />
<br />
## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true<br />
If ($RegValuePFRO) {<br />
$PendFileRename = $true<br />
}<br />
<br />
## Determine SCCM 2012 Client Reboot Pending Status<br />
## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0<br />
$CCMClientSDK = $null<br />
$CCMSplat = @{<br />
NameSpace='ROOT\ccm\ClientSDK'<br />
Class='CCM_ClientUtilities'<br />
Name='DetermineIfRebootPending'<br />
ComputerName=$Computer<br />
ErrorAction='Stop'<br />
}<br />
## Try CCMClientSDK<br />
Try {<br />
$CCMClientSDK = Invoke-WmiMethod @CCMSplat<br />
} Catch [System.UnauthorizedAccessException] {<br />
$CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue<br />
If ($CcmStatus.Status -ne 'Running') {<br />
Write-Warning "$Computer`: Error - CcmExec service is not running."<br />
$CCMClientSDK = $null<br />
}<br />
} Catch {<br />
$CCMClientSDK = $null<br />
}<br />
<br />
If ($CCMClientSDK) {<br />
If ($CCMClientSDK.ReturnValue -ne 0) {<br />
Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)" <br />
}<br />
If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {<br />
$SCCM = $true<br />
}<br />
}<br />
<br />
Else {<br />
$SCCM = $null<br />
}<br />
<br />
## Creating Custom PSObject and Select-Object Splat<br />
$SelectSplat = @{<br />
Property=(<br />
'Computer',<br />
'CBServicing',<br />
'WindowsUpdate',<br />
'CCMClientSDK',<br />
'PendComputerRename',<br />
'PendFileRename',<br />
'PendFileRenVal',<br />
'RebootPending'<br />
)}<br />
New-Object -TypeName PSObject -Property @{<br />
Computer=$WMI_OS.CSName<br />
CBServicing=$CBSRebootPend<br />
WindowsUpdate=$WUAURebootReq<br />
CCMClientSDK=$SCCM<br />
PendComputerRename=$CompPendRen<br />
PendFileRename=$PendFileRename<br />
PendFileRenVal=$RegValuePFRO<br />
RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)<br />
} | Select-Object @SelectSplat<br />
<br />
} Catch {<br />
Write-Warning "$Computer`: $_"<br />
## If $ErrorLog, log the file to a user specified location/path<br />
If ($ErrorLog) {<br />
Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append<br />
}<br />
}<br />
}## End Foreach ($Computer in $ComputerName)<br />
}## End Process<br />
<br />
End { }## End End<br />
<br />
}## End Function Get-PendingReboot<br />
</pre><br />
<br />
<br />
== Get Group Memberships of AD-Object ==<br />
<br />
Get-ADPrincipalGroupMembership -identity <USER><br />
<br />
<br />
== Search/Filter Users ==<br />
<br />
Get-ADUser reference: [https://technet.microsoft.com/en-us/library/ee617241.aspx @M$]<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=Fleetservices User,DC=fleetservices,DC=intra' \<br />
-Server 'Fleetservices.intra'<br />
<br />
or export result to CSV-File<br />
<br />
Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title -SearchBase 'OU=HPI,DC=fleet,DC=int' \<br />
-Server 'Fleet.int' | Export-CSV c:\temp\FleetInt.csv<br />
<br />
get logon scripts of ad-users:<br />
<br />
Get-ADUser -filter * -SearchBase "OU=Eschborn,OU=UserAccounts,OU=Accounts,DC=europe,DC=arifleet,DC=com" \<br />
-properties name,scriptpath | select name,scriptpath<br />
<br />
<br />
get 'password never expires' flag:<br />
<br />
get-aduser -filter * -SearchBase "OU=Accounts,DC=europe,DC=arifleet,DC=com" -properties Name,PasswordNeverExpires,Enabled | `<br />
where { $_.passwordNeverExpires -eq "true" -and $_.Enabled -eq "true"} | `<br />
select SamAccountName,PasswordNeverExpires,Enabled,DistinguishedName | `<br />
sort -property SamAccountName | select-string -pattern "OU=ServiceAccounts" -notMatch<br />
<br />
<br />
=== Bulk-Replace UPN domain of users ===<br />
<br />
<pre><br />
Import-Module ActiveDirectory<br />
$oldSuffix = "olddomain.tld"<br />
$newSuffix = "newdomain.tld"<br />
$ou = "OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=europe,DC=newdomain,DC=tld"<br />
$server = "localhost"<br />
<br />
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {<br />
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)<br />
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn<br />
}<br />
</pre><br />
<br />
=== Bulk-Clear Manager from AD Users ===<br />
<br />
<pre><br />
$OU = "OU=Obsolete,DC=dom,DC=domain,DC=tld"<br />
$users = get-aduser -Filter { mail -like "*" -and ObjectClass -eq "user" } -SearchBase $OU -Properties sAMAccountName,manager<br />
<br />
# list managers<br />
$users.manager<br />
<br />
$users | Set-ADUser -Manager $null<br />
</pre><br />
<br />
== Search/Filter Computers ==<br />
<br />
Get-ADComputer -SearchBase 'OU=Build,OU=MemberServers,dc=europe,dc=arifleet,dc=com' -Filter '*'<br />
<br />
<br />
== Bulk change Group Scope ==<br />
<br />
<pre><br />
$MySearchBase = "ou=Groups,ou=ABC,dc=lab,dc=local"<br />
<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Global"' -SearchBase "$MySearchBase"<br />
<br />
# Print list<br />
$MyGroupList.name<br />
<br />
# Set scope<br />
$MyGroupList | Set-ADGroup -GroupScope Universal<br />
<br />
# Now we can change to DomainLocal<br />
$MyGroupList = get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "Universal"' -SearchBase "$MySearchBase"<br />
<br />
$MyGroupList.name<br />
<br />
$MyGroupList | Set-ADGroup -GroupScope DomainLocal<br />
</pre><br />
<br />
<br />
== DNS ==<br />
<br />
=== set secure zone transfer servers ===<br />
<br />
For all Zones:<br />
<br />
Get-DnsServerZone | Select-Object zonename | Set-DnsServerPrimaryZone -SecureSecondaries TransferToSecureServers -SecondaryServers <IP-1>,<IP-2>,<IP-n><br />
<br />
<br />
== File operations ==<br />
<br />
=== create shortcut ===<br />
<br />
<pre><br />
$WshShell = New-Object -comObject WScript.Shell<br />
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\NAME.lnk")<br />
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\NAME.exe"<br />
$Shortcut.Save()<br />
</pre><br />
<br />
<br />
=== robocopy ===<br />
<br />
robocopy F:\SOURCE D:\DESTINATION\ /MIR /FFT /Z /W:5 /tee /log:RobocopySync.log<br />
<br />
# '''/MIR''' specifies that robocopy should mirror the source directory and the destination directory. Beware that this may delete files at the destination.<br />
# '''/FFT''' uses fat file timing instead of NTFS. This means the granularity is a bit less precise.<br />
# '''/W:5''' reduces the wait time between failures to 5 seconds instead of the 30 second default.<br />
# '''/R:2''' reduces the repeat count of failures to 2 tries instead of the 1000000(!) default retries.<br />
# '''/Z''' ensures robocopy can resume the transfer of a large file in mid-file instead of restarting.<br />
# '''/B''' copy files in Backup mode.<br />
# '''/ZB''' use restartable mode; if access denied use Backup mode.<br />
# '''/MT[:n]''' Do multi-threaded copies with n threads (default 8).<br />
# '''/CREATE''' creates directories and zero-length files only.<br />
# '''/XF file [file]...''' eXclude Files matching given names/paths/wildcards.<br />
# '''/XD dirs [dirs]...''' eXclude Directories matching given names/paths.<br />
# '''/XA:H''' makes robocopy ignore hidden files, usually these will be system files that we’re not interested in.<br />
# '''/log:RobocopySync.log''' write output into logfile instead stdout. Use in combination with '''/tee''' to get output to stdout AND logfile<br />
# '''/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).<br />
# '''/COPYALL''' Same as /COPY:DATSOU)<br />
<br />
<br />
<br />
== set thumbnail-image ==<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
== get .Net Version installed ==<br />
<br />
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get name,version<br />
<br />
<br />
== List files/folderstructure recursively ==<br />
<br />
List files including their relative path and output full UNC Path:<br />
<br />
<pre><br />
foreach ($myfile in $(ls -R -Name "\\SERVER\Share$\folder\foo\")) {<br />
$out = "\\SERVER\Share$\folder\foo\" + $myfile<br />
echo $out >> ./fileList.txt<br />
}<br />
</pre><br />
<br />
<br />
== List shared folders ==<br />
<br />
get-WmiObject -class Win32_Share <br />
<br />
<br />
== get ACL folder permissions ==<br />
<br />
get-acl C:\folder | Format-List<br />
<br />
<pre><br />
$children = get-childitem e:\<br />
<br />
foreach($child in $children) {<br />
echo $child.name<br />
(get-acl e:\$child).access | ft -auto IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags<br />
echo ""<br />
echo ""<br />
}<br />
</pre><br />
<br />
<br />
== set/remove ACL folder permissions ==<br />
<br />
Traverse through whole tree:<br />
<br />
<pre><br />
foreach ($folder in Get-ChildItem -Path .\Programme -Recurse -Directory) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($false, $true) # Inheritance on<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
This folder only:<br />
<br />
<pre><br />
foreach ($folder in get-item \\<server>\e$\Folder) {<br />
$AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("domain\user", "ListDirectory", "None", "None", "Allow")<br />
$acl = Get-Acl $folder.fullname<br />
$acl.SetAccessRuleProtection($true, $false) # Inheritance off<br />
$acl.SetAccessRule($AccessRule)<br />
Set-Acl -Path $folder.FullName -AclObject $acl<br />
}<br />
</pre><br />
<br />
<br />
Remove permissions by DOMAIN:<br />
<br />
<pre><br />
$acl = Get-Acl D:\path\to\folder<br />
$rules = $acl.access | Where-Object {<br />
(-not $_.IsInherited) -and<br />
$_.IdentityReference -like "DOMAIN\*"<br />
}<br />
<br />
foreach($rule in $rules) {<br />
$acl.RemoveAccessRule($rule)<br />
}<br />
</pre><br />
<br />
Remove a User/Group completely from ACLs:<br/><br />
(This includes all Allow AND Deny rules)<br />
<br />
<pre><br />
$acl = Get-Acl D:\path<br />
$usersid = New-Object System.Security.Principal.Ntaccount("CREATOR OWNER")<br />
$acl.PurgeAccessRules($usersid)<br />
$acl | Set-Acl D:\path<br />
</pre><br />
<br />
== get/set/copy NTFS permissions ==<br />
<br />
Copy some folder eg. E:\Data to F:\DataNew <br/><br />
<br/><br />
Since the old and new foldernames differ, we'll have to get the permissions of the root folder:<br />
<br />
cd E:\data<br />
icacls . /save ..\DATA-root_perms.txt /c<br />
<br />
now we tell icacls that it should get the content of our root folder and traverse (/t) through folder-structure:<br />
<br />
icacls .\ /save ..\DATA_perms.txt /c /t<br />
<br />
now we have 2 permission files which we can restore on the new folder:<br />
<br />
cd F:\DataNew<br />
icacls . /restore E:\DATA-root_perms.txt /c<br />
icacls .\ /restore E:\DATA_perms.txt /c<br />
<br />
If you have the same folder name, e.g. you copy from E:\data to F:\data you can do this:<br />
<br />
cd e:<br />
icacls .\Data /save .\DATA_perms.txt /c /t<br />
icacls F: /restore E:\DATA_perms.txt /c<br />
<br />
where:<br />
<br />
/t Traverse through folders<br />
/c Continue on errors<br />
<br />
<br />
<br />
== setspn ==<br />
<br />
List SPN:<br />
<br />
setspn -L <accountname><br />
<br />
setspn -L <hostname><br />
<br />
Register new SPN:<br />
<br />
setspn -R <server><br />
<br />
It will register SPN "HOST/server" and "HOST/{DNS of server}"<br/><br/><br />
<br />
Register additional SPN (alias) for <server>:<br />
<br />
setspn -S host/<serveralias> <server><br />
<br />
<br />
== winMTR.ps1 ==<br />
<br />
<pre><br />
<#<br />
.SYNOPSIS<br />
An MTR clone for PowerShell.<br />
Written by Tyler Applebaum.<br />
Version 2.0<br />
<br />
.LINK<br />
https://gist.github.com/tylerapplebaum/dc527a3bd875f11871e2<br />
http://www.team-cymru.org/IP-ASN-mapping.html#dns<br />
<br />
.DESCRIPTION<br />
Runs a traceroute to a specified target; sends ICMP packets to each hop to measure loss and latency.<br />
Big shout out to Team Cymru for the ASN resolution.<br />
Thanks to DrDrrae for a bugfix on PowerShell v5<br />
<br />
.PARAMETER Target<br />
Input must be in the form of an IP address or FQDN. Should be compatible with most TLDs.<br />
<br />
.PARAMETER PingCycles<br />
Specifies the number of ICMP packets to send per hop. Default is 10.<br />
<br />
.PARAMETER DNSServer<br />
An optional parameter to specify a different DNS server than configured on your network adapter.<br />
<br />
.INPUTS<br />
System.String, System.Int32<br />
<br />
.OUTPUTS<br />
PSObject containing the traceroute results. Also saves a file to the desktop.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute 8.8.4.4 -b 512<br />
Runs a traceroute to 8.8.4.4 with 512-byte ICMP packets.<br />
<br />
.EXAMPLE<br />
PS C:\> Get-Traceroute amazon.com -s 75.75.75.75 -f amazon.com<br />
Runs a traceroute to amazon.com using 75.75.75.75 as the DNS resolver and saves the output as amazon.com.txt.<br />
#><br />
<br />
#Requires -version 4<br />
[CmdletBinding()]<br />
param(<br />
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]<br />
[String]$Target,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("c")]<br />
[ValidateRange(5,100)]<br />
[int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("b")]<br />
[ValidateRange(32,1000)]<br />
[int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("s")]<br />
[IPAddress]$DNSServer = $Null,<br />
<br />
[Parameter(ValueFromPipeline)]<br />
[Alias("f")]<br />
[String]$Filename = "Traceroute_$Target"<br />
<br />
)<br />
Function script:Set-Variables {<br />
$PerTraceArr = @()<br />
$script:ASNOwnerArr = @()<br />
$ASNOwnerObj = New-Object PSObject<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")<br />
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.<br />
$script:i = 0<br />
$script:x = 0<br />
$script:z = 0<br />
$script:WHOIS = ".origin.asn.cymru.com"<br />
$script:ASNWHOIS = ".asn.cymru.com"<br />
} #End Set-Variables<br />
<br />
Function script:Set-WindowSize {<br />
$Window = $Host.UI.RawUI<br />
If ($Window.BufferSize.Width -lt 175 -OR $Window.WindowSize.Width -lt 175) {<br />
$NewSize = $Window.BufferSize<br />
$NewSize.Height = 3000<br />
$NewSize.Width = 175<br />
$Window.BufferSize = $NewSize<br />
<br />
$NewSize = $Window.WindowSize<br />
$NewSize.Height = 50<br />
$NewSize.Width = 175<br />
$Window.WindowSize = $NewSize<br />
}<br />
} #End Set-WindowSize<br />
<br />
Function script:Get-Traceroute {<br />
$script:TraceResults = Test-NetConnection $Target -InformationLevel Detailed -TraceRoute | Select -ExpandProperty TraceRoute<br />
} #End Get-Traceroute<br />
<br />
Function script:Resolve-ASN {<br />
$HopASN = $null #Reset to null each time<br />
$HopASNRecord = $null #Reset to null each time<br />
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<br />
$HopSplit = $Hop.Split('.')<br />
$HopRev = $HopSplit[3] + '.' + $HopSplit[2] + '.' + $HopSplit[1] + '.' + $HopSplit[0]<br />
$HopASNRecord = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopRev$WHOIS -ErrorAction SilentlyContinue | Select Strings<br />
}<br />
Else {<br />
$HopASNRecord = $null<br />
}<br />
<br />
If ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().IsArray){ #Check for array;<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "Object found $HopASN"<br />
}<br />
<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASN = "AS"+$HopASNRecord.Strings[0].Split('|').Trim()[0]<br />
Write-Verbose "String found $HopASN"<br />
}<br />
<br />
Else {<br />
$HopASN = "-"<br />
}<br />
} #End Resolve-ASN<br />
<br />
Function script:Resolve-ASNOwner {<br />
If ($HopASN -notlike "-") { <br />
$IndexNo = $ASNOwnerArr.ASN.IndexOf($HopASN)<br />
Write-Verbose "Current object: $ASNOwnerObj"<br />
<br />
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<br />
Write-Verbose "ASN $HopASN not previously resolved; performing lookup" #Check the previous lookups before running this unnecessarily<br />
$HopASNOwner = Resolve-DnsName -Server $DNSServer -Type TXT -Name $HopASN$ASNWHOIS -ErrorAction SilentlyContinue | Select Strings<br />
<br />
If ($HopASNOwner.Strings -AND $HopASNOwner.Strings.GetType().IsArray){ #Check for array;<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "Object found $HopASNOwner"<br />
}<br />
ElseIf ($HopASNRecord.Strings -AND $HopASNRecord.Strings.GetType().FullName -like "System.String"){ #Check for string; normal case.<br />
$HopASNOwner = $HopASNOwner.Strings[0].Split('|').Trim()[4].Split('-')[0]<br />
Write-Verbose "String found $HopASNOwner"<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
}<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN"($HopASN) -Force<br />
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"($HopASNOwner) -Force<br />
$ASNOwnerArr += $ASNOwnerObj #Add our new value to the cache<br />
}<br />
Else { #We get to use a cached entry and save Team Cymru some lookups<br />
Write-Verbose "ASN Owner found in cache"<br />
$HopASNOwner = $ASNOwnerArr[$IndexNo]."ASN Owner"<br />
}<br />
}<br />
Else {<br />
$HopASNOwner = "-"<br />
Write-Verbose "ASN Owner lookup not performed - RFC1918 IP found or hop TimedOut"<br />
}<br />
} #End Resolve-ASNOwner<br />
<br />
Function script:Resolve-DNS {<br />
$HopNameArr = $null<br />
$script:HopName = New-Object psobject<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") {<br />
$z++ #Increment the count for the progress bar<br />
$script:HopNameArr = Resolve-DnsName -Server $DNSServer -Type PTR $Hop -ErrorAction SilentlyContinue | Select NameHost<br />
Write-Verbose "Hop = $Hop"<br />
<br />
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.<br />
$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<br />
Write-Verbose "Object found $HopName"<br />
}<br />
<br />
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.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $HopNameArr.NameHost.Split(',')[0].Trim() #In the case of multiple PTRs select the first one<br />
Write-Verbose "String found $HopName"<br />
}<br />
<br />
ElseIf ($HopNameArr.NameHost -like $null) { #Check for null last because when an array is returned with PTR and NS records, it contains null values.<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If there's no PTR record, set name equal to IP<br />
Write-Verbose "HopNameArr apparently empty for $HopName"<br />
}<br />
Write-Progress -Activity "Resolving PTR Record" -Status "Looking up $Hop, Hop #$z of $($TraceResults.length)" -PercentComplete ($z / $($TraceResults.length)*100)<br />
}<br />
Else {<br />
$z++<br />
$script:HopName | Add-Member -MemberType NoteProperty -Name NameHost -Value $Hop #If the hop times out, set name equal to TimedOut<br />
Write-Verbose "Hop = $Hop"<br />
}<br />
} #End Resolve-DNS<br />
<br />
Function script:Get-PerHopRTT {<br />
$PerHopRTTArr = @() #Store all RTT values per hop<br />
$SAPSObj = $null #Clear the array each cycle<br />
$SendICMP = New-Object System.Net.NetworkInformation.Ping<br />
$i++ #Advance the count<br />
$x = 0 #Reset x for the next hop count. X tracks packet loss percentage.<br />
$BufferData = "a" * $BufLen #Send the UTF-8 letter "a"<br />
$ByteArr = [Text.Encoding]::UTF8.GetBytes($BufferData)<br />
If ($Hop -notlike "TimedOut" -and $Hop -notlike "0.0.0.0") { #Normal case, attempt to ping hop<br />
For ($y = 1; $y -le $PingCycles; $y++){<br />
$HopResults = $SendICMP.Send($Hop,1000,$ByteArr) #Send the packet with a 1 second timeout<br />
$HopRTT = $HopResults.RoundtripTime<br />
$PerHopRTTArr += $HopRTT #Add RTT to HopRTT array<br />
If ($HopRTT -eq 0) {<br />
$x = $x + 1<br />
}<br />
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)<br />
} #End for loop<br />
$PerHopRTTArr = $PerHopRTTArr | Where-Object {$_ -gt 0} #Remove zeros from the array<br />
$HopRTTMin = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Minimum).Minimum<br />
$HopRTTMax = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Maximum).Maximum<br />
$HopRTTAvg = "{0:N0}" -f ($PerHopRTTArr | Measure-Object -Average).Average<br />
$HopLoss = "{0:N1}" -f (($x / $PingCycles) * 100) + "`%"<br />
$HopText = [string]$HopRTT + "ms"<br />
If ($HopLoss -like "*100*") { #100% loss, but name resolves<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
}<br />
} #End main ping loop<br />
Else { #Hop TimedOut - no ping attempted<br />
$HopResults = $null<br />
$HopRTT = $null<br />
$HopText = $null<br />
$HopLoss = "100.0%"<br />
$HopRTTAvg = "-"<br />
$HopRTTMin = "-"<br />
$HopRTTMax = "-"<br />
} #End TimedOut condition<br />
$script:SAPSObj = [PSCustomObject]@{<br />
"Hop" = $i<br />
"Hop Name" = $HopName.NameHost<br />
"ASN" = $HopASN<br />
"ASN Owner" = $HopASNOwner<br />
"`% Loss" = $HopLoss<br />
"Hop IP" = $Hop<br />
"Avg RTT" = $HopRTTAvg<br />
"Min RTT" = $HopRTTMin<br />
"Max RTT" = $HopRTTMax<br />
}<br />
$PerTraceArr += $SAPSObj #Add the object to the array<br />
} #End Get-PerHopRTT<br />
<br />
. Set-Variables<br />
. Set-WindowSize<br />
. Get-Traceroute<br />
ForEach ($Hop in $TraceResults) {<br />
. Resolve-ASN<br />
. Resolve-ASNOwner<br />
. Resolve-DNS<br />
. Get-PerHopRTT<br />
}<br />
<br />
$PerTraceArr | Format-Table -Autosize<br />
$PerTraceArr | Format-Table -Autosize | Out-File -Append $env:UserProfile\Desktop\$Filename.txt -encoding UTF8<br />
</pre><br />
<br />
== top like output ==<br />
<br />
=== in processor time ===<br />
<br />
<pre><br />
While(1) { <br />
$p = get-counter '\Process(*)\% Processor Time'; <br />
cls; <br />
$p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a<br />
}<br />
</pre><br />
<br />
<br />
=== in percent ===<br />
<br />
<pre><br />
while(1) {<br />
cls; <br />
Get-Counter '\Process(*)\% Processor Time' `<br />
| Select-Object -ExpandProperty countersamples `<br />
| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} `<br />
| Sort-Object -Property cookedvalue -Descending `<br />
| Select-Object -First 25 `<br />
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize; <br />
sleep 2<br />
}<br />
</pre><br />
<br />
<br />
Delete SPN from host:<br />
<br />
setspn -D host/<serveralias> <server><br />
<br />
== SCCM Related ==<br />
<br />
=== Pull pending updates and install ===<br />
<br />
<pre><br />
function Get-CMMissingUpdate {<br />
<br />
param (<br />
$computer = "localhost"<br />
)<br />
<br />
Get-WmiObject -Query "SELECT * FROM CCM_SoftwareUpdate" -Namespace "ROOT\ccm\ClientSDK" -ComputerName $computer<br />
<br />
}<br />
<br />
<br />
function Install-CMMissingUpdate {<br />
<br />
param (<br />
$computer = "localhost"<br />
)<br />
<br />
([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (<br />
Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK'))<br />
<br />
}<br />
</pre><br />
<br />
<br />
<br />
== SSL/TLS ==<br />
<br />
yadda<br />
<br />
<br />
=== Disable SSL 2.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Disable SSL 3.0 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' -name Enabled -value 0 –PropertyType DWORD<br />
</pre><br />
<br />
<br />
=== Enable TLS 1.1 & TLS 1.2 ===<br />
<br />
<pre><br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force<br />
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '0xffffffff' –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value 1 –PropertyType DWORD<br />
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 –PropertyType DWORD<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Windows/exchange&diff=1720
Windows/exchange
2021-02-16T11:26:54Z
<p>Cbs: </p>
<hr />
<div><br />
== PowerShell ==<br />
<br />
powershell commands<br />
<br />
<br />
=== possible access rights ===<br />
<br />
<pre><br />
The Access Rights parameters are as below:<br />
<br />
ReadItems: The user has the right to read items within the specified folder.<br />
CreateItems The user has the right to create items within the specified folder.<br />
EditOwnedItems The user has the right to edit the items that the user owns in the specified folder.<br />
DeleteOwnedItems The user has the right to delete items that the user owns in the specified folder.<br />
EditAllItems The user has the right to edit all items in the specified folder.<br />
DeleteAllItems The user has the right to delete all items in the specified folder.<br />
CreateSubfolders The user has the right to create subfolders in the specified folder.<br />
FolderOwner The user is the owner of the specified folder. The user has the right to view and move the folder and create subfolders. The user can’t read items, edit items, delete items, or create items.<br />
FolderContact The user is the contact for the specified public folder.<br />
FolderVisible The user can view the specified folder, but can’t read or edit items within the specified public folder.<br />
<br />
The Roles with which we can provide the access rights are as below:<br />
<br />
None FolderVisible<br />
Owner CreateItems, ReadItems, CreateSubfolders, FolderOwner, FolderContact, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingEditor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
Editor CreateItems, ReadItems, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems<br />
PublishingAuthor CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
Author CreateItems, ReadItems, FolderVisible, EditOwnedItems, DeleteOwnedItems<br />
NonEditingAuthor CreateItems, ReadItems, FolderVisible<br />
Reviewer ReadItems, FolderVisible<br />
Contributor CreateItems, FolderVisible<br />
<br />
Ref: http://technet.microsoft.com/en-us/library/dd298062(v=exchg.150).aspx<br />
<br />
The following roles apply specifically to calendar folders:<br />
<br />
AvailabilityOnly View only availability data<br />
LimitedDetails View availability data with subject and location<br />
</pre><br />
<br />
<br />
=== create mailbox ===<br />
<br />
Create a new mailbox<br />
<br />
New-Mailbox -Name 'prospect NL' -Alias 'prospect.nl' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Rooms and Equipment' \<br />
-UserPrincipalName 'prospect.nl@arifleet.com' -SamAccountName 'prospect.nl' -FirstName 'prospect' -Initials '' -LastName 'NL' \<br />
-Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Stuttgart Mailbox DB One'<br />
<br />
<br />
=== create linked mailbox ===<br />
<br />
New-Mailbox -Name 'Koroch, Ernst' -Alias 'ekoroch' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Users' -UserPrincipalName \<br />
'ekoroch@arifleet.com' -SamAccountName 'ekoroch' -FirstName 'Ernst' -Initials '' -LastName 'Koroch' -Database 'Stuttgart Mailbox DB One' \<br />
-LinkedMasterAccount 'fleetservices\ekoroch' -LinkedDomainController 'dc03.fleetservices.intra' -LinkedCredential \<br />
'System.Management.Automation.PSCredential'<br />
<br />
<br />
=== Repair Mailbox ===<br />
<br />
see: [https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx]<br />
<br />
New-MailboxRepairRequest -Mailbox <Emailaddress> -CorruptionType SearchFolder,AggregateCounts,ProvisionedFolder,FolderView [-DetectOnly]<br />
<br />
<br />
=== Email-Enable AD Group ===<br />
<br />
Enable-DistributionGroup <ADGroupID> -PrimarySmtpAddress yadda@domain.tld<br />
<br />
<br />
=== add mailbox permissions ===<br />
<br />
Add full access to mailbox 'mailbox@arifleet.de' for user 'DOMAIN\user': <br />
<br />
Add-MailboxPermission -Identity mailbox@arifleet.de -User DOMAIN\user -AccessRights Fullaccess -InheritanceType All<br />
<br />
-AccessRights <right> <br/><br />
where <right> may be<br />
<br />
FullAccess<br />
ExternalAccount<br />
DeleteItem<br />
ReadPermission<br />
ChangePermission<br />
ChangeOwner<br />
<br />
disable auto-mapping of <br />
<br />
-Automapping $false<br />
<br />
<br />
=== remove mailbox permissions ===<br />
<br />
remove-MailboxPermission -Identity mailbox@arifleet.de -user domari\user -AccessRights Fullaccess -inheritance all<br />
<br />
<br />
=== add/remove 'Send as' permissions ===<br />
<br />
Add-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
You can grant the permissions by using Active Directory Users & Computers. Simply open the properties of the group, switch to the Security tab, add the mailbox user or group, and then tick the Send As box and apply the change. After making this change you may notice that it does not take effect for up to 2 hours. This is due to caching on the Exchange servers. Though you can speed up the change by restarting the Information Store that is obviously not going to be practical in most production environments, so you’ll often find that you just need to wait.<br />
<br />
Remove-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'<br />
<br />
<br />
==== 'Send as'/'SendOnBehalf' Distributiongroups ====<br />
<br />
Set-DistributionGroup <DistributionGroupName> -GrantSendOnBehalfTo USER@arifleet.com<br />
<br />
and sendOnBehalf for Distributiongroups<br />
<br />
<br />
<br />
==== SentItem Configuration ====<br />
<br />
Until Exchange 2010:<br />
<br />
Set-MailboxSentItemsConfiguration <ALIAS> -SendAsItemsCopiedTo SenderAndFrom<br />
<br />
Exchange 2016:<br />
<br />
Set-Mailbox -identity <UPN> [-DomainController <HOSTNAME>] -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true<br />
<br />
<br />
=== add mailbox folder permissions ===<br />
<br />
Add-MailboxFolderPermission -Identity poolcar@netcar24.com:\Calendar -user csteidl@arifleet.com -AccessRights [[Windows/exchange#possible_access_rights|<see RIGHTS>]]<br />
<br />
Set default-rights for ressource mailboxes (to show up subjects a.s.o.):<br />
<br />
Set-MailboxFolderPermission meetingroom:\Calendar -User Default -AccessRights Reviewer<br />
<br />
=== get mailbox permissions ===<br />
<br />
get permissions of fhess on mailbox prospect.be<br />
<br />
Get-MailboxPermission -Identity prospect.be@arifleet.com -User "fhess"<br />
<br />
<br />
get folder permissions<br />
<br />
get-mailboxfolderpermission -identity fhess<br />
<br />
<br />
get UPN of users<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.User.ADRecipient.UserPrincipalName }<br />
<br />
<br />
get full user details<br />
<br />
Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.identity.adrecipient.identity }<br />
<br />
<br />
<br />
=== Find permissions granted to spec. users ===<br />
<br />
Get-Mailbox -RecipientType 'UserMailbox' -ResultSize Unlimited | Get-MailboxPermission | where { $_.user.tostring() -eq "DOMAIN\username" -and $_.IsInherited -eq $false }<br />
<br />
<br />
<br />
=== enable autoreply / vacation message ===<br />
<br />
set the message (optionally) and enable auto reply<br />
<br />
$message = get-content message.txt<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState enabled \<br />
-ExternalAudience <none/all/known> \<br />
-InternalMessage "$message" \<br />
-ExternalMessage "$message"<br />
<br />
<br />
=== disable auto-reply / vacation message ===<br />
<br />
disable auto reply<br />
<br />
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState disabled<br />
<br />
<br />
=== Retention policies ===<br />
<br />
create server side retention policies<br />
<br />
<br />
==== Create Retention Policy Tag ====<br />
<br />
New-RetentionPolicyTag "ARI STG - Delete all 180 days" -Type All -Comment "Deletes all items older 180 days" -RetentionEnabled $true \<br />
-AgeLimitForRetention 180 -RetentionAction DeleteAndAllowRecovery<br />
<br />
RetentionAction: MoveToFolder, MoveToDeletedItems, DeleteAndAllowRecovery, PermanentlyDelete, MoveToArchive<br />
<br />
<br />
==== Create Retention Policy ====<br />
<br />
New-RetentionPolicy "ARI STG - Delete ALL items older 180 days" -RetentionPolicyTagLinks "ARI STG - Delete all 180 days"<br />
<br />
Activate policy by: Open Mailbox Properties --> Mailbox Settings --> Messaging Records Mgmt --> Apply Retention policy<br />
<br />
<br />
=== get distribution group members ===<br />
<br />
get-distributiongroupmember <group><br />
<br />
get-distributiongroupmember mailaddress@arifleet.de<br />
<br />
<br />
=== get users by filter and add to distributiongroup ===<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -ne 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \<br />
{ (mail -like '*<PATTERN>*' -and (employeeType -eq 'MGR') -and enabled -eq 'true') } | \<br />
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }<br />
<br />
<br />
<br />
=== Get Mailbox by ExchangeGuid/Mapi-session ===<br />
<br />
get-mailbox -ResultSize unlimited | where {$_.ExchangeGuid -eq "265182e3-a31c-4a9f-e38e-687f5a7c2d6b"}<br />
<br />
<br />
=== Get Mailbox by Ressource type ===<br />
<br />
<br />
Get-Mailbox -RecipientTypeDetails RoomMailbox<br />
<br />
Get-Mailbox -RecipientTypeDetails EquipmentMailbox<br />
<br />
<br />
=== Get Mail Public folder ===<br />
<br />
Get-MailPublicFolder helpdesk@sub.domain.com | Get-PublicFolder [| Select *]<br />
<br />
<br />
=== Logging ===<br />
<br />
further logfiles can be found here:<br />
<br />
C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\ProtocolLog<br />
<br />
<br />
==== Track accross multiple servers ====<br />
<br />
get-transportserver<br />
<br />
<br />
e.g. that to "get-messagetrackinglog":<br />
<br />
get-transportserver | get-messagetrackinglog<br />
<br />
<br />
==== message tracking ====<br />
<br />
get-messagetrackinglog -Sender 'user@arifleet.de' -Start "5/04/2015 5:00:00 AM" -End "5/15/2015 8:30:00 AM"<br />
<br />
get-transportserver | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
get-transportservice | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \<br />
-Start "6/01/2015 5:00:00 AM" \<br />
-End "6/01/2015 10:30:00 AM" \<br />
-resultsize unlimited | ft -Wrap<br />
<br />
<pre><br />
-MessageSubject <String><br />
-Recipients <String[]><br />
-Start/-End (get-date).AddHours(-1).toString()<br />
-ResultSize Unlimited<br />
</pre><br />
<br />
some more examples:<br />
<br />
get-messagetrackinglog -Recipients:recipient@email.be -Start "6/8/2015 4:42:00 AM" -End "6/9/2015 9:52:00 PM" | Select *,{$_.Recipients} | export-csv .\maillog.csv<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | \<br />
where-object {$_.Recipients -like “*@gmail.com, *@yahoo.com” -AND $_.EventId -eq “Send”} |ft -auto >>C:\External mails.txt<br />
<br />
Get-MessageTrackingLog -resultsize unlimited | sort -property Timestamp<br />
<br />
=== repair mailbox ===<br />
<br />
New-MailboxRepairRequest -Mailbox schaden@arifleet.de -CorruptionType SearchFolder<br />
<br />
<br />
-CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview<br />
-Archive Prueft Mailbox _und_ Archive<br />
-DetectOnly Prueft nur, keine Reparatur!<br />
<br />
Ergebnisse der Prüfung werden im Anwendungs Event-Log des Servers protokolliert. Die Events tragen die folgenden Ereignis-IDs:<br />
<br />
10044,10045,10046,10047,10048,10049,10050,10051,10059,10062<br />
<br />
mit einem rechtsklick auf 'Application' laesst dich das eventlog nach diesen ID's filtern.<br />
<br />
<br />
=== move mailbox between exchange-databases ===<br />
<br />
Move Mailboxes between exchange >= 2010 servers <br/><br />
the output is piped into 'ft' (format table) to get complete output and not stripped it...<br />
<br />
New-MoveRequest -Identity mailbox@arifleet.de -TargetDatabase ‘Whatever Database-Name 001’ | ft -AutoSize -Wrap<br />
<br />
create a batch<br />
<br />
Get-Mailbox -Database "Stuttgart Mailbox DB One" | Where-Object { $_.alias -like "jira*" } | New-MoveRequest -TargetDatabase [...]<br />
<br />
Options:<br />
<br />
-BadItemLimit 0<br />
-Suspend <br />
-SuspendComment "Resume after 11:00 p.m. PST"<br />
-SuspendWhenReadyToComplete<br />
-BatchName "Some Name to identify the Batch-Moves"<br />
<br />
get moverequest status:<br />
<br />
Get-MoveRequestStatistics "sadg"<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics<br />
<br />
Get-MoveRequest | Get-MoveRequestStatistics | select DisplayName,alias,Status,TotalMailboxSize,PercentComplete| ft<br />
<br />
<br />
=== get Mailbox sizes ===<br />
<br />
Get-MailboxDatabase | Where-Object { $_.Name -like "STG*" } | Get-MailboxStatistics | sort -property TotalItemSize -desc \<br />
| select DisplayName,ItemCount,TotalItemSize,TotalDeletedItemSize |ft<br />
<br />
<br />
=== get database size ===<br />
<br />
Get-MailboxDatabase -status | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Sort-Object DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
Get-MailboxDatabase -status | Where-Object { $_.name -like "STG*" } | Sort -property DatabaseSize -Desc | select ServerName,Name,DatabaseSize<br />
<br />
=== Export Mailbox (Folder) ===<br />
<br />
New-MailboxExportRequest -mailbox schaden \<br />
-includefolders "******@arifleet.de/00 UNFALLORDNER ab 1.3.2011/Storopack R+V (*.***@*******.com) TK 150 \/ keine VK RA Schmid" \<br />
-filepath "\\stgwpvinfEXC01\g$\Storopack R+V (*.***@*******.com) TK 150_keine VK RA Schmid.pst"<br />
<br />
# be sure to mask e.g. '/' characters in foldernames with '\'<br />
# leave out '''-includefolders''' to export the entire mailbox<br/><br />
## add a '.../*' to -includefolders to include subfolders<br />
<br />
=== Search Mailbox content ===<br />
<br />
This one searches for all messages between 1/1/2017 and 12/31/2018 and creates copies of it within the Mailbox of targetmailbox into targetfolder:<br />
<br />
Search-Mailbox -Identity <USER-ID> -SearchQuery "received>=01/01/2017 AND received<=12/31/2018" -targetmailbox "<TARGET-USER-ID>" -targetfolder "SearchResults"<br />
<br />
<br />
=== set thumbnail-image ===<br />
<br />
from an exchange server<br />
<br />
Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \<br />
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg" -Encoding Byte -ReadCount 0))<br />
<br />
<br />
from an AD<br />
<br />
$photo = [byte[]](Get-Content path of pic -Encoding byte)<br />
Set-ADUser username -Replace @{thumbnailPhoto=$photo}<br />
<br />
<br />
=== Import/Acivate new Certificate ===<br />
<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path c:\certificates\YOUR_CERTIFICATE.cer -Encoding byte -ReadCount 0))<br />
<br />
In case of encrypted .pfx or something like that:<br />
<br />
$pass = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force<br />
Import-ExchangeCertificate -FriendlyName "webmail10102019" -Password $pass -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path Webmail.pfx -Encoding byte -ReadCount 0))<br />
<br />
activate:<br />
<br />
Enable-ExchangeCertificate -Thumbprint 1234ae0567a72fccb75b1d0198628675333d010e -Services POP,IMAP,SMTP,IIS<br />
<br />
=== DAG/Cluster stuff ===<br />
<br />
Check who's master:<br />
<br />
Get-ClusterGroup EU-DAG<br />
<br />
<br />
Get detailed DAG info:<br />
<br />
Get-DatabaseAvailabilityGroup STG-DAG -status | fl<br />
<br />
<br />
Test replication health (do so on all cluster members):<br />
<br />
Test-ReplicationHealth -server EXC02<br />
<br />
<br />
Get mount status, copy/reply queue, Index state<br />
<br />
Get-MailboxDatabaseCopyStatus -server exc01<br />
<br />
<br />
Check Queues:<br />
<br />
get-queue -server stgwpvinfexc02<br />
<br />
<br />
Check service health (do so on all cluster members):<br/><br />
(test whether all the Microsoft Windows services that Exchange requires on a server have started)<br />
<br />
Test-servicehealth –server EXC02<br />
<br />
<br />
Test MapiConnectivity (Note: this will only test if the DB’s are mounted/active copy on the specific server):<br />
<br />
Test-MapiConnectivity -server EXC02<br />
<br />
<br />
Test/view replication:<br />
<br />
Get-MailboxdatabaseCopystatus -server EXC02<br />
<br />
<br />
Failover Cluster:<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup <br />
<br />
This will failover the 2 node cluster to the other node<br />
<br />
Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup -node EXC01<br />
<br />
This will failover the cluster to the node EXC01<br />
<br />
<br />
Move Databases:<br />
<br />
Move-ActiveMailboxDatabase DB3 -ActivateOnServer MBX4<br />
<br />
This example performs a switchover of the database DB3 to the Mailbox server MBX4. When the command completes, MBX4 hosts the active copy of DB3. Because the MountDialOverride parameter isn't specified, MBX4 mounts the database using a database auto mount dial setting of Lossless.<br />
<br />
<br />
Get-MailboxDatabase stg-* | Move-ActiveMailboxDatabase -ActivateOnServer MBX4<br />
<br />
Same as above, but moves all databases starting with 'STG-*' to MBX04<br />
<br />
<br />
Move-ActiveMailboxDatabase DB1 -ActivateOnServer MBX3 -MountDialOverride:GoodAvailability<br />
<br />
This example performs a switchover of the database DB1 to the Mailbox server MBX3. When the command completes, MBX3 hosts the active copy of DB1. Because the MountDialOverride parameter is specified with a value of Good Availability, MBX3 mounts the database using a database auto mount dial setting of GoodAvailability.<br />
<br />
<br />
== Outlook stuff ==<br />
<br />
=== get all add-ins ===<br />
<br />
Be aware that HKCU can only be grabbed if running in the user context!<br />
<br />
$searchScopes = "HKCU:\SOFTWARE\Microsoft\Office\Outlook\Addins","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins"<br />
$searchScopes | % {Get-ChildItem -Path $_ | % {Get-ItemProperty -Path $_.PSPath} | Select-Object @{n="Name";e={Split-Path $_.PSPath -leaf}},FriendlyName,Description} | Sort-Object -Unique -Property name<br />
<br />
<br />
== Transport stuff ==<br />
<br />
some stuff i used the GUI for<br />
<br />
<br />
=== Relay Configuration (GUI) ===<br />
<br />
Go:<br />
Server-Configuration --> Hub Transport --> Receive Connectors (Tab)<br />
<br />
- Select a valuable connector which matches you needs or create a new.<br />
- for me there was 'Relay internal' which was to allow anonymous connects from spec. hosts/nets --> Double-Click<br />
- Switch to 'Network'-Tab --> Add IP or rage to lower box.<br />
<br />
<br />
<br />
=== Max connection from single IP ===<br />
<br />
set-ReceiveConnector -Identity "exc03\Application_Relay" -MaxInboundConnectionPerSource 50<br />
<br />
sets the max inbound connections per source IP to 50 (default 20)<br />
<br />
<br />
<br />
=== Create an anonymous Receive Connector ===<br />
<br />
after you created an receive connector by GUI you will have to run:<br />
<br />
Get-ReceiveConnector "STGWPVINFEXC02\Application_Relay_Intern" | \<br />
Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"</div>
Cbs
https://schnallich.net/index.php?title=Hp/3PAR&diff=1719
Hp/3PAR
2021-02-11T13:09:00Z
<p>Cbs: </p>
<hr />
<div><br />
== Diag ==<br />
<br />
=== Infos for HP (creating Case) ===<br />
<br />
> showsys <br />
> showsys -d<br />
<br />
(System Information inclusing serial)<br />
<br />
<br />
> servicemag status <br />
<br />
(shows if any drive was already evacuated)<br />
<br />
<br />
> checkhealth pd<br />
<br />
(do healthcheck of physical disks)<br />
<br />
<br />
> showpd -s <br />
> showpd -state<br />
> showpd -s -failed<br />
> showpd -failed -degraded<br />
<br />
(show the state of all drives)<br />
<br />
<br />
> showpd -i <br />
<br />
(show the drive inventory including type and serial)<br />
<br />
<br />
> showport -sfp [-d]<br />
<br />
(show the SFP ports and their status [detailed list])<br />
<br />
=== showsys (System info) ===<br />
<br />
Help page<br />
<br />
<pre><br />
showsys - Show system information.<br />
<br />
SYNTAX<br />
showsys [options]<br />
<br />
DESCRIPTION<br />
The showsys command displays the HP 3PAR Storage system properties such as<br />
a system name, serial number, and system capacity information.<br />
<br />
AUTHORITY<br />
Any role in the system<br />
<br />
OPTIONS<br />
-d<br />
Specifies that more detailed information about the system is displayed.<br />
<br />
-param<br />
Specifies that the system parameters are displayed.<br />
<br />
-fan<br />
Displays the system fan information.<br />
<br />
-space<br />
Displays the system capacity information in MB (1024^2 bytes).<br />
<br />
-domainspace<br />
Displays the system capacity information broken down by domain in MB<br />
(1024^2 bytes).<br />
<br />
-desc<br />
Displays the system descriptor properties.<br />
<br />
-devtype FC|NL|SSD<br />
Displays the system capacity information where the disks must have a<br />
device type string matching the specified device type; either Fast<br />
Class (FC), Nearline (NL), Solid State Drive (SSD). This option can<br />
only be issued with the -space option.<br />
<br />
SPECIFIERS<br />
None.<br />
<br />
NOTES<br />
See setsys command for information on setting the threshold parameters<br />
indicated by the Value column in the output for showsys -param.<br />
<br />
In the output for showsys -param, (from configured settings) indicates that<br />
the system parameters displayed have been successfully read from the<br />
Persistent Repository (PR). If the PR is not available (most likely because<br />
of problems with the admin volume), the output reads (from default settings)<br />
and the values displayed would indicate the system defaults. When (from<br />
default settings) is displayed, system parameters cannot be updated.<br />
<br />
If the VVRetentionTimeMax is 0, then the volume retention time in the system<br />
is disabled.<br />
<br />
For the system capacity information, there might be some overlaps among<br />
Volumes, System, and Failed Capacities.<br />
<br />
EXAMPLES<br />
The following example displays the system descriptor properties of a HP 3PAR<br />
storage system:<br />
<br />
cli% showsys -desc<br />
------------System s36------------<br />
System Name : s36<br />
Location : Your Facility Address<br />
Owner : Your Company Name<br />
Contact : Joe Admin<br />
Comment : Your Notes<br />
<br />
The following example displays more detailed (-d option) information about<br />
the same storage server:<br />
<br />
cli% showsys -d<br />
------------General-------------<br />
System Name : S424<br />
System Model : HP_3PAR 7200<br />
Serial Number : 1600424<br />
System ID : 424<br />
Number of Nodes : 2<br />
Master Node : 0<br />
Nodes Online : 0,1<br />
Nodes in Cluster : 0,1<br />
<br />
-----System Capacity (MB)-----<br />
Total Capacity : 6277120<br />
Allocated Capacity : 687872<br />
Free Capacity : 5589248<br />
Failed Capacity : 0<br />
<br />
---------System Fan---------<br />
Primary Node ID : 0<br />
Secondary Node ID : 1<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
Primary Node ID : 1<br />
Secondary Node ID : 0<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
<br />
--------System Descriptors--------<br />
Location :<br />
Owner :<br />
Contact :<br />
Comment :<br />
</pre><br />
<br />
<br />
==== Space details ====<br />
<br />
> showsys -space<br />
<br />
<br />
=== Chech Hardware ===<br />
<br />
> admithw<br />
<br />
Check Hardware and try to fix issues. Initialize new disks<br />
<br />
<br />
=== IOPS Stats ===<br />
<br />
statvlun -ni -iter 1 -hostsum<br />
<br />
Output:<br />
<pre><br />
14:09:22 10/13/2018 r/w I/O per second KBytes per sec Svt ms IOSz KB <br />
Hostname Cur Avg Max Cur Avg Max Cur Avg Cur Avg Qlen<br />
FF1EPPINFVMH02 t 105 105 105 2278 2278 2278 0.42 0.42 21.7 21.7 0<br />
...<br />
</pre><br />
<br />
<br />
== Tuning ==<br />
<br />
=== Move VVs between CPGs ===<br />
<br />
[[Hp/3PAR#Move volume to another CPG using tunevv|Move volume to another CPG using tunevv]]<br />
<br />
<br />
=== Balance PDs ===<br />
<br />
If allocation of physical diskspace is not in balance through disks available.<br/><br />
Dry-Run:<br />
<br />
tunenodech -dr -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
NO Dry-Run:<br />
<br />
tunenodech -waittask -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
{{Achtung|Do this for all Nodes in your 3PAR environment after each other!! Just replace '-node 0' by '-node N'}}<br />
<br />
<br />
<br />
== CPGs ==<br />
<br />
=== Show CPGs ===<br />
<br />
<pre><br />
% showcpg<br />
----Volumes---- -Usage- -------------(MiB)-------------<br />
Id Name Warn% VVs TPVVs TDVVs Usr Snp Base Snp Free Total<br />
0 FC_r1 - 0 0 0 0 0 0 0 0 0<br />
1 FC_r5 - 35 35 0 35 34 3774976 14848 193536 3983360<br />
2 FC_r6 - 19 19 0 19 0 27048320 0 478208 27526528<br />
3 FC_Snap - 20 20 0 0 20 0 138752 51712 190464<br />
5 SSD_AO_R6 - 0 0 0 0 0 4998656 0 2560 5001216<br />
4 SSD_r5 - 0 0 0 0 0 2070144 0 37248 2107392<br />
--------------------------------------------------------------------------<br />
6 total 54 54 37892096 153600 763264 38808960<br />
</pre><br />
<br />
<br />
Show the Data Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sdg<br />
-----(MiB)------ <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 32768 -ssz 2 -ha cage -t r1 -p -devtype FC <br />
1 FC_r5 - - 32768 -ssz 6 -ha mag -t r5 -p -devtype FC <br />
2 FC_r6 - - 32768 -t r6 -ha mag -ssz 6 -ss 128 -p -devtype FC <br />
3 FC_Snap - - 32768 -t r6 -ha mag -ssz 8 -ss 64 -ch first -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -t r5 -ha mag -ssz 4 -ss 64 -ch first -p -devtype SSD<br />
4 SSD_r5 - - 8192 -t r5 -ha mag -ss 64 -p -devtype SSD<br />
</pre><br />
<br />
<br />
Show the Admin Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sag<br />
-----(MiB)----- <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 8192 -p -devtype FC -ha cage -p -devtype FC<br />
1 FC_r5 - - 8192 -p -devtype FC -p -devtype FC <br />
2 FC_r6 - - 8192 -ha mag -p -devtype FC <br />
3 FC_Snap - - 8192 -ha mag -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -ha mag -p -devtype SSD <br />
4 SSD_r5 - - 8192 -ha mag -p -devtype SSD<br />
</pre><br />
<br />
<br />
=== Create CPG ===<br />
<br />
% createcpg -t r6 -ha mag -sdgs 32G -ssz 8 -ss 128 -p -devtype FC <CPG_Name><br />
<br />
-t RAID Level<br/><br />
-ha HA Settings (port|cage|mag)<br/><br />
-sdgs Data-Growth Size<br/><br />
-ssz size_number_chunklets: 2 for RAID-1, 4 for RAID-5, and 8 for RAID-6<br/><br />
-p define a pattern / -devtype define a pattern for DevTypes to match<br/><br />
<br />
== Virtual Volumes ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Virtual Volumes ===<br />
<br />
showvv -listcols<br />
<br />
showvv -showcols Name,VV_WWN,SnpCPG<br />
<br />
<br />
=== Create Virtual Volume ===<br />
<br />
createvv -tpvv -pol zero_detect -snp_cpg FC_Snap FC_r6 FF3_VMW_AO_03 4194304<br />
<br />
<pre><br />
-Tpvv Thin provisions Virtual Volume<br />
-pol zero_detect I believe it is needed to thin luns<br />
-snp_cfg FC_Snap Where the writes will go for snapshots. HP refers to this as snap or copy space<br />
FF3_VMW_AO_03 Name: this is the lun name<br />
4194304 Size: This is the number to 4tb<br />
8388608 Size: 8tb<br />
</pre><br />
<br />
=== Move volume to another CPG using tunevv ===<br />
<br />
Assuming I want to move a virtual volume ('''VV12_AO''') to another new CPG ('''FC_r6'''):<br />
<br />
tunevv usr_cpg FC_r6 VV12_AO<br />
<br />
The logical disks used for user space are moved to CPG FC_r6 for virtual volume VV12_AO<br />
If you want to move the VV regions only use:<br />
<br />
tunevv usr_cpg FC_r6 -src_cpg FC_r5 VV12_AO<br />
<br />
<br />
Assuming I want to move a snapshot volume ('''VV12_AO''') to another new SnapCPG ('''FC_Snap'''):<br />
<br />
tunevv snp_cpg FC_Snap VV12_AO<br />
<br />
Unfortunatly you will have to run both commands seperatly. As of the documentation they can't be combined.<br />
<br />
<br />
== Auth LDAP ==<br />
<br />
yadda<br />
<br />
<br />
=== Set LDAP auth ===<br />
<br />
<pre><br />
setauthparam -f -clearall<br />
setauthparam -f ldap-server 10.30.111.112<br />
setauthparam -f ldap-server-hn STGWPVEURDC02.<DOMAIN>.<DOMAIN>.com<br />
setauthparam -f kerberos-realm <DOMAIN>.<DOMAIN>.com<br />
setauthparam -f binding sasl<br />
setauthparam -f sasl-mechanism GSSAPI<br />
setauthparam -f accounts-dn "OU=PrivilegedAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=com" <br />
setauthparam -f account-obj user<br />
setauthparam -f account-name-attr sAMAccountName <br />
setauthparam -f memberof-attr memberOf<br />
setauthparam -f super-map "CN=SAN_Admins,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
setauthparam -f browse-map "CN=SAN_ReadOnly,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
</pre><br />
<br />
Check that it works for you:<br />
<br />
checkpassword <LDAP-Username><br />
...<br />
...<br />
user <LDAP-Username> is authenticated and authorized<br />
<br />
=== Get LDAP auth config ===<br />
<br />
<pre><br />
% showauthparam<br />
Param --------------------------------------Value---------------------------------------<br />
ldap-server 10.30.111.106 <br />
ldap-server-hn DC05.<DOMAIN>.<TLD> <br />
kerberos-realm <DOMAIN>.<TLD> <br />
binding sasl <br />
sasl-mechanism GSSAPI<br />
[...]<br />
</pre><br />
<br />
<br />
== Network ==<br />
<br />
yadda<br />
<br />
<br />
=== get network settings ===<br />
<br />
<pre><br />
% shownet<br />
IP Address Netmask/PrefixLen Nodes Active Speed Duplex AutoNeg Status<br />
10.11.12.100 255.255.255.0 01 0 1000 Full Yes Active<br />
<br />
Default route : 10.11.12.1<br />
NTP server : 10.30.111.111<br />
DNS server : 10.11.12.42<br />
</pre><br />
<br />
<br />
=== set DNS server ===<br />
<br />
Add:<br />
<br />
setnet dns -add 10.30.111.111<br />
<br />
Remove:<br />
<br />
setnet dns -remove 10.30.111.111<br />
<br />
<br />
=== re-new expired certificates ===<br />
<br />
Show the actual cert:<br />
<br />
% showcert<br />
Service Commonname Type Enddate Fingerprint <br />
unified-server* HP_3PAR 8200-CZ3740W5MD cert Oct 16 15:36:12 2020 GMT bdae8ff911a32e50a65a81dbae656b46112fa992<br />
<br />
<br />
Renew the cert:<br />
<br />
<pre><br />
createcert unified-server -selfsigned -CN 3par.yadda.com -SAN DNS:3par-alias.yadda.com,DNS:10.12.13.14<br />
The following services will be restarted if currently running:<br />
cim: manages communications with SMI-S clients<br />
<br />
wsapi: Web Services API server<br />
<br />
Continue creating self-signed certificate (yes/no)? yes<br />
Self-signed certificate created.<br />
cimserver restarted<br />
The Web Services API server stopped successfully.<br />
<br />
The Web Services API Server will start shortly.<br />
</pre><br />
<br />
Done!<br />
<br />
<br />
== Full Command List ==<br />
<br />
<pre><br />
HP 3PAR CLI command list<br />
<br />
showalert - show status of system alerts<br />
showauthparam - show authentication parameters<br />
showbattery - show battery status information<br />
showblock - show block mapping info for vvs, lds, pds<br />
showcage - show disk cage information<br />
showcim - show the CIM server information<br />
showclienv - show CLI environment parameters<br />
showcpg - show Common Provisioning Groups (CPGs)<br />
showdate - show date and time on all system nodes<br />
showdomain - show domains in the system<br />
showdomainset - show sets of domains in the system<br />
showeeprom - show node eeprom information<br />
showeventlog - show event logs<br />
showfirmwaredb - show current database of firmware levels<br />
showhost - show host and host path information<br />
showhostset - show sets of hosts in the system<br />
showinventory - show hardware inventory<br />
showiscsisession - show iscsi sessions<br />
showld - show logical disks (LDs) in the system<br />
showldch - show LD to PD chunklet mapping<br />
showldmap - show LD to VV mapping<br />
showlicense - show installed license key<br />
shownet - show network configuration and status<br />
shownode - show node and its component information<br />
shownodeenv - show node environmental status (voltages,temperatures)<br />
showpatch - show what patches have been applied to the system<br />
showpd - show physical disks (PDs) in the system<br />
showpdata - show preserved data status<br />
showpdch - show status of selected chunklets of physical disks<br />
showpdvv - show PD to VV mapping<br />
showport - show Fibre Channel and iSCSI ports in the system<br />
showportarp - show ARP table for ports<br />
showportdev - show detailed information about devices on a Fibre Channel port<br />
showportisns - show iSNS host information for ports<br />
showportlesb - show Link Error Status Block information about devices on Fibre Channel port <br />
showrcopy - show remote copy configuration information<br />
showrctransport - show information about end-to-end transport for remote copy <br />
showrsv - show information about reservation and registration of VLUNs connected on a Fibre Channel port<br />
showsched - show scheduled tasks in the system<br />
showsnmppw - shows SNMP access passwords<br />
showsnmpmgr - show SNMP trap managers<br />
showspace - show estimated free space<br />
showspare - show information about spare and relocated chunklets<br />
showsshkey - show ssh public keys authorized by the current user<br />
showsys - show system information (system name, serial number etc.)<br />
showsysmgr - show system manager startup state<br />
showtarget - show unrecognized targets<br />
showtask - show information about tasks<br />
showtemplate - show templates<br />
showtoc - show system Table of Contents (TOC) summary<br />
showtocgen - show system Table of Contents (TOC) generation number<br />
showuser - show user accounts and SSH keys<br />
showuseracl - show user access control list<br />
showuserconn - show user connections<br />
showversion - show software versions<br />
showvlun - show virtual LUNs (VLUNs) in the system<br />
showvv - show virtual volumes (VVs) in the system<br />
showvvmap - show VV to LD mapping<br />
showvvpd - show VV distribution across PDs<br />
showvvset - show sets of VVs in the system<br />
checkhealth - perform checks to determine overall state of the system<br />
checkpassword - display authentication and authorization details<br />
checkport - perform loopback test on fc ports<br />
checkpd - perform surface scan or diagnostics on physical disks<br />
checkld - perform validity checks of data on logical disks<br />
checkvv - perform validity checks of virtual volume administrative information.<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Hp/3PAR&diff=1718
Hp/3PAR
2021-02-11T13:05:33Z
<p>Cbs: /* Balance PDs */</p>
<hr />
<div><br />
== Diag ==<br />
<br />
=== Infos for HP (creating Case) ===<br />
<br />
> showsys <br />
> showsys -d<br />
<br />
(System Information inclusing serial)<br />
<br />
<br />
> servicemag status <br />
<br />
(shows if any drive was already evacuated)<br />
<br />
<br />
> checkhealth pd<br />
<br />
(do healthcheck of physical disks)<br />
<br />
<br />
> showpd -s <br />
> showpd -state<br />
> showpd -s -failed<br />
> showpd -failed -degraded<br />
<br />
(show the state of all drives)<br />
<br />
<br />
> showpd -i <br />
<br />
(show the drive inventory including type and serial)<br />
<br />
<br />
> showport -sfp [-d]<br />
<br />
(show the SFP ports and their status [detailed list])<br />
<br />
=== showsys (System info) ===<br />
<br />
Help page<br />
<br />
<pre><br />
showsys - Show system information.<br />
<br />
SYNTAX<br />
showsys [options]<br />
<br />
DESCRIPTION<br />
The showsys command displays the HP 3PAR Storage system properties such as<br />
a system name, serial number, and system capacity information.<br />
<br />
AUTHORITY<br />
Any role in the system<br />
<br />
OPTIONS<br />
-d<br />
Specifies that more detailed information about the system is displayed.<br />
<br />
-param<br />
Specifies that the system parameters are displayed.<br />
<br />
-fan<br />
Displays the system fan information.<br />
<br />
-space<br />
Displays the system capacity information in MB (1024^2 bytes).<br />
<br />
-domainspace<br />
Displays the system capacity information broken down by domain in MB<br />
(1024^2 bytes).<br />
<br />
-desc<br />
Displays the system descriptor properties.<br />
<br />
-devtype FC|NL|SSD<br />
Displays the system capacity information where the disks must have a<br />
device type string matching the specified device type; either Fast<br />
Class (FC), Nearline (NL), Solid State Drive (SSD). This option can<br />
only be issued with the -space option.<br />
<br />
SPECIFIERS<br />
None.<br />
<br />
NOTES<br />
See setsys command for information on setting the threshold parameters<br />
indicated by the Value column in the output for showsys -param.<br />
<br />
In the output for showsys -param, (from configured settings) indicates that<br />
the system parameters displayed have been successfully read from the<br />
Persistent Repository (PR). If the PR is not available (most likely because<br />
of problems with the admin volume), the output reads (from default settings)<br />
and the values displayed would indicate the system defaults. When (from<br />
default settings) is displayed, system parameters cannot be updated.<br />
<br />
If the VVRetentionTimeMax is 0, then the volume retention time in the system<br />
is disabled.<br />
<br />
For the system capacity information, there might be some overlaps among<br />
Volumes, System, and Failed Capacities.<br />
<br />
EXAMPLES<br />
The following example displays the system descriptor properties of a HP 3PAR<br />
storage system:<br />
<br />
cli% showsys -desc<br />
------------System s36------------<br />
System Name : s36<br />
Location : Your Facility Address<br />
Owner : Your Company Name<br />
Contact : Joe Admin<br />
Comment : Your Notes<br />
<br />
The following example displays more detailed (-d option) information about<br />
the same storage server:<br />
<br />
cli% showsys -d<br />
------------General-------------<br />
System Name : S424<br />
System Model : HP_3PAR 7200<br />
Serial Number : 1600424<br />
System ID : 424<br />
Number of Nodes : 2<br />
Master Node : 0<br />
Nodes Online : 0,1<br />
Nodes in Cluster : 0,1<br />
<br />
-----System Capacity (MB)-----<br />
Total Capacity : 6277120<br />
Allocated Capacity : 687872<br />
Free Capacity : 5589248<br />
Failed Capacity : 0<br />
<br />
---------System Fan---------<br />
Primary Node ID : 0<br />
Secondary Node ID : 1<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
Primary Node ID : 1<br />
Secondary Node ID : 0<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
<br />
--------System Descriptors--------<br />
Location :<br />
Owner :<br />
Contact :<br />
Comment :<br />
</pre><br />
<br />
<br />
==== Space details ====<br />
<br />
> showsys -space<br />
<br />
<br />
=== Chech Hardware ===<br />
<br />
> admithw<br />
<br />
Check Hardware and try to fix issues. Initialize new disks<br />
<br />
<br />
=== IOPS Stats ===<br />
<br />
statvlun -ni -iter 1 -hostsum<br />
<br />
Output:<br />
<pre><br />
14:09:22 10/13/2018 r/w I/O per second KBytes per sec Svt ms IOSz KB <br />
Hostname Cur Avg Max Cur Avg Max Cur Avg Cur Avg Qlen<br />
FF1EPPINFVMH02 t 105 105 105 2278 2278 2278 0.42 0.42 21.7 21.7 0<br />
...<br />
</pre><br />
<br />
<br />
== Tuning ==<br />
<br />
=== Move VVs between CPGs ===<br />
<br />
[[Hp/3PAR#Move volume to another CPG using tunevv|Move volume to another CPG using tunevv]]<br />
<br />
<br />
=== Balance PDs ===<br />
<br />
If allocation of physical diskspace is not in balance through disks available.<br/><br />
Dry-Run:<br />
<br />
tunenodech -dr -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
NO Dry-Run:<br />
<br />
tunenodech -waittask -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
{{Achtung|Do this for all Nodes in your 3PAR environment after each other!! Just replace '-node 0' by '-node N'}}<br />
<br />
== CPGs ==<br />
<br />
=== Show CPGs ===<br />
<br />
<pre><br />
% showcpg<br />
----Volumes---- -Usage- -------------(MiB)-------------<br />
Id Name Warn% VVs TPVVs TDVVs Usr Snp Base Snp Free Total<br />
0 FC_r1 - 0 0 0 0 0 0 0 0 0<br />
1 FC_r5 - 35 35 0 35 34 3774976 14848 193536 3983360<br />
2 FC_r6 - 19 19 0 19 0 27048320 0 478208 27526528<br />
3 FC_Snap - 20 20 0 0 20 0 138752 51712 190464<br />
5 SSD_AO_R6 - 0 0 0 0 0 4998656 0 2560 5001216<br />
4 SSD_r5 - 0 0 0 0 0 2070144 0 37248 2107392<br />
--------------------------------------------------------------------------<br />
6 total 54 54 37892096 153600 763264 38808960<br />
</pre><br />
<br />
<br />
Show the Data Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sdg<br />
-----(MiB)------ <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 32768 -ssz 2 -ha cage -t r1 -p -devtype FC <br />
1 FC_r5 - - 32768 -ssz 6 -ha mag -t r5 -p -devtype FC <br />
2 FC_r6 - - 32768 -t r6 -ha mag -ssz 6 -ss 128 -p -devtype FC <br />
3 FC_Snap - - 32768 -t r6 -ha mag -ssz 8 -ss 64 -ch first -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -t r5 -ha mag -ssz 4 -ss 64 -ch first -p -devtype SSD<br />
4 SSD_r5 - - 8192 -t r5 -ha mag -ss 64 -p -devtype SSD<br />
</pre><br />
<br />
<br />
Show the Admin Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sag<br />
-----(MiB)----- <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 8192 -p -devtype FC -ha cage -p -devtype FC<br />
1 FC_r5 - - 8192 -p -devtype FC -p -devtype FC <br />
2 FC_r6 - - 8192 -ha mag -p -devtype FC <br />
3 FC_Snap - - 8192 -ha mag -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -ha mag -p -devtype SSD <br />
4 SSD_r5 - - 8192 -ha mag -p -devtype SSD<br />
</pre><br />
<br />
<br />
=== Create CPG ===<br />
<br />
% createcpg -t r6 -ha mag -sdgs 32G -ssz 8 -ss 128 -p -devtype FC <CPG_Name><br />
<br />
-t RAID Level<br/><br />
-ha HA Settings (port|cage|mag)<br/><br />
-sdgs Data-Growth Size<br/><br />
-ssz size_number_chunklets: 2 for RAID-1, 4 for RAID-5, and 8 for RAID-6<br/><br />
-p define a pattern / -devtype define a pattern for DevTypes to match<br/><br />
<br />
== Virtual Volumes ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Virtual Volumes ===<br />
<br />
showvv -listcols<br />
<br />
showvv -showcols Name,VV_WWN,SnpCPG<br />
<br />
<br />
=== Create Virtual Volume ===<br />
<br />
createvv -tpvv -pol zero_detect -snp_cpg FC_Snap FC_r6 FF3_VMW_AO_03 4194304<br />
<br />
<pre><br />
-Tpvv Thin provisions Virtual Volume<br />
-pol zero_detect I believe it is needed to thin luns<br />
-snp_cfg FC_Snap Where the writes will go for snapshots. HP refers to this as snap or copy space<br />
FF3_VMW_AO_03 Name: this is the lun name<br />
4194304 Size: This is the number to 4tb<br />
8388608 Size: 8tb<br />
</pre><br />
<br />
=== Move volume to another CPG using tunevv ===<br />
<br />
Assuming I want to move a virtual volume ('''VV12_AO''') to another new CPG ('''FC_r6'''):<br />
<br />
tunevv usr_cpg FC_r6 VV12_AO<br />
<br />
The logical disks used for user space are moved to CPG FC_r6 for virtual volume VV12_AO<br />
If you want to move the VV regions only use:<br />
<br />
tunevv usr_cpg FC_r6 -src_cpg FC_r5 VV12_AO<br />
<br />
<br />
Assuming I want to move a snapshot volume ('''VV12_AO''') to another new SnapCPG ('''FC_Snap'''):<br />
<br />
tunevv snp_cpg FC_Snap VV12_AO<br />
<br />
Unfortunatly you will have to run both commands seperatly. As of the documentation they can't be combined.<br />
<br />
<br />
== Auth LDAP ==<br />
<br />
yadda<br />
<br />
<br />
=== Set LDAP auth ===<br />
<br />
<pre><br />
setauthparam -f -clearall<br />
setauthparam -f ldap-server 10.30.111.112<br />
setauthparam -f ldap-server-hn STGWPVEURDC02.<DOMAIN>.<DOMAIN>.com<br />
setauthparam -f kerberos-realm <DOMAIN>.<DOMAIN>.com<br />
setauthparam -f binding sasl<br />
setauthparam -f sasl-mechanism GSSAPI<br />
setauthparam -f accounts-dn "OU=PrivilegedAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=com" <br />
setauthparam -f account-obj user<br />
setauthparam -f account-name-attr sAMAccountName <br />
setauthparam -f memberof-attr memberOf<br />
setauthparam -f super-map "CN=SAN_Admins,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
setauthparam -f browse-map "CN=SAN_ReadOnly,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
</pre><br />
<br />
Check that it works for you:<br />
<br />
checkpassword <LDAP-Username><br />
...<br />
...<br />
user <LDAP-Username> is authenticated and authorized<br />
<br />
=== Get LDAP auth config ===<br />
<br />
<pre><br />
% showauthparam<br />
Param --------------------------------------Value---------------------------------------<br />
ldap-server 10.30.111.106 <br />
ldap-server-hn DC05.<DOMAIN>.<TLD> <br />
kerberos-realm <DOMAIN>.<TLD> <br />
binding sasl <br />
sasl-mechanism GSSAPI<br />
[...]<br />
</pre><br />
<br />
<br />
== Network ==<br />
<br />
yadda<br />
<br />
<br />
=== get network settings ===<br />
<br />
<pre><br />
% shownet<br />
IP Address Netmask/PrefixLen Nodes Active Speed Duplex AutoNeg Status<br />
10.11.12.100 255.255.255.0 01 0 1000 Full Yes Active<br />
<br />
Default route : 10.11.12.1<br />
NTP server : 10.30.111.111<br />
DNS server : 10.11.12.42<br />
</pre><br />
<br />
<br />
=== set DNS server ===<br />
<br />
Add:<br />
<br />
setnet dns -add 10.30.111.111<br />
<br />
Remove:<br />
<br />
setnet dns -remove 10.30.111.111<br />
<br />
<br />
=== re-new expired certificates ===<br />
<br />
Show the actual cert:<br />
<br />
% showcert<br />
Service Commonname Type Enddate Fingerprint <br />
unified-server* HP_3PAR 8200-CZ3740W5MD cert Oct 16 15:36:12 2020 GMT bdae8ff911a32e50a65a81dbae656b46112fa992<br />
<br />
<br />
Renew the cert:<br />
<br />
<pre><br />
createcert unified-server -selfsigned -CN 3par.yadda.com -SAN DNS:3par-alias.yadda.com,DNS:10.12.13.14<br />
The following services will be restarted if currently running:<br />
cim: manages communications with SMI-S clients<br />
<br />
wsapi: Web Services API server<br />
<br />
Continue creating self-signed certificate (yes/no)? yes<br />
Self-signed certificate created.<br />
cimserver restarted<br />
The Web Services API server stopped successfully.<br />
<br />
The Web Services API Server will start shortly.<br />
</pre><br />
<br />
Done!<br />
<br />
<br />
== Full Command List ==<br />
<br />
<pre><br />
HP 3PAR CLI command list<br />
<br />
showalert - show status of system alerts<br />
showauthparam - show authentication parameters<br />
showbattery - show battery status information<br />
showblock - show block mapping info for vvs, lds, pds<br />
showcage - show disk cage information<br />
showcim - show the CIM server information<br />
showclienv - show CLI environment parameters<br />
showcpg - show Common Provisioning Groups (CPGs)<br />
showdate - show date and time on all system nodes<br />
showdomain - show domains in the system<br />
showdomainset - show sets of domains in the system<br />
showeeprom - show node eeprom information<br />
showeventlog - show event logs<br />
showfirmwaredb - show current database of firmware levels<br />
showhost - show host and host path information<br />
showhostset - show sets of hosts in the system<br />
showinventory - show hardware inventory<br />
showiscsisession - show iscsi sessions<br />
showld - show logical disks (LDs) in the system<br />
showldch - show LD to PD chunklet mapping<br />
showldmap - show LD to VV mapping<br />
showlicense - show installed license key<br />
shownet - show network configuration and status<br />
shownode - show node and its component information<br />
shownodeenv - show node environmental status (voltages,temperatures)<br />
showpatch - show what patches have been applied to the system<br />
showpd - show physical disks (PDs) in the system<br />
showpdata - show preserved data status<br />
showpdch - show status of selected chunklets of physical disks<br />
showpdvv - show PD to VV mapping<br />
showport - show Fibre Channel and iSCSI ports in the system<br />
showportarp - show ARP table for ports<br />
showportdev - show detailed information about devices on a Fibre Channel port<br />
showportisns - show iSNS host information for ports<br />
showportlesb - show Link Error Status Block information about devices on Fibre Channel port <br />
showrcopy - show remote copy configuration information<br />
showrctransport - show information about end-to-end transport for remote copy <br />
showrsv - show information about reservation and registration of VLUNs connected on a Fibre Channel port<br />
showsched - show scheduled tasks in the system<br />
showsnmppw - shows SNMP access passwords<br />
showsnmpmgr - show SNMP trap managers<br />
showspace - show estimated free space<br />
showspare - show information about spare and relocated chunklets<br />
showsshkey - show ssh public keys authorized by the current user<br />
showsys - show system information (system name, serial number etc.)<br />
showsysmgr - show system manager startup state<br />
showtarget - show unrecognized targets<br />
showtask - show information about tasks<br />
showtemplate - show templates<br />
showtoc - show system Table of Contents (TOC) summary<br />
showtocgen - show system Table of Contents (TOC) generation number<br />
showuser - show user accounts and SSH keys<br />
showuseracl - show user access control list<br />
showuserconn - show user connections<br />
showversion - show software versions<br />
showvlun - show virtual LUNs (VLUNs) in the system<br />
showvv - show virtual volumes (VVs) in the system<br />
showvvmap - show VV to LD mapping<br />
showvvpd - show VV distribution across PDs<br />
showvvset - show sets of VVs in the system<br />
checkhealth - perform checks to determine overall state of the system<br />
checkpassword - display authentication and authorization details<br />
checkport - perform loopback test on fc ports<br />
checkpd - perform surface scan or diagnostics on physical disks<br />
checkld - perform validity checks of data on logical disks<br />
checkvv - perform validity checks of virtual volume administrative information.<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Hp/3PAR&diff=1717
Hp/3PAR
2021-02-11T13:02:06Z
<p>Cbs: /* Balance PDs */</p>
<hr />
<div><br />
== Diag ==<br />
<br />
=== Infos for HP (creating Case) ===<br />
<br />
> showsys <br />
> showsys -d<br />
<br />
(System Information inclusing serial)<br />
<br />
<br />
> servicemag status <br />
<br />
(shows if any drive was already evacuated)<br />
<br />
<br />
> checkhealth pd<br />
<br />
(do healthcheck of physical disks)<br />
<br />
<br />
> showpd -s <br />
> showpd -state<br />
> showpd -s -failed<br />
> showpd -failed -degraded<br />
<br />
(show the state of all drives)<br />
<br />
<br />
> showpd -i <br />
<br />
(show the drive inventory including type and serial)<br />
<br />
<br />
> showport -sfp [-d]<br />
<br />
(show the SFP ports and their status [detailed list])<br />
<br />
=== showsys (System info) ===<br />
<br />
Help page<br />
<br />
<pre><br />
showsys - Show system information.<br />
<br />
SYNTAX<br />
showsys [options]<br />
<br />
DESCRIPTION<br />
The showsys command displays the HP 3PAR Storage system properties such as<br />
a system name, serial number, and system capacity information.<br />
<br />
AUTHORITY<br />
Any role in the system<br />
<br />
OPTIONS<br />
-d<br />
Specifies that more detailed information about the system is displayed.<br />
<br />
-param<br />
Specifies that the system parameters are displayed.<br />
<br />
-fan<br />
Displays the system fan information.<br />
<br />
-space<br />
Displays the system capacity information in MB (1024^2 bytes).<br />
<br />
-domainspace<br />
Displays the system capacity information broken down by domain in MB<br />
(1024^2 bytes).<br />
<br />
-desc<br />
Displays the system descriptor properties.<br />
<br />
-devtype FC|NL|SSD<br />
Displays the system capacity information where the disks must have a<br />
device type string matching the specified device type; either Fast<br />
Class (FC), Nearline (NL), Solid State Drive (SSD). This option can<br />
only be issued with the -space option.<br />
<br />
SPECIFIERS<br />
None.<br />
<br />
NOTES<br />
See setsys command for information on setting the threshold parameters<br />
indicated by the Value column in the output for showsys -param.<br />
<br />
In the output for showsys -param, (from configured settings) indicates that<br />
the system parameters displayed have been successfully read from the<br />
Persistent Repository (PR). If the PR is not available (most likely because<br />
of problems with the admin volume), the output reads (from default settings)<br />
and the values displayed would indicate the system defaults. When (from<br />
default settings) is displayed, system parameters cannot be updated.<br />
<br />
If the VVRetentionTimeMax is 0, then the volume retention time in the system<br />
is disabled.<br />
<br />
For the system capacity information, there might be some overlaps among<br />
Volumes, System, and Failed Capacities.<br />
<br />
EXAMPLES<br />
The following example displays the system descriptor properties of a HP 3PAR<br />
storage system:<br />
<br />
cli% showsys -desc<br />
------------System s36------------<br />
System Name : s36<br />
Location : Your Facility Address<br />
Owner : Your Company Name<br />
Contact : Joe Admin<br />
Comment : Your Notes<br />
<br />
The following example displays more detailed (-d option) information about<br />
the same storage server:<br />
<br />
cli% showsys -d<br />
------------General-------------<br />
System Name : S424<br />
System Model : HP_3PAR 7200<br />
Serial Number : 1600424<br />
System ID : 424<br />
Number of Nodes : 2<br />
Master Node : 0<br />
Nodes Online : 0,1<br />
Nodes in Cluster : 0,1<br />
<br />
-----System Capacity (MB)-----<br />
Total Capacity : 6277120<br />
Allocated Capacity : 687872<br />
Free Capacity : 5589248<br />
Failed Capacity : 0<br />
<br />
---------System Fan---------<br />
Primary Node ID : 0<br />
Secondary Node ID : 1<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
Primary Node ID : 1<br />
Secondary Node ID : 0<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
<br />
--------System Descriptors--------<br />
Location :<br />
Owner :<br />
Contact :<br />
Comment :<br />
</pre><br />
<br />
<br />
==== Space details ====<br />
<br />
> showsys -space<br />
<br />
<br />
=== Chech Hardware ===<br />
<br />
> admithw<br />
<br />
Check Hardware and try to fix issues. Initialize new disks<br />
<br />
<br />
=== IOPS Stats ===<br />
<br />
statvlun -ni -iter 1 -hostsum<br />
<br />
Output:<br />
<pre><br />
14:09:22 10/13/2018 r/w I/O per second KBytes per sec Svt ms IOSz KB <br />
Hostname Cur Avg Max Cur Avg Max Cur Avg Cur Avg Qlen<br />
FF1EPPINFVMH02 t 105 105 105 2278 2278 2278 0.42 0.42 21.7 21.7 0<br />
...<br />
</pre><br />
<br />
<br />
== Tuning ==<br />
<br />
=== Move VVs between CPGs ===<br />
<br />
[[Hp/3PAR#Move volume to another CPG using tunevv|Move volume to another CPG using tunevv]]<br />
<br />
<br />
=== Balance PDs ===<br />
<br />
If allocation of physical diskspace is not in balance.<br/><br />
Dry-Run:<br />
<br />
tunenodech -dr -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
NO Dry-Run:<br />
<br />
tunenodech -waittask -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
{{Achtung|Do this for all Nodes in your 3PAR environment after each other!! Just replace '-node 0' by '-node N'}}<br />
<br />
== CPGs ==<br />
<br />
=== Show CPGs ===<br />
<br />
<pre><br />
% showcpg<br />
----Volumes---- -Usage- -------------(MiB)-------------<br />
Id Name Warn% VVs TPVVs TDVVs Usr Snp Base Snp Free Total<br />
0 FC_r1 - 0 0 0 0 0 0 0 0 0<br />
1 FC_r5 - 35 35 0 35 34 3774976 14848 193536 3983360<br />
2 FC_r6 - 19 19 0 19 0 27048320 0 478208 27526528<br />
3 FC_Snap - 20 20 0 0 20 0 138752 51712 190464<br />
5 SSD_AO_R6 - 0 0 0 0 0 4998656 0 2560 5001216<br />
4 SSD_r5 - 0 0 0 0 0 2070144 0 37248 2107392<br />
--------------------------------------------------------------------------<br />
6 total 54 54 37892096 153600 763264 38808960<br />
</pre><br />
<br />
<br />
Show the Data Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sdg<br />
-----(MiB)------ <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 32768 -ssz 2 -ha cage -t r1 -p -devtype FC <br />
1 FC_r5 - - 32768 -ssz 6 -ha mag -t r5 -p -devtype FC <br />
2 FC_r6 - - 32768 -t r6 -ha mag -ssz 6 -ss 128 -p -devtype FC <br />
3 FC_Snap - - 32768 -t r6 -ha mag -ssz 8 -ss 64 -ch first -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -t r5 -ha mag -ssz 4 -ss 64 -ch first -p -devtype SSD<br />
4 SSD_r5 - - 8192 -t r5 -ha mag -ss 64 -p -devtype SSD<br />
</pre><br />
<br />
<br />
Show the Admin Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sag<br />
-----(MiB)----- <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 8192 -p -devtype FC -ha cage -p -devtype FC<br />
1 FC_r5 - - 8192 -p -devtype FC -p -devtype FC <br />
2 FC_r6 - - 8192 -ha mag -p -devtype FC <br />
3 FC_Snap - - 8192 -ha mag -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -ha mag -p -devtype SSD <br />
4 SSD_r5 - - 8192 -ha mag -p -devtype SSD<br />
</pre><br />
<br />
<br />
=== Create CPG ===<br />
<br />
% createcpg -t r6 -ha mag -sdgs 32G -ssz 8 -ss 128 -p -devtype FC <CPG_Name><br />
<br />
-t RAID Level<br/><br />
-ha HA Settings (port|cage|mag)<br/><br />
-sdgs Data-Growth Size<br/><br />
-ssz size_number_chunklets: 2 for RAID-1, 4 for RAID-5, and 8 for RAID-6<br/><br />
-p define a pattern / -devtype define a pattern for DevTypes to match<br/><br />
<br />
== Virtual Volumes ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Virtual Volumes ===<br />
<br />
showvv -listcols<br />
<br />
showvv -showcols Name,VV_WWN,SnpCPG<br />
<br />
<br />
=== Create Virtual Volume ===<br />
<br />
createvv -tpvv -pol zero_detect -snp_cpg FC_Snap FC_r6 FF3_VMW_AO_03 4194304<br />
<br />
<pre><br />
-Tpvv Thin provisions Virtual Volume<br />
-pol zero_detect I believe it is needed to thin luns<br />
-snp_cfg FC_Snap Where the writes will go for snapshots. HP refers to this as snap or copy space<br />
FF3_VMW_AO_03 Name: this is the lun name<br />
4194304 Size: This is the number to 4tb<br />
8388608 Size: 8tb<br />
</pre><br />
<br />
=== Move volume to another CPG using tunevv ===<br />
<br />
Assuming I want to move a virtual volume ('''VV12_AO''') to another new CPG ('''FC_r6'''):<br />
<br />
tunevv usr_cpg FC_r6 VV12_AO<br />
<br />
The logical disks used for user space are moved to CPG FC_r6 for virtual volume VV12_AO<br />
If you want to move the VV regions only use:<br />
<br />
tunevv usr_cpg FC_r6 -src_cpg FC_r5 VV12_AO<br />
<br />
<br />
Assuming I want to move a snapshot volume ('''VV12_AO''') to another new SnapCPG ('''FC_Snap'''):<br />
<br />
tunevv snp_cpg FC_Snap VV12_AO<br />
<br />
Unfortunatly you will have to run both commands seperatly. As of the documentation they can't be combined.<br />
<br />
<br />
== Auth LDAP ==<br />
<br />
yadda<br />
<br />
<br />
=== Set LDAP auth ===<br />
<br />
<pre><br />
setauthparam -f -clearall<br />
setauthparam -f ldap-server 10.30.111.112<br />
setauthparam -f ldap-server-hn STGWPVEURDC02.<DOMAIN>.<DOMAIN>.com<br />
setauthparam -f kerberos-realm <DOMAIN>.<DOMAIN>.com<br />
setauthparam -f binding sasl<br />
setauthparam -f sasl-mechanism GSSAPI<br />
setauthparam -f accounts-dn "OU=PrivilegedAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=com" <br />
setauthparam -f account-obj user<br />
setauthparam -f account-name-attr sAMAccountName <br />
setauthparam -f memberof-attr memberOf<br />
setauthparam -f super-map "CN=SAN_Admins,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
setauthparam -f browse-map "CN=SAN_ReadOnly,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
</pre><br />
<br />
Check that it works for you:<br />
<br />
checkpassword <LDAP-Username><br />
...<br />
...<br />
user <LDAP-Username> is authenticated and authorized<br />
<br />
=== Get LDAP auth config ===<br />
<br />
<pre><br />
% showauthparam<br />
Param --------------------------------------Value---------------------------------------<br />
ldap-server 10.30.111.106 <br />
ldap-server-hn DC05.<DOMAIN>.<TLD> <br />
kerberos-realm <DOMAIN>.<TLD> <br />
binding sasl <br />
sasl-mechanism GSSAPI<br />
[...]<br />
</pre><br />
<br />
<br />
== Network ==<br />
<br />
yadda<br />
<br />
<br />
=== get network settings ===<br />
<br />
<pre><br />
% shownet<br />
IP Address Netmask/PrefixLen Nodes Active Speed Duplex AutoNeg Status<br />
10.11.12.100 255.255.255.0 01 0 1000 Full Yes Active<br />
<br />
Default route : 10.11.12.1<br />
NTP server : 10.30.111.111<br />
DNS server : 10.11.12.42<br />
</pre><br />
<br />
<br />
=== set DNS server ===<br />
<br />
Add:<br />
<br />
setnet dns -add 10.30.111.111<br />
<br />
Remove:<br />
<br />
setnet dns -remove 10.30.111.111<br />
<br />
<br />
=== re-new expired certificates ===<br />
<br />
Show the actual cert:<br />
<br />
% showcert<br />
Service Commonname Type Enddate Fingerprint <br />
unified-server* HP_3PAR 8200-CZ3740W5MD cert Oct 16 15:36:12 2020 GMT bdae8ff911a32e50a65a81dbae656b46112fa992<br />
<br />
<br />
Renew the cert:<br />
<br />
<pre><br />
createcert unified-server -selfsigned -CN 3par.yadda.com -SAN DNS:3par-alias.yadda.com,DNS:10.12.13.14<br />
The following services will be restarted if currently running:<br />
cim: manages communications with SMI-S clients<br />
<br />
wsapi: Web Services API server<br />
<br />
Continue creating self-signed certificate (yes/no)? yes<br />
Self-signed certificate created.<br />
cimserver restarted<br />
The Web Services API server stopped successfully.<br />
<br />
The Web Services API Server will start shortly.<br />
</pre><br />
<br />
Done!<br />
<br />
<br />
== Full Command List ==<br />
<br />
<pre><br />
HP 3PAR CLI command list<br />
<br />
showalert - show status of system alerts<br />
showauthparam - show authentication parameters<br />
showbattery - show battery status information<br />
showblock - show block mapping info for vvs, lds, pds<br />
showcage - show disk cage information<br />
showcim - show the CIM server information<br />
showclienv - show CLI environment parameters<br />
showcpg - show Common Provisioning Groups (CPGs)<br />
showdate - show date and time on all system nodes<br />
showdomain - show domains in the system<br />
showdomainset - show sets of domains in the system<br />
showeeprom - show node eeprom information<br />
showeventlog - show event logs<br />
showfirmwaredb - show current database of firmware levels<br />
showhost - show host and host path information<br />
showhostset - show sets of hosts in the system<br />
showinventory - show hardware inventory<br />
showiscsisession - show iscsi sessions<br />
showld - show logical disks (LDs) in the system<br />
showldch - show LD to PD chunklet mapping<br />
showldmap - show LD to VV mapping<br />
showlicense - show installed license key<br />
shownet - show network configuration and status<br />
shownode - show node and its component information<br />
shownodeenv - show node environmental status (voltages,temperatures)<br />
showpatch - show what patches have been applied to the system<br />
showpd - show physical disks (PDs) in the system<br />
showpdata - show preserved data status<br />
showpdch - show status of selected chunklets of physical disks<br />
showpdvv - show PD to VV mapping<br />
showport - show Fibre Channel and iSCSI ports in the system<br />
showportarp - show ARP table for ports<br />
showportdev - show detailed information about devices on a Fibre Channel port<br />
showportisns - show iSNS host information for ports<br />
showportlesb - show Link Error Status Block information about devices on Fibre Channel port <br />
showrcopy - show remote copy configuration information<br />
showrctransport - show information about end-to-end transport for remote copy <br />
showrsv - show information about reservation and registration of VLUNs connected on a Fibre Channel port<br />
showsched - show scheduled tasks in the system<br />
showsnmppw - shows SNMP access passwords<br />
showsnmpmgr - show SNMP trap managers<br />
showspace - show estimated free space<br />
showspare - show information about spare and relocated chunklets<br />
showsshkey - show ssh public keys authorized by the current user<br />
showsys - show system information (system name, serial number etc.)<br />
showsysmgr - show system manager startup state<br />
showtarget - show unrecognized targets<br />
showtask - show information about tasks<br />
showtemplate - show templates<br />
showtoc - show system Table of Contents (TOC) summary<br />
showtocgen - show system Table of Contents (TOC) generation number<br />
showuser - show user accounts and SSH keys<br />
showuseracl - show user access control list<br />
showuserconn - show user connections<br />
showversion - show software versions<br />
showvlun - show virtual LUNs (VLUNs) in the system<br />
showvv - show virtual volumes (VVs) in the system<br />
showvvmap - show VV to LD mapping<br />
showvvpd - show VV distribution across PDs<br />
showvvset - show sets of VVs in the system<br />
checkhealth - perform checks to determine overall state of the system<br />
checkpassword - display authentication and authorization details<br />
checkport - perform loopback test on fc ports<br />
checkpd - perform surface scan or diagnostics on physical disks<br />
checkld - perform validity checks of data on logical disks<br />
checkvv - perform validity checks of virtual volume administrative information.<br />
</pre></div>
Cbs
https://schnallich.net/index.php?title=Hp/3PAR&diff=1716
Hp/3PAR
2021-02-11T08:14:48Z
<p>Cbs: </p>
<hr />
<div><br />
== Diag ==<br />
<br />
=== Infos for HP (creating Case) ===<br />
<br />
> showsys <br />
> showsys -d<br />
<br />
(System Information inclusing serial)<br />
<br />
<br />
> servicemag status <br />
<br />
(shows if any drive was already evacuated)<br />
<br />
<br />
> checkhealth pd<br />
<br />
(do healthcheck of physical disks)<br />
<br />
<br />
> showpd -s <br />
> showpd -state<br />
> showpd -s -failed<br />
> showpd -failed -degraded<br />
<br />
(show the state of all drives)<br />
<br />
<br />
> showpd -i <br />
<br />
(show the drive inventory including type and serial)<br />
<br />
<br />
> showport -sfp [-d]<br />
<br />
(show the SFP ports and their status [detailed list])<br />
<br />
=== showsys (System info) ===<br />
<br />
Help page<br />
<br />
<pre><br />
showsys - Show system information.<br />
<br />
SYNTAX<br />
showsys [options]<br />
<br />
DESCRIPTION<br />
The showsys command displays the HP 3PAR Storage system properties such as<br />
a system name, serial number, and system capacity information.<br />
<br />
AUTHORITY<br />
Any role in the system<br />
<br />
OPTIONS<br />
-d<br />
Specifies that more detailed information about the system is displayed.<br />
<br />
-param<br />
Specifies that the system parameters are displayed.<br />
<br />
-fan<br />
Displays the system fan information.<br />
<br />
-space<br />
Displays the system capacity information in MB (1024^2 bytes).<br />
<br />
-domainspace<br />
Displays the system capacity information broken down by domain in MB<br />
(1024^2 bytes).<br />
<br />
-desc<br />
Displays the system descriptor properties.<br />
<br />
-devtype FC|NL|SSD<br />
Displays the system capacity information where the disks must have a<br />
device type string matching the specified device type; either Fast<br />
Class (FC), Nearline (NL), Solid State Drive (SSD). This option can<br />
only be issued with the -space option.<br />
<br />
SPECIFIERS<br />
None.<br />
<br />
NOTES<br />
See setsys command for information on setting the threshold parameters<br />
indicated by the Value column in the output for showsys -param.<br />
<br />
In the output for showsys -param, (from configured settings) indicates that<br />
the system parameters displayed have been successfully read from the<br />
Persistent Repository (PR). If the PR is not available (most likely because<br />
of problems with the admin volume), the output reads (from default settings)<br />
and the values displayed would indicate the system defaults. When (from<br />
default settings) is displayed, system parameters cannot be updated.<br />
<br />
If the VVRetentionTimeMax is 0, then the volume retention time in the system<br />
is disabled.<br />
<br />
For the system capacity information, there might be some overlaps among<br />
Volumes, System, and Failed Capacities.<br />
<br />
EXAMPLES<br />
The following example displays the system descriptor properties of a HP 3PAR<br />
storage system:<br />
<br />
cli% showsys -desc<br />
------------System s36------------<br />
System Name : s36<br />
Location : Your Facility Address<br />
Owner : Your Company Name<br />
Contact : Joe Admin<br />
Comment : Your Notes<br />
<br />
The following example displays more detailed (-d option) information about<br />
the same storage server:<br />
<br />
cli% showsys -d<br />
------------General-------------<br />
System Name : S424<br />
System Model : HP_3PAR 7200<br />
Serial Number : 1600424<br />
System ID : 424<br />
Number of Nodes : 2<br />
Master Node : 0<br />
Nodes Online : 0,1<br />
Nodes in Cluster : 0,1<br />
<br />
-----System Capacity (MB)-----<br />
Total Capacity : 6277120<br />
Allocated Capacity : 687872<br />
Free Capacity : 5589248<br />
Failed Capacity : 0<br />
<br />
---------System Fan---------<br />
Primary Node ID : 0<br />
Secondary Node ID : 1<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
Primary Node ID : 1<br />
Secondary Node ID : 0<br />
State : OK<br />
LED : Green<br />
Speed : Normal<br />
<br />
--------System Descriptors--------<br />
Location :<br />
Owner :<br />
Contact :<br />
Comment :<br />
</pre><br />
<br />
<br />
==== Space details ====<br />
<br />
> showsys -space<br />
<br />
<br />
=== Chech Hardware ===<br />
<br />
> admithw<br />
<br />
Check Hardware and try to fix issues. Initialize new disks<br />
<br />
<br />
=== IOPS Stats ===<br />
<br />
statvlun -ni -iter 1 -hostsum<br />
<br />
Output:<br />
<pre><br />
14:09:22 10/13/2018 r/w I/O per second KBytes per sec Svt ms IOSz KB <br />
Hostname Cur Avg Max Cur Avg Max Cur Avg Cur Avg Qlen<br />
FF1EPPINFVMH02 t 105 105 105 2278 2278 2278 0.42 0.42 21.7 21.7 0<br />
...<br />
</pre><br />
<br />
<br />
== Tuning ==<br />
<br />
=== Move VVs between CPGs ===<br />
<br />
[[Hp/3PAR#Move volume to another CPG using tunevv|Move volume to another CPG using tunevv]]<br />
<br />
<br />
=== Balance PDs ===<br />
<br />
If allocation of physical diskspace is not in balance.<br/><br />
Dry-Run:<br />
<br />
tunenodech -dr -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
NO Dry-Run:<br />
<br />
tunenodech -waittask -debug -f -maxchunk 8 -chunkpct 5 -node 0 -devtype FC -fulldiskpct 1 -chonly<br />
<br />
<br />
<br />
<br />
== CPGs ==<br />
<br />
=== Show CPGs ===<br />
<br />
<pre><br />
% showcpg<br />
----Volumes---- -Usage- -------------(MiB)-------------<br />
Id Name Warn% VVs TPVVs TDVVs Usr Snp Base Snp Free Total<br />
0 FC_r1 - 0 0 0 0 0 0 0 0 0<br />
1 FC_r5 - 35 35 0 35 34 3774976 14848 193536 3983360<br />
2 FC_r6 - 19 19 0 19 0 27048320 0 478208 27526528<br />
3 FC_Snap - 20 20 0 0 20 0 138752 51712 190464<br />
5 SSD_AO_R6 - 0 0 0 0 0 4998656 0 2560 5001216<br />
4 SSD_r5 - 0 0 0 0 0 2070144 0 37248 2107392<br />
--------------------------------------------------------------------------<br />
6 total 54 54 37892096 153600 763264 38808960<br />
</pre><br />
<br />
<br />
Show the Data Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sdg<br />
-----(MiB)------ <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 32768 -ssz 2 -ha cage -t r1 -p -devtype FC <br />
1 FC_r5 - - 32768 -ssz 6 -ha mag -t r5 -p -devtype FC <br />
2 FC_r6 - - 32768 -t r6 -ha mag -ssz 6 -ss 128 -p -devtype FC <br />
3 FC_Snap - - 32768 -t r6 -ha mag -ssz 8 -ss 64 -ch first -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -t r5 -ha mag -ssz 4 -ss 64 -ch first -p -devtype SSD<br />
4 SSD_r5 - - 8192 -t r5 -ha mag -ss 64 -p -devtype SSD<br />
</pre><br />
<br />
<br />
Show the Admin Grows Values and Config:<br />
<br />
<pre><br />
% showcpg -sag<br />
-----(MiB)----- <br />
Id Name Warn Limit Grow Args <br />
0 FC_r1 - - 8192 -p -devtype FC -ha cage -p -devtype FC<br />
1 FC_r5 - - 8192 -p -devtype FC -p -devtype FC <br />
2 FC_r6 - - 8192 -ha mag -p -devtype FC <br />
3 FC_Snap - - 8192 -ha mag -p -devtype FC <br />
5 SSD_AO_R6 - - 8192 -ha mag -p -devtype SSD <br />
4 SSD_r5 - - 8192 -ha mag -p -devtype SSD<br />
</pre><br />
<br />
<br />
=== Create CPG ===<br />
<br />
% createcpg -t r6 -ha mag -sdgs 32G -ssz 8 -ss 128 -p -devtype FC <CPG_Name><br />
<br />
-t RAID Level<br/><br />
-ha HA Settings (port|cage|mag)<br/><br />
-sdgs Data-Growth Size<br/><br />
-ssz size_number_chunklets: 2 for RAID-1, 4 for RAID-5, and 8 for RAID-6<br/><br />
-p define a pattern / -devtype define a pattern for DevTypes to match<br/><br />
<br />
== Virtual Volumes ==<br />
<br />
yadda<br />
<br />
<br />
=== Show Virtual Volumes ===<br />
<br />
showvv -listcols<br />
<br />
showvv -showcols Name,VV_WWN,SnpCPG<br />
<br />
<br />
=== Create Virtual Volume ===<br />
<br />
createvv -tpvv -pol zero_detect -snp_cpg FC_Snap FC_r6 FF3_VMW_AO_03 4194304<br />
<br />
<pre><br />
-Tpvv Thin provisions Virtual Volume<br />
-pol zero_detect I believe it is needed to thin luns<br />
-snp_cfg FC_Snap Where the writes will go for snapshots. HP refers to this as snap or copy space<br />
FF3_VMW_AO_03 Name: this is the lun name<br />
4194304 Size: This is the number to 4tb<br />
8388608 Size: 8tb<br />
</pre><br />
<br />
=== Move volume to another CPG using tunevv ===<br />
<br />
Assuming I want to move a virtual volume ('''VV12_AO''') to another new CPG ('''FC_r6'''):<br />
<br />
tunevv usr_cpg FC_r6 VV12_AO<br />
<br />
The logical disks used for user space are moved to CPG FC_r6 for virtual volume VV12_AO<br />
If you want to move the VV regions only use:<br />
<br />
tunevv usr_cpg FC_r6 -src_cpg FC_r5 VV12_AO<br />
<br />
<br />
Assuming I want to move a snapshot volume ('''VV12_AO''') to another new SnapCPG ('''FC_Snap'''):<br />
<br />
tunevv snp_cpg FC_Snap VV12_AO<br />
<br />
Unfortunatly you will have to run both commands seperatly. As of the documentation they can't be combined.<br />
<br />
<br />
== Auth LDAP ==<br />
<br />
yadda<br />
<br />
<br />
=== Set LDAP auth ===<br />
<br />
<pre><br />
setauthparam -f -clearall<br />
setauthparam -f ldap-server 10.30.111.112<br />
setauthparam -f ldap-server-hn STGWPVEURDC02.<DOMAIN>.<DOMAIN>.com<br />
setauthparam -f kerberos-realm <DOMAIN>.<DOMAIN>.com<br />
setauthparam -f binding sasl<br />
setauthparam -f sasl-mechanism GSSAPI<br />
setauthparam -f accounts-dn "OU=PrivilegedAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=com" <br />
setauthparam -f account-obj user<br />
setauthparam -f account-name-attr sAMAccountName <br />
setauthparam -f memberof-attr memberOf<br />
setauthparam -f super-map "CN=SAN_Admins,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
setauthparam -f browse-map "CN=SAN_ReadOnly,OU=PrivilegedRoles,OU=Groups,DC=<DOMAIN>,DC=<DOMAIN>,DC=com"<br />
</pre><br />
<br />
Check that it works for you:<br />
<br />
checkpassword <LDAP-Username><br />
...<br />
...<br />
user <LDAP-Username> is authenticated and authorized<br />
<br />
=== Get LDAP auth config ===<br />
<br />
<pre><br />
% showauthparam<br />
Param --------------------------------------Value---------------------------------------<br />
ldap-server 10.30.111.106 <br />
ldap-server-hn DC05.<DOMAIN>.<TLD> <br />
kerberos-realm <DOMAIN>.<TLD> <br />
binding sasl <br />
sasl-mechanism GSSAPI<br />
[...]<br />
</pre><br />
<br />
<br />
== Network ==<br />
<br />
yadda<br />
<br />
<br />
=== get network settings ===<br />
<br />
<pre><br />
% shownet<br />
IP Address Netmask/PrefixLen Nodes Active Speed Duplex AutoNeg Status<br />
10.11.12.100 255.255.255.0 01 0 1000 Full Yes Active<br />
<br />
Default route : 10.11.12.1<br />
NTP server : 10.30.111.111<br />
DNS server : 10.11.12.42<br />
</pre><br />
<br />
<br />
=== set DNS server ===<br />
<br />
Add:<br />
<br />
setnet dns -add 10.30.111.111<br />
<br />
Remove:<br />
<br />
setnet dns -remove 10.30.111.111<br />
<br />
<br />
=== re-new expired certificates ===<br />
<br />
Show the actual cert:<br />
<br />
% showcert<br />
Service Commonname Type Enddate Fingerprint <br />
unified-server* HP_3PAR 8200-CZ3740W5MD cert Oct 16 15:36:12 2020 GMT bdae8ff911a32e50a65a81dbae656b46112fa992<br />
<br />
<br />
Renew the cert:<br />
<br />
<pre><br />
createcert unified-server -selfsigned -CN 3par.yadda.com -SAN DNS:3par-alias.yadda.com,DNS:10.12.13.14<br />
The following services will be restarted if currently running:<br />
cim: manages communications with SMI-S clients<br />
<br />
wsapi: Web Services API server<br />
<br />
Continue creating self-signed certificate (yes/no)? yes<br />
Self-signed certificate created.<br />
cimserver restarted<br />
The Web Services API server stopped successfully.<br />
<br />
The Web Services API Server will start shortly.<br />
</pre><br />
<br />
Done!<br />
<br />
<br />
== Full Command List ==<br />
<br />
<pre><br />
HP 3PAR CLI command list<br />
<br />
showalert - show status of system alerts<br />
showauthparam - show authentication parameters<br />
showbattery - show battery status information<br />
showblock - show block mapping info for vvs, lds, pds<br />
showcage - show disk cage information<br />
showcim - show the CIM server information<br />
showclienv - show CLI environment parameters<br />
showcpg - show Common Provisioning Groups (CPGs)<br />
showdate - show date and time on all system nodes<br />
showdomain - show domains in the system<br />
showdomainset - show sets of domains in the system<br />
showeeprom - show node eeprom information<br />
showeventlog - show event logs<br />
showfirmwaredb - show current database of firmware levels<br />
showhost - show host and host path information<br />
showhostset - show sets of hosts in the system<br />
showinventory - show hardware inventory<br />
showiscsisession - show iscsi sessions<br />
showld - show logical disks (LDs) in the system<br />
showldch - show LD to PD chunklet mapping<br />
showldmap - show LD to VV mapping<br />
showlicense - show installed license key<br />
shownet - show network configuration and status<br />
shownode - show node and its component information<br />
shownodeenv - show node environmental status (voltages,temperatures)<br />
showpatch - show what patches have been applied to the system<br />
showpd - show physical disks (PDs) in the system<br />
showpdata - show preserved data status<br />
showpdch - show status of selected chunklets of physical disks<br />
showpdvv - show PD to VV mapping<br />
showport - show Fibre Channel and iSCSI ports in the system<br />
showportarp - show ARP table for ports<br />
showportdev - show detailed information about devices on a Fibre Channel port<br />
showportisns - show iSNS host information for ports<br />
showportlesb - show Link Error Status Block information about devices on Fibre Channel port <br />
showrcopy - show remote copy configuration information<br />
showrctransport - show information about end-to-end transport for remote copy <br />
showrsv - show information about reservation and registration of VLUNs connected on a Fibre Channel port<br />
showsched - show scheduled tasks in the system<br />
showsnmppw - shows SNMP access passwords<br />
showsnmpmgr - show SNMP trap managers<br />
showspace - show estimated free space<br />
showspare - show information about spare and relocated chunklets<br />
showsshkey - show ssh public keys authorized by the current user<br />
showsys - show system information (system name, serial number etc.)<br />
showsysmgr - show system manager startup state<br />
showtarget - show unrecognized targets<br />
showtask - show information about tasks<br />
showtemplate - show templates<br />
showtoc - show system Table of Contents (TOC) summary<br />
showtocgen - show system Table of Contents (TOC) generation number<br />
showuser - show user accounts and SSH keys<br />
showuseracl - show user access control list<br />
showuserconn - show user connections<br />
showversion - show software versions<br />
showvlun - show virtual LUNs (VLUNs) in the system<br />
showvv - show virtual volumes (VVs) in the system<br />
showvvmap - show VV to LD mapping<br />
showvvpd - show VV distribution across PDs<br />
showvvset - show sets of VVs in the system<br />
checkhealth - perform checks to determine overall state of the system<br />
checkpassword - display authentication and authorization details<br />
checkport - perform loopback test on fc ports<br />
checkpd - perform surface scan or diagnostics on physical disks<br />
checkld - perform validity checks of data on logical disks<br />
checkvv - perform validity checks of virtual volume administrative information.<br />
</pre></div>
Cbs