################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 🐍 PYTHON: ================================================================================================================================================================================================================================================================ 🐍 Instructions / Commands / Verbs / Functions / Keywords / Methods / Actions ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📦 import Import modules or specific attributes import math 🔧 def Define a function def greet(name): print("Hello", name) 🔙 return Return a value from a function return x + y 🛠️ try Start a try block for exception handling try: x=1/0 ❓ if If conditional statement if x > 0: 🔄 elif Else-if conditional branching elif x == 0: ❎ else Else conditional branch else: ⚠️ except Exception handler block except ZeroDivisionError: 🔁 while While loop while x < 5: 🔄 for For loop for i in range(3): 🔍 in Membership test in loops and conditions if 'a' in my_str: 📤 from Import specific attributes from a module from os import path 📝 pass No operation placeholder pass 🚫 break Break out of a loop break 🔜 continue Continue to next loop iteration continue 📣 print Output to console print("Hello world") ⬆️ raise Raise an exception raise ValueError("Wrong value") 🧪 assert Assert a condition for debugging assert x > 0, "Must be positive" 🔒 with Context manager (resource handling) with open('file.txt') as f: 🗑️ del Delete an object or variable del my_var 👫 global Declare a global variable inside a function global count 🔐 nonlocal Declare a nonlocal variable in nested scopes nonlocal total 🧮 lambda Create anonymous functions f = lambda x: x**2 📚 yield Yield value from generator function yield i 🎛️ async Define an asynchronous function async def fetch(): ⏳ await Wait for an async function to complete result = await fetch() 🧰 try...except...finally Try block w/ exception handler and cleanup final block try: ... 👉 else with loops Optional else block for loops if no break for i in x: ... else: print("Done") 📦 import as Import module with alias import numpy as np 📄 open Open a file or resource open('test.txt', 'r') 🪝 __init__ Constructor method in classes def __init__(self, val): 🏗️ class Define a class class Person: ⚙️ def __str__ String representation method of a class def __str__(self): ⚙️ def __repr__ Official string representation method of a class def __repr__(self): ⚙️ def __call__ Make object callable def __call__(self): 🔄 for...else For loop with optional else clause if no break for i in l: ... else: print("No break") ⬇️ try...else Try block with else if no exception try: ... else: print("No error") 🎯 assert with message Assert with optional error message assert x != 0, "Zero not allowed" 🧩 isinstance Check object type isinstance(obj, int) 🧪 type Get type of an object type(x) ✂️ slice Slice notation for sequences seq[2:5] 🔢 range Generate sequence of numbers range(5) 🧱 list Create list my_list = [1,2,3] 📑 tuple Create tuple my_tuple = (1, 2) 🔒 set Create set my_set = {1,2,3} 🌍 dict Create dictionary my_dict = {'a':1} 🧹 delattr Delete attribute of objects delattr(obj, 'attr') 📋 setattr Set attribute of objects setattr(obj, 'attr', val) 🧩 getattr Get attribute of objects getattr(obj, 'attr') 🕵️‍♂️ eval Evaluate string as Python expression eval('3 + 5') 📊 exec Execute string as Python code exec('print("Hi")') 🧱 list comprehension Concise list creation [x*2 for x in range(5)] 🧊 generator expression Create generator expression (x*2 for x in range(5)) 🔧 decorator Modify functions/classes with syntactic sugar @staticmethod 💣 raise from Re-raise exceptions with explicit cause raise ValueError from e 🔗 chained comparisons Compare multiple values 1 < x < 10 🚦 conditional expressions # Ternary if expression x = a if cond else b 🦾 walrus operator Assignment expression inside expressions if (n := len(x)) > 10: 💾 file handling keywords File open/read/write/close with open('f.txt') as file: 📑 match case Structural pattern matching (Python 3.10+) match x: case 1: ... ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📑 Python Built-in Functions ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 〰️ abs() Return absolute value abs(-7) # 7 🩺 all() Check if all items are true all([True, True]) # True 🔍 any() Check if any item is true any([False, True]) # True 🅱️ ascii() Return ASCII representation of object ascii("é") # "'\\xe9'" 🐦 bin() Convert int to binary string bin(3) # '0b11' 🔢 bool() Convert to Boolean bool(0) # False 🏗️ breakpoint() Enter debugger breakpoint() 🧱 bytearray() Mutable array of bytes bytearray(b"Hi") 💠 bytes() Immutable bytes object bytes([1,2,3]) 🔡 callable() Check if object is callable callable(len) # True 📊 chr() Convert int to Unicode char chr(65) # 'A' 📝 classmethod() Declare class method @classmethod ⚖️ compile() Compile source to code object compile("x=5", "", "exec") ⊂ complex() Create complex number complex(1, 2) 📋 delattr() Delete object attribute delattr(obj, 'attr') 🌍 dict() Create dict dict(a=1, b=2) 🌊 dir() List attributes and methods dir([]) 🖇️ divmod() Quotient and remainder divmod(5, 2) # (2, 1) 👁️ enumerate() Enumerate iterable list(enumerate(['a','b'])) # [(0,'a'),(1,'b')] ☑️ eval() Evaluate string expression eval("1+2") # 3 📤 exec() Execute Python code string exec("print('hi')") 🧾 filter() Filter iterable by function list(filter(lambda x: x>0, [-1,0,1])) 📈 float() Convert to float float("2.5") # 2.5 📜 format() Format a value format(123, "06") 🧰 frozenset() Immutable set frozenset({1,2}) 🧩 getattr() Get object attribute getattr(obj, 'attr', None) 🛑 globals() Get global symbol table globals() 🧱 hasattr() Check if object has attribute hasattr(obj, 'attr') 🧮 hash() Get hash of object hash("abc") 🎯 help() Show help documentation help(abs) 🏠 hex() Convert to hex string hex(255) # '0xff' 🆔 id() Get object memory id id(obj) 🏗️ input() Read input from user input("Enter:") 🔣 int() Convert to int int("5") 📁 isinstance() Check object type isinstance(5, int) 🧬 issubclass() Check class inheritance issubclass(bool, int) 📍 iter() Get iterator iter([1,2]) 🧪 len() Get length of object len([1,2]) 📦 list() Create list list((1,2)) 📤 locals() Get local symbol table locals() 🔗 map() Map function over iterable list(map(str, [1,2])) 🧩 max() Max element max(1, 2, 3) ➖ min() Min element min([1, 2, 3]) 🧑‍💻 next() Next iterator item next(iter([1,2])) ⛔ object() Base object class object() 🎨 oct() Convert to octal string oct(8) # '0o10' 📄 open() Open file open("file.txt") ⏪ ord() Unicode code of char ord("A") # 65 🔑 pow() Power calculation pow(2,3) # 8 📦 print() Print output print("Hello") 🏷️ property() Create property property(fget) 🎲 range() Range of numbers range(5) 🗑️ repr() String representation repr("abc") 🔄 reversed() Reverse iterator list(reversed([1,2,3])) 🧊 round() Round number round(3.14159, 2) # 3.14 🔒 set() Create set set([1,2]) 🏗️ setattr() Set attribute setattr(obj, 'attr', 3) 📑 slice() Slice object slice(1,5) 🗂️ sorted() Sorted iterable sorted([3,1,2]) 📀 staticmethod() Create static method @staticmethod 🧩 str() Convert to string str(123) 🧱 sum() Sum iterable sum([1,2]) ✂️ super() Access superclass super() 📑 tuple() Create tuple tuple([1,2]) 📝 type() Get object type type(5) 📍 vars() Get __dict__ attribute vars(obj) 🎤 zip() Zip iterables list(zip([1,2], ['a','b'])) ⚡ __import__() Import module dynamically __import__('math') ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ✨ String Methods (str) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔡 .capitalize() Capitalize first char "hello".capitalize() 🔡 .casefold() Casefold string (lowercase) "ß".casefold() 🔡 .center(width, fillchar) Center string with padding "cat".center(5, '*') 🔡 .count(sub[, start, end]) Count occurrences "hello".count('l') 🔡 .encode(encoding, errors) Encode string "abc".encode('utf-8') 🔡 .endswith(suffix[, start, end]) Ends with substring "hello".endswith('o') 🔡 .expandtabs(tabsize) Expand tabs "a\tb".expandtabs(2) 🔡 .find(sub[, start, end]) Find substring "hello".find('e') 🔡 .format(*args, **kwargs) Format string "{} {}".format("hi", 2) 🔡 .format_map(mapping) Format using mapping "{name}".format_map({'name':'Tom'}) 🔡 .index(sub[, start, end]) Find substring, raises if missing "hello".index('e') 🔡 .isalnum() Check if alphanumeric "abc123".isalnum() 🔡 .isalpha() Check if alphabetic "abc".isalpha() 🔡 .isascii() Check if ASCII chars only "abc".isascii() 🔡 .isdecimal() Check if decimal digit "123".isdecimal() 🔡 .isdigit() Check if digits only "123".isdigit() 🔡 .isidentifier() Check valid identifier "var_1".isidentifier() 🔡 .islower() Check all lowercase "abc".islower() 🔡 .isnumeric() Check numeric "123".isnumeric() 🔡 .isprintable() Check printable chars "abc\n".isprintable() 🔡 .isspace() Check if whitespace only " \t\n".isspace() 🔡 .istitle() Check title casing "Hello".istitle() 🔡 .isupper() Check all uppercase "ABC".isupper() 🔡 .join(iterable) Join with string separator ",".join(['a','b']) 🔡 .ljust(width, fillchar) Left justify string "cat".ljust(5, '*') 🔡 .lower() Convert to lowercase "ABC".lower() 🔡 .lstrip(chars) Strip left chars " abc".lstrip() 🔡 .partition(sep) Split at first sep "a,b,c".partition(',') 🔡 .removeprefix(prefix) Remove prefix "Test".removeprefix("Te") 🔡 .removesuffix(suffix) Remove suffix "Test".removesuffix("st") 🔡 .replace(old, new[, count]) Replace substrings "aabb".replace('a','c') 🔡 .rfind(sub[, start, end]) Find last occurrence "hello".rfind('l') 🔡 .rindex(sub[, start, end]) Find last occurrence, raise if miss "hello".rindex('l') 🔡 .rjust(width[, fillchar]) Right justify string "cat".rjust(5, '*') 🔡 .rpartition(sep) Split at last sep "a,b,c".rpartition(',') 🔡 .rsplit(sep, maxsplit) Split from right "a,b,c".rsplit(',',1) 🔡 .rstrip(chars) Strip right chars " abc ".rstrip() 🔡 .split(sep, maxsplit) Split string "a,b,c".split(',') 🔡 .splitlines(keepends) Split lines "a\nb\n".splitlines() 🔡 .startswith(prefix[, start, end]) Check prefix "abc".startswith('a') 🔡 .strip(chars) Strip chars on both ends " abc ".strip() 🔡 .swapcase() Swap case "aBc".swapcase() 🔡 .title() Title case "a bc".title() 🔡 .translate(table) Translate using mapping "abc".translate(str.maketrans('a','b')) 🔡 .upper() Convert to uppercase "abc".upper() 🔡 .zfill(width) Zero fill string "42".zfill(5) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🧱 List Methods (list) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🧱 .append(x) Add element to end lst.append(5) 🧱 .clear() Remove all elements lst.clear() 🧱 .copy() Return shallow copy lst.copy() 🧱 .count(x) Count occurrences lst.count(3) 🧱 .extend(iterable) Extend list with iterable lst.extend([4,5]) 🧱 .index(x[, start, end]) Get index of element lst.index(3) 🧱 .insert(i, x) Insert element at position lst.insert(0, 10) 🧱 .pop([i]) Remove and return element lst.pop() 🧱 .remove(x) Remove first occurrence lst.remove(3) 🧱 .reverse() Reverse list in-place lst.reverse() 🧱 .sort(key=None, reverse=False) Sort list lst.sort() ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🌍 Dict Methods (dict) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🌍 .clear() Remove all items d.clear() 🌍 .copy() Return shallow copy d.copy() 🌍 .fromkeys(iterable, value=None) Create dict from keys dict.fromkeys(['a','b'], 0) 🌍 .get(key[, default]) Return value by key, default None d.get('key', 0) 🌍 .items() Return view of key-value pairs d.items() 🌍 .keys() Return view of keys d.keys() 🌍 .pop(key[, default]) Remove item by key d.pop('key', None) 🌍 .popitem() Remove and return item d.popitem() 🌍 .setdefault(key, default) Get or set value if key missing d.setdefault('key', 0) 🌍 .update([other]) Update dict with another d.update({'a':1}) 🌍 .values() Return view of values d.values() ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔒 Set Methods (set & frozenset) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔒 .add(x) Add element s.add(5) 🔒 .clear() Remove all elements s.clear() 🔒 .copy() Return shallow copy s.copy() 🔒 .difference(other) Return set difference s.difference(t) 🔒 .difference_update(other) Remove elements in other s.difference_update(t) 🔒 .discard(x) Remove element if present s.discard(3) 🔒 .intersection(other) Return set intersection s.intersection(t) 🔒 .intersection_update(other) Keep only elements in other s.intersection_update(t) 🔒 .isdisjoint(other) Check if sets have no common elements s.isdisjoint(t) 🔒 .issubset(other) Check if subset s.issubset(t) 🔒 .issuperset(other) Check if superset s.issuperset(t) 🔒 .pop() Remove and return an element s.pop() 🔒 .remove(x) Remove element, raise if missing s.remove(3) 🔒 .symmetric_difference(other) Return elements in either set, not both s.symmetric_difference(t) 🔒 .symmetric_difference_update(other) Update with symmetric difference s.symmetric_difference_update(t) 🔒 .union(other) Return union set s.union(t) 🔒 .update(other) Update set with elements from other s.update(t) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📑 Tuple (tuple) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📑 .count(x) Count occurrences tpl.count(2) 📑 .index(x[, start, end]) Return index of element tpl.index(3) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 💠 Bytes & Bytearray Methods ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 💠 .capitalize() Capitalize first char b.capitalize() 💠 .center(width[, fillchar]) Center the bytes object b.center(5, b'*') 💠 .count(sub[, start, end]) Count occurrences b.count(b'a') 💠 .decode(encoding, errors) Decode bytes to str b.decode('utf-8') 💠 .endswith(suffix[, start, end]) Check suffix b.endswith(b'a') 💠 .find(sub[, start, end]) Find substring b.find(b'a') 💠 .index(sub[, start, end]) Find substring, raise if missing b.index(b'a') 💠 .isalnum() Check if alphanumeric bytes b.isalnum() 💠 .isalpha() Check if alphabetic bytes b.isalpha() 💠 .isdigit() Check if digit bytes b.isdigit() 💠 .islower() Check if lowercase bytes b.islower() 💠 .isspace() Check if whitespace bytes b.isspace() 💠 .istitle() Check if titlecase bytes b.istitle() 💠 .isupper() Check if uppercase bytes b.isupper() 💠 .join(iterable) Join bytes iterable b"".join([b'a', b'b']) 💠 .ljust(width[, fillchar]) Left-justify bytes b.ljust(5, b'*') 💠 .lower() Convert bytes to lowercase b.lower() 💠 .lstrip([chars]) Left strip bytes b.lstrip() 💠 .partition(sep) Partition bytes b.partition(b',') 💠 .replace(old, new[, count]) Replace bytes b.replace(b'a', b'b') 💠 .rfind(sub[, start, end]) Find last occurrence b.rfind(b'a') 💠 .rindex(sub[, start, end]) Find last occurrence, raise if missing b.rindex(b'a') 💠 .rjust(width[, fillchar]) Right justify bytes b.rjust(5, b'*') 💠 .rpartition(sep) Partition bytes from right b.rpartition(b',') 💠 .rsplit(sep, maxsplit) Split bytes b.rsplit(b',', 1) 💠 .rstrip([chars]) Right strip bytes b.rstrip() 💠 .split(sep, maxsplit) Split bytes b.split(b',') 💠 .splitlines(keepends) Split lines b.splitlines() 💠 .startswith(prefix[, start, end]) Check prefix b.startswith(b'a') 💠 .strip([chars]) Strip bytes b.strip() 💠 .swapcase() Swap case bytes b.swapcase() 💠 .title() Title case bytes b.title() 💠 .translate(table) Translate bytes b.translate(b.maketrans(b'a', b'b')) 💠 .upper() Convert bytes to uppercase b.upper() 💠 .zfill(width) Zero-fill bytes b.zfill(5) ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 📦 Azure CLI & Azure PowerShell Commands for Top 10 Azure Services ================================================================================================================================================================================================================================================================ 1️⃣ Azure Resource Manager (ARM) Deployments & Resource Groups ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🛠️ az group create New-AzResourceGroup Create Resource Group az group create --name myRG --location eastus New-AzResourceGroup -Name myRG -Location eastus 🗑️ az group delete Remove-AzResourceGroup Delete Resource Group az group delete --name myRG Remove-AzResourceGroup -Name myRG 📋 az deployment group create New-AzResourceGroupDeployment Deploy ARM/Bicep template az deployment group create --resource-group myRG --template-file template.json New-AzResourceGroupDeployment -ResourceGroupName myRG -TemplateFile template.json 👀 az deployment group what-if Preview deployment changes az deployment group what-if --resource-group myRG --template-file template.json 📝 az deployment operation group list List deployment operations az deployment operation group list --resource-group myRG --name deployment1 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 2️⃣ Azure Virtual Machines (VMs) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🛠️ az vm create New-AzVM Create VM az vm create -g myRG -n myVM --image UbuntuLTS New-AzVM -ResourceGroupName myRG -Name myVM -Image UbuntuLTS -Credential (Get-Credential) 📋 az vm list Get-AzVM List VMs az vm list -g myRG Get-AzVM -ResourceGroupName myRG ▶️ az vm start Start-AzVM Start VM az vm start --resource-group myRG --name myVM Start-AzVM -ResourceGroupName myRG -Name myVM ⏸️ az vm stop Stop-AzVM Stop VM az vm stop --resource-group myRG --name myVM Stop-AzVM -ResourceGroupName myRG -Name myVM 🔄 az vm restart Restart-AzVM Restart VM az vm restart --resource-group myRG --name myVM Restart-AzVM -ResourceGroupName myRG -Name myVM ❌ az vm delete Remove-AzVM Delete VM az vm delete --resource-group myRG --name myVM --yes Remove-AzVM -ResourceGroupName myRG -Name myVM -Force ⚙️ az vm extension set Set-AzVMExtension Manage VM Extensions az vm extension set --resource-group myRG --vm-name myVM --name CustomScript --publisher Microsoft.Azure.Extensions --settings '{"fileUris":["https://..."]}' Set-AzVMExtension -ResourceGroupName myRG -VMName myVM -Name CustomScript -Publisher Microsoft.Azure.Extensions -TypeHandlerVersion 2.0 -SettingString '{"fileUris":["https://..."]}' ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3️⃣ Azure Storage Accounts & Blob Storage ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🛠️ az storage account create New-AzStorageAccount Create Storage Account az storage account create --name mystorage --resource-group myRG --location eastus --sku Standard_LRS New-AzStorageAccount -ResourceGroupName myRG -Name mystorage -Location eastus -SkuName Standard_LRS 🗑️ az storage account delete Remove-AzStorageAccount Delete Storage Account az storage account delete --name mystorage --resource-group myRG --yes Remove-AzStorageAccount -ResourceGroupName myRG -Name mystorage -Force 🆕 az storage container create New-AzStorageContainer Create Blob Container az storage container create --account-name mystorage --name mycontainer New-AzStorageContainer -Name mycontainer -Context $ctx ⬆️ az storage blob upload Set-AzStorageBlobContent Upload Blob az storage blob upload --account-name mystorage --container-name mycontainer --file file.txt --name blob1 Set-AzStorageBlobContent -File file.txt -Container mycontainer -Blob blob1 ⬇️ az storage blob download Get-AzStorageBlobContent Download Blob az storage blob download --account-name mystorage --container-name mycontainer --name blob1 --file download.txt Get-AzStorageBlobContent -Container mycontainer -Blob blob1 -Destination download.txt ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 4️⃣ Azure Networking (VNets, NSGs, Load Balancers) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az network vnet create New-AzVirtualNetwork Create VNet az network vnet create -g myRG -n myVnet --address-prefix 10.0.0.0/16 New-AzVirtualNetwork -ResourceGroupName myRG -Name myVnet -AddressPrefix 10.0.0.0/16 🆕 az network nsg create New-AzNetworkSecurityGroup Create NSG az network nsg create -g myRG -n myNsg New-AzNetworkSecurityGroup -ResourceGroupName myRG -Name myNsg ➕ az network nsg rule create Add-AzNetworkSecurityRuleConfig Add NSG rule az network nsg rule create -g myRG --nsg-name myNsg -n myRule --priority 100 --protocol Tcp --destination-port-range 22 --access Allow Add-AzNetworkSecurityRuleConfig -Name myRule -NetworkSecurityGroup $nsg -Priority 100 -Protocol Tcp -DestinationPortRange 22 -Access Allow 🆕 az network lb create New-AzLoadBalancer Create Load Balancer az network lb create -g myRG -n myLB --sku Basic New-AzLoadBalancer -ResourceGroupName myRG -Name myLB -Sku Basic 🆕 az network public-ip create New-AzPublicIpAddress Create Public IP az network public-ip create -g myRG -n myPublicIp New-AzPublicIpAddress -ResourceGroupName myRG -Name myPublicIp ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 5️⃣ Azure App Services & Web Apps ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az webapp create New-AzWebApp Create Web App az webapp create --resource-group myRG --plan myPlan --name myWebApp --runtime "DOTNETCORE|3.1" New-AzWebApp -ResourceGroupName myRG -Name myWebApp -Location eastus -AppServicePlan myPlan ⚙️ az webapp config appsettings set Set-AzWebApp Set Settings az webapp config appsettings set --resource-group myRG --name myWebApp --settings "WEBSITE_NODE_DEFAULT_VERSION=10.14" Set-AzWebApp -ResourceGroupName myRG -Name myWebApp -AppSettings @{"WEBSITE_NODE_DEFAULT_VERSION"="10.14"} 🌐 az webapp browse Browse App az webapp browse --resource-group myRG --name myWebApp — 📝 az webapp log tail Stream Logs az webapp log tail --resource-group myRG --name myWebApp — ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6️⃣ Azure SQL Database ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az sql server create New-AzSqlServer Create SQL Server az sql server create --name myserver --resource-group myRG --location eastus --admin-user adminuser --admin-password 'Password!' New-AzSqlServer -ResourceGroupName myRG -ServerName myserver -Location eastus -SqlAdministratorCredentials (Get-Credential) 🆕 az sql db create New-AzSqlDatabase Create SQL Database az sql db create --resource-group myRG --server myserver --name mydb --service-objective S0 New-AzSqlDatabase -ResourceGroupName myRG -ServerName myserver -DatabaseName mydb -RequestedServiceObjectiveName S0 🗑️ az sql db delete Remove-AzSqlDatabase Delete SQL Database az sql db delete --resource-group myRG --server myserver --name mydb --yes Remove-AzSqlDatabase -ResourceGroupName myRG -ServerName myserver -DatabaseName mydb ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 7️⃣ Azure Kubernetes Service (AKS) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az aks create New-AzAks Create AKS Cluster az aks create --resource-group myRG --name myAKS --node-count 3 --enable-addons monitoring --generate-ssh-keys New-AzAks -ResourceGroupName myRG -Name myAKS -NodeCount 3 -EnableAddOn Monitoring 📥 az aks get-credentials Get-AzAksCredential Get AKS Credentials az aks get-credentials --resource-group myRG --name myAKS Get-AzAksCredential -ResourceGroupName myRG -Name myAKS ⚙️ az aks scale Set-AzAks Scale AKS Cluster az aks scale --resource-group myRG --name myAKS --node-count 5 Set-AzAks -ResourceGroupName myRG -Name myAKS -NodeCount 5 🗑️ az aks delete Remove-AzAks Delete AKS Cluster az aks delete --resource-group myRG --name myAKS --yes Remove-AzAks -ResourceGroupName myRG -Name myAKS -Force ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 8️⃣ Azure Key Vault ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az keyvault create New-AzKeyVault Create Key Vault az keyvault create --name myVault --resource-group myRG --location eastus New-AzKeyVault -VaultName myVault -ResourceGroupName myRG -Location eastus 🔐 az keyvault secret set Set-AzKeyVaultSecret Set Key Vault Secret az keyvault secret set --vault-name myVault --name mySecret --value "myValue" Set-AzKeyVaultSecret -VaultName myVault -Name mySecret -SecretValue (ConvertTo-SecureString "myValue" -AsPlainText -Force) 🔍 az keyvault secret show Get-AzKeyVaultSecret Get Key Vault Secret az keyvault secret show --vault-name myVault --name mySecret Get-AzKeyVaultSecret -VaultName myVault -Name mySecret 🗑️ az keyvault secret delete Remove-AzKeyVaultSecret Delete Key Vault Secret az keyvault secret delete --vault-name myVault --name mySecret Remove-AzKeyVaultSecret -VaultName myVault -Name mySecret ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 9️⃣ Azure Monitor ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📊 az monitor metrics list Get-AzMetric List Resource Metrics az monitor metrics list --resource MyVm --metric CPUPercentage Get-AzMetric -ResourceId /subscriptions/.../resourceGroups/myRG/providers/Microsoft.Compute/virtualMachines/MyVm -MetricName "Percentage CPU" ⚠️ az monitor metrics alert create New-AzMetricAlertRuleV2 Create Metric Alert az monitor metrics alert create --name myAlert --resource-group myRG --scopes /subscriptions/... --condition "avg Percentage CPU > 80" New-AzMetricAlertRuleV2 -Name myAlert -ResourceGroupName myRG -TargetResourceId /subscriptions/... -Condition (New-AzMetricAlertRuleV2Criteria -MetricName "Percentage CPU" -Operator GreaterThan -Threshold 80) 🔔 az monitor activity-log alert create New-AzActivityLogAlert Create Activity Log Alert az monitor activity-log alert create --name logAlert --resource-group myRG --scope /subscriptions/... --condition "category = Write" New-AzActivityLogAlert -Name logAlert -ResourceGroupName myRG -Scope "/subscriptions/..." -Condition "category = Write" ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 🔟 Azure Active Directory / Entra ID ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az ad user create New-AzureADUser Create Azure AD User az ad user create --display-name "John Doe" --user-principal-name johndoe@contoso.com --password "Password!" New-AzureADUser -DisplayName "John Doe" -UserPrincipalName johndoe@contoso.com -AccountEnabled $true -PasswordProfile $passwordProfile 🆕 az ad group create New-AzureADGroup Create Azure AD Group az ad group create --display-name "My Group" --mail-nickname "mygroup" New-AzureADGroup -DisplayName "My Group" -MailEnabled $false -SecurityEnabled $true -MailNickname "mygroup" 🔑 az ad sp create-for-rbac New-AzADServicePrincipal Create Service Principal az ad sp create-for-rbac --name "appSP" --role contributor --scopes /subscriptions/subID New-AzADServicePrincipal -DisplayName "appSP" -Role Contributor 🆕 az ad app create New-AzureADApplication Create App Registration az ad app create --display-name "My App" New-AzureADApplication -DisplayName "My App" ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 1️⃣ AKS Cluster Management ================================================================================================================================================================================================================================================================ 🆕 az aks create New-AzAksCluster Create AKS cluster az aks create --resource-group myRG --name myAKS --node-count 3 --enable-addons monitoring --generate-ssh-keys New-AzAksCluster -ResourceGroupName myRG -Name myAKS -NodeCount 3 -EnableAddOn Monitoring 📋 az aks get-credentials Get-AzAksCredential Download kubeconfig credentials az aks get-credentials --resource-group myRG --name myAKS Get-AzAksCredential -ResourceGroupName myRG -Name myAKS ⚙️ az aks scale Set-AzAks Scale node count az aks scale --resource-group myRG --name myAKS --node-count 5 Set-AzAks -ResourceGroupName myRG -Name myAKS -NodeCount 5 ⬆️ az aks upgrade Update-AzAksCluster Upgrade AKS cluster version az aks upgrade --resource-group myRG --name myAKS --kubernetes-version 1.22.6 Update-AzAksCluster -ResourceGroupName myRG -Name myAKS -KubernetesVersion 1.22.6 🗑️ az aks delete Remove-AzAksCluster Delete AKS cluster az aks delete --resource-group myRG --name myAKS --yes Remove-AzAksCluster -ResourceGroupName myRG -Name myAKS ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 2️⃣ AKS Node Pools & Addons ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az aks nodepool create New-AzAksNodePool Add new node pool az aks nodepool create --resource-group myRG --cluster-name myAKS --name nodepool1 --node-count 3 --node-vm-size Standard_DS2_v2 New-AzAksNodePool -ResourceGroupName myRG -ClusterName myAKS -Name nodepool1 -NodeCount 3 -VmSize Standard_DS2_v2 📋 az aks nodepool list Get-AzAksNodePool List node pools az aks nodepool list --resource-group myRG --cluster-name myAKS Get-AzAksNodePool -ResourceGroupName myRG -ClusterName myAKS ⚙️ az aks nodepool scale Set-AzAksNodePool Scale node pool az aks nodepool scale --resource-group myRG --cluster-name myAKS --name nodepool1 --node-count 5 Set-AzAksNodePool -ResourceGroupName myRG -ClusterName myAKS -Name nodepool1 -NodeCount 5 ⬆️ az aks nodepool upgrade Update-AzAksNodePool Upgrade node pool Kubernetes version az aks nodepool upgrade --resource-group myRG --cluster-name myAKS --name nodepool1 --kubernetes-version 1.22.6 Update-AzAksNodePool -ResourceGroupName myRG -ClusterName myAKS -Name nodepool1 -KubernetesVersion 1.22.6 🧩 az aks enable-addons Enable-AzAksAddOn Enable AKS addons (like monitoring, policy) az aks enable-addons --addons monitoring --resource-group myRG --name myAKS Enable-AzAksAddOn -ClusterName myAKS -ResourceGroupName myRG -AddOnName monitoring ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3️⃣ AKS RBAC, Identity, & Maintenance ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔐 az aks update-credentials Set-AzAksClusterCredential Reset Service Principal or credentials for AKS cluster az aks update-credentials --resource-group myRG --name myAKS --reset-service-principal Set-AzAksClusterCredential -ResourceGroupName myRG -Name myAKS -ResetServicePrincipal 🛡️ az aks enable-aad Enable Azure AD integration for AKS cluster Retrieve docs, example below az aks update --resource-group myRG --name myAKS --enable-aad Set-AzAksCluster -ResourceGroupName myRG -Name myAKS -EnableAzureActiveDirectory ♻️ az aks maintenanceconfiguration New-AzAksMaintenanceConfiguration Create or update AKS maintenance window configurations az aks maintenanceconfiguration create --resource-group myRG --cluster-name myAKS --name maintenance -w "Sunday 5pm" New-AzAksMaintenanceConfiguration -ResourceGroupName myRG -ClusterName myAKS -Name maintenance -Window "Sunday 5pm" 🛑 az aks stop Stop an AKS cluster (scale down control plane) az aks stop --name myAKS --resource-group myRG No direct cmdlet; use Azure CLI ▶️ az aks start Start a stopped AKS cluster az aks start --name myAKS --resource-group myRG No direct cmdlet; use Azure CLI ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 1️⃣ Azure Virtual Machines (VMs) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🛠️ az vm create Create a VM az vm create -g myRG -n myVM --image UbuntuLTS ▶️ az vm start Start a VM az vm start --resource-group myRG --name myVM ⏸️ az vm stop Stop a VM az vm stop --resource-group myRG --name myVM 🔄 az vm restart Restart a VM az vm restart --resource-group myRG --name myVM ❌ az vm delete Delete a VM az vm delete --resource-group myRG --name myVM --yes 🛠️ New-AzVM Create VM (PowerShell) New-AzVM -ResourceGroupName myRG -Name myVM -Image UbuntuLTS -Credential (Get-Credential) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 2️⃣ Azure Kubernetes Service (AKS) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az aks create Create AKS cluster az aks create --resource-group myRG --name myAKS --node-count 3 --enable-addons monitoring --generate-ssh-keys 📋 az aks get-credentials Download kubeconfig az aks get-credentials --resource-group myRG --name myAKS ⚙️ az aks scale Scale AKS nodes az aks scale --resource-group myRG --name myAKS --node-count 5 🗑️ az aks delete Delete AKS cluster az aks delete --resource-group myRG --name myAKS --yes 🆕 New-AzAksCluster Create AKS cluster New-AzAksCluster -ResourceGroupName myRG -Name myAKS -NodeCount 3 -EnableAddOn Monitoring ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3️⃣ Azure Blob Storage ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🛠️ az storage account create Create Storage Account az storage account create --name mystorage --resource-group myRG --location eastus --sku Standard_LRS 🆕 az storage container create Create blob container az storage container create --account-name mystorage --name mycontainer ⬆️ az storage blob upload Upload files as blobs az storage blob upload --account-name mystorage --container-name mycontainer --file file.txt --name blob1 ⬇️ az storage blob download Download blobs from container az storage blob download --account-name mystorage --container-name mycontainer --name blob1 --file download.txt ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 4️⃣ Azure App Services ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az webapp create Create Web App az webapp create --resource-group myRG --plan myPlan --name myWebApp --runtime "DOTNETCORE|3.1" ⚙️ az webapp config appsettings set Set app settings az webapp config appsettings set --resource-group myRG --name myWebApp --settings "WEBSITE_NODE_DEFAULT_VERSION=10.14" 🌐 az webapp browse Open web app in browser az webapp browse --resource-group myRG --name myWebApp ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 5️⃣ Azure SQL Database ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az sql server create Create SQL server az sql server create --name myserver --resource-group myRG --location eastus --admin-user adminuser --admin-password 'Password!' 🆕 az sql db create Create database az sql db create --resource-group myRG --server myserver --name mydb --service-objective S0 🗑️ az sql db delete Delete database az sql db delete --resource-group myRG --server myserver --name mydb --yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6️⃣ Azure Key Vault ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az keyvault create Create Key Vault az keyvault create --name myVault --resource-group myRG --location eastus 🔐 az keyvault secret set Set secret az keyvault secret set --vault-name myVault --name mySecret --value "MySecretValue" 🔍 az keyvault secret show Show secret az keyvault secret show --vault-name myVault --name mySecret 🗑️ az keyvault secret delete Delete secret az keyvault secret delete --vault-name myVault --name mySecret ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 7️⃣ Azure DevOps Pipelines (GitHub Actions examples) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ⬆️ GitHub Actions checkout Check out repo source code uses: actions/checkout@v4 🧰 GitHub Actions login Login to Azure using OIDC uses: azure/login@v2 with client-id, tenant-id, subscription-id 🚀 GitHub Actions deploy Deploy Bicep template in Azure run: az deployment group create --resource-group myRG --template-file infra.bicep --parameters @params.json 🔄 GitHub Actions workflow Trigger workflow on push or pull request on: [push, pull_request] 🎯 GitHub Actions environment Define environment and approvals environment: production with reviewers ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 8️⃣ Azure Functions ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az functionapp create Create function app az functionapp create --resource-group myRG --consumption-plan-location eastus --runtime python --functions-version 4 --name myfuncapp ⚙️ az functionapp config set Set app configuration az functionapp config appsettings set --resource-group myRG --name myfuncapp --settings "AzureWebJobsStorage=..." 📊 az functionapp log tail Stream logs az functionapp log tail --name myfuncapp --resource-group myRG ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 9️⃣ Azure Monitor ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📊 az monitor metrics list List metrics for resource az monitor metrics list --resource /subscriptions/.../resourceGroups/myRG/providers/Microsoft.Compute/virtualMachines/myVM --metric CPUPercentage ⚠️ az monitor metrics alert create Create metric alert az monitor metrics alert create --name cpuAlert --resource-group myRG --scopes /subscriptions/... --condition "avg Percentage CPU > 80" ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔟 Azure Active Directory / Entra ID ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az ad user create Create user az ad user create --display-name "John Doe" --user-principal-name johndoe@contoso.com --password "Password!" 🆕 az ad group create Create group az ad group create --display-name "My Group" --mail-nickname "mygroup" 🔑 az ad sp create-for-rbac Create service principal az ad sp create-for-rbac --name "appSP" --role contributor --scopes /subscriptions/subID ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣1️⃣ Azure Cosmos DB ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az cosmosdb create Create Cosmos DB Account az cosmosdb create --name mycosmosdb --resource-group myRG --kind MongoDB --locations regionName=eastus 📋 az cosmosdb list List Cosmos DB accounts az cosmosdb list --resource-group myRG ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣2️⃣ Azure Logic Apps ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az logic workflow create Create Logic App workflow az logic workflow create --resource-group myRG --name myworkflow --definition @definition.json 🧰 az logic workflow run Start Logic App workflow az logic workflow run --resource-group myRG --name myworkflow ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣3️⃣ Azure SQL Managed Instance ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az sql mi create Create SQL Managed Instance az sql mi create --name myinstance --resource-group myRG --location eastus --admin-user admin --admin-password 'password' ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣4️⃣ Azure Synapse Analytics ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az synapse workspace create Create Synapse workspace az synapse workspace create --name mysynapse --resource-group myRG --location eastus --sql-admin-login-user sqladmin --sql-admin-login-password 'Password!' ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣5️⃣ Azure Data Factory ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az datafactory factory create Create Data Factory az datafactory factory create --resource-group myRG --name myfactory --location eastus ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣6️⃣ Azure Event Hubs ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az eventhubs namespace create Create Event Hub Namespace az eventhubs namespace create --name mynamespace --resource-group myRG --location eastus ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣7️⃣ Azure Service Bus ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az servicebus namespace create Create Service Bus Namespace az servicebus namespace create --name mynamespace --resource-group myRG --location eastus ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣8️⃣ Azure API Management ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az apim create Create API Management service az apim create --name myapim --resource-group myRG --location eastus ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣9️⃣ Azure Backup ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az backup vault create Create Recovery Services vault az backup vault create --name mybackupvault --resource-group myRG --location eastus ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 2️⃣0️⃣ Azure Container Registry (ACR) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 az acr create Create Container Registry az acr create --resource-group myRG --name myacr --sku Basic --admin-enabled true ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 Command 📋 Description 💻 Example ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- az acr create Create Container Registry az acr create --resource-group myRG --name myacr --sku Basic --admin-enabled true az acr list List all container registries az acr list --output table az acr login Login to registry with Docker CLI az acr login --name myacr az acr build Build image using ACR task az acr build --registry myacr --image myimage:latest . az acr delete Delete a container registry az acr delete --name myacr --resource-group myRG --yes az acr import Import image from another registry az acr import --name myacr --source docker.io/library/nginx:latest --image nginx:latest az acr repository list List repositories in ACR az acr repository list --name myacr az acr repository delete Delete a repository or image az acr repository delete --name myacr --repository myrepo --yes az acr repository show Show repository or image properties az acr repository show --name myacr --repository myrepo az acr repository show-tags List tags in repository az acr repository show-tags --name myacr --repository myrepo az acr repository untag Remove a tag from an image az acr repository untag --name myacr --repository myrepo --tag v1 az acr check-health Check registry health az acr check-health --name myacr az acr update Update registry properties az acr update --name myacr --sku Premium az acr credential show Show registry login credentials az acr credential show --name myacr az acr credential renew Regenerate registry credentials az acr credential renew --name myacr --password-name password az acr webhook list List webhooks configured for registry az acr webhook list --registry myacr az acr webhook create Create a webhook for registry az acr webhook create --name myhook --registry myacr --uri http://mywebhook.com --actions push az acr webhook delete Delete a webhook az acr webhook delete --name myhook --registry myacr az acr task list List the tasks in a registry az acr task list --registry myacr az acr task run Run a specific task az acr task run --registry myacr --name mytask ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ ⚡ Azure PowerShell Commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔑 Connect-AzAccount Authenticate and connect to Azure Connect-AzAccount 📜 Disconnect-AzAccount Disconnect logged-in Azure session Disconnect-AzAccount 📄 Get-AzSubscription List all subscriptions accessible Get-AzSubscription 📄 Select-AzSubscription Select an active subscription Select-AzSubscription -SubscriptionId "xxxx-xxxx-xxxx" 🏷️ Get-AzResourceGroup List all resource groups Get-AzResourceGroup 🏗️ New-AzResourceGroup Create a new resource group New-AzResourceGroup -Name "myRG" -Location "EastUS" 🗑️ Remove-AzResourceGroup Delete a specified resource group Remove-AzResourceGroup -Name "myRG" -Force 🚀 New-AzVM Create a new virtual machine New-AzVM -ResourceGroupName "myRG" -Name "myVM" -Image UbuntuLTS -Location EastUS 📋 Get-AzVM List virtual machines in a resource group Get-AzVM -ResourceGroupName "myRG" ▶️ Start-AzVM Start a virtual machine Start-AzVM -ResourceGroupName "myRG" -Name "myVM" ⏸️ Stop-AzVM Stop a virtual machine Stop-AzVM -ResourceGroupName "myRG" -Name "myVM" ♻️ Restart-AzVM Restart a virtual machine Restart-AzVM -ResourceGroupName "myRG" -Name "myVM" 🧰 Get-AzStorageAccount List storage accounts Get-AzStorageAccount -ResourceGroupName "myRG" 🏗️ New-AzStorageAccount Create a new storage account New-AzStorageAccount -ResourceGroupName "myRG" -Name "mystorage" -SkuName Standard_LRS -Location EastUS 🛑 Remove-AzStorageAccount Delete a storage account Remove-AzStorageAccount -ResourceGroupName "myRG" -Name "mystorage" -Force 🔍 Get-AzKeyVault List Key Vaults Get-AzKeyVault -ResourceGroupName "myRG" 🆕 New-AzKeyVault Create a new Key Vault New-AzKeyVault -ResourceGroupName "myRG" -VaultName "myVault" -Location EastUS 🔐 Set-AzKeyVaultSecret Set or update a Key Vault secret Set-AzKeyVaultSecret -VaultName "myVault" -Name "MySecret" -SecretValue (ConvertTo-SecureString "supersecret" -AsPlainText -Force) 🌐 Get-AzNetworkSecurityGroup List NSG Get-AzNetworkSecurityGroup -ResourceGroupName "myRG" 🏗️ New-AzNetworkSecurityGroup Create NSG New-AzNetworkSecurityGroup -ResourceGroupName "myRG" -Name "myNSG" -Location EastUS 🛑 Remove-AzNetworkSecurityGroup Delete a NSG Remove-AzNetworkSecurityGroup -ResourceGroupName "myRG" -Name "myNSG" -Force 🌟 Get-AzRoleAssignment List role assignments Get-AzRoleAssignment -ResourceGroupName "myRG" 🔑 New-AzADServicePrincipal Create an Azure AD Service Principal New-AzADServicePrincipal -DisplayName "myAppSp" 🛠️ New-AzResourceGroupDeployment Deploy resources using ARM template or Bicep file New-AzResourceGroupDeployment -ResourceGroupName "myRG" -TemplateFile ".\template.bicep" -TemplateParameterFile ".\parameters.json" 📦 Get-AzResource Get Azure resources Get-AzResource -ResourceGroupName "myRG" -ResourceType "Microsoft.Compute/virtualMachines" -ResourceName "myVM" 📆 Get-AzActivityLog Fetch Azure activity logs Get-AzActivityLog -ResourceGroupName "myRG" -StartTime (Get-Date).AddDays(-7) 🧰 Invoke-AzRestMethod Invoke a REST API call into Azure Invoke-AzRestMethod -Method GET -Path "/subscriptions/{sub}/resourceGroups/{rg}" ⚙️ Get-AzAutomationRunbook List Automation Runbooks Get-AzAutomationRunbook -ResourceGroupName "myRG" -AutomationAccountName "myAccount" 🏅 Start-AzAutomationRunbook Start an Automation Runbook Start-AzAutomationRunbook -ResourceGroupName "myRG" -AutomationAccountName "myAccount" -Name "MyRunbook" 🎛️ Get-AzFunctionApp List Function Apps Get-AzFunctionApp -ResourceGroupName "myRG" 🏗️ New-AzFunctionApp Create a new Function App New-AzFunctionApp -ResourceGroupName "myRG" -Name "myFuncApp" -StorageAccountName "mystorage" -Location "eastus" -Runtime DotNet ♻️ Restart-AzFunctionApp Restart Function App Restart-AzFunctionApp -ResourceGroupName "myRG" -Name "myFuncApp" 🔨 Set-AzVmExtension Configure VM extension Set-AzVMExtension -ResourceGroupName "myRG" -VMName "myVM" -Name "CustomScript" -Publisher "Microsoft.Azure.Extensions" -Type "CustomScript" ⇢⇢ ⇢⇢ -TypeHandlerVersion 2.0 -SettingString '{"fileUris":["https://..."]}' -ProtectedSettingString '{"commandToExecute":"..."}' ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ⚡ PowerShell Commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 Get-Command Get all available commands Get-Command 📖 Get-Help Display help information for a command Get-Help Get-Process 📁 Get-ChildItem List files and directories Get-ChildItem C:\Users 📍 Get-Location Show current directory Get-Location 📂 Set-Location Change current directory Set-Location C:\Temp 📃 Get-Content Read content from a file Get-Content .\file.txt 📝 Set-Content Overwrite content or create a file Set-Content .\file.txt "Hello world" 📄 Add-Content Append content to a file Add-Content .\file.txt "Appended text" ✂️ Remove-Item Delete files or folders Remove-Item .\file.txt 📋 Copy-Item Copy files or folders Copy-Item .\file.txt .\copy.txt 🏃‍♂️ Move-Item Move or rename files/folders Move-Item .\copy.txt .\newcopy.txt 📦 New-Item Create new file/folder New-Item -Path .\newfile.txt -ItemType File 🔍 Get-Process List processes Get-Process chrome ⚙️ Start-Process Start a new process Start-Process notepad.exe 🛑 Stop-Process Stop running process Stop-Process -Name notepad ⚙️ Get-Service Get Windows services Get-Service wuauserv 🆕 Start-Service Start a Windows service Start-Service wuauserv 🛑 Stop-Service Stop a Windows service Stop-Service wuauserv 🕵️ Get-EventLog Read event logs Get-EventLog -LogName System -Newest 10 📊 Measure-Object Measure properties (count, sum, average, etc.) Get-ChildItem | Measure-Object 🧩 Select-Object Select specific properties or objects Get-Process | Select-Object -Property ProcessName, Id 🔄 Sort-Object Sort objects Get-Process | Sort-Object CPU -Descending 📜 Format-Table Format output as a table Get-Process | Format-Table -Property Id,ProcessName 📜 Format-List Format output as a list Get-Service | Format-List ✒️ Write-Output Display output on console Write-Output "Hello, PowerShell" 🧹 Clear-Host Clear console screen Clear-Host 🕰️ Get-Date Show current date/time Get-Date 📅 Set-Date Set system date/time Set-Date "August 25, 2025 10:00:00 AM" 👁️ Test-Path Check if file or path exists Test-Path .\file.txt 🧪 Invoke-WebRequest Fetch content from web URL Invoke-WebRequest https://example.com 💾 Export-Csv Export data to CSV file Get-Process | Export-Csv processes.csv 📥 Import-Csv Import data from CSV file Import-Csv processes.csv ⚙️ Get-Member Get properties and methods of an object Get-Process | Get-Member ⌛ Start-Job Run background job Start-Job -ScriptBlock { Get-Process } ⌛ Get-Job List running jobs Get-Job ⌛ Receive-Job Get output from background jobs Receive-Job -Id 1 ⌛ Stop-Job Stop background job Stop-Job -Id 1 💡 ForEach-Object Loop through items Get-Process | ForEach-Object { $_.Id } 🕵️ Where-Object Filter objects Get-Process | Where-Object { $_.CPU -gt 100 } 🗂️ Import-Module Load PowerShell module Import-Module Az 💾 Export-ModuleMember Export functions or variables from module Export-ModuleMember -Function Get-MyCmdlet 🛠️ New-Alias Create a shortcut alias New-Alias ll Get-ChildItem 🔄 Clear-Variable Clear variable and its value Clear-Variable -Name myVar 🧱 Get-Variable Get variables in current environment Get-Variable -Name myVar ♻️ Set-Variable Set or create variable Set-Variable -Name myVar -Value 42 🔍 Get-Content Read content of a file Get-Content .\log.txt 💣 Try/Catch/Finally Exception handling block try { Get-Item nosuchfile } catch { Write-Host "Error" } 📦 Register-ScheduledTask Register a scheduled task Register-ScheduledTask -TaskName "Backup" -Trigger $trigger -Action $action ⚙️ Invoke-Command Run command on remote computers Invoke-Command -ComputerName server1 -ScriptBlock { Get-Process } 🌐 Get-Help Get cmdlet help and examples Get-Help Get-Process ⚙️ Set-ExecutionPolicy Change script execution policy Set-ExecutionPolicy RemoteSigned 🚦 Test-Connection Ping a remote host Test-Connection google.com ================================================================================================================================================================================================================================================================ ⚡ PowerShell Commands + Networking ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 Get-Command Get all available commands Get-Command 📖 Get-Help Display help information for a command Get-Help Get-Process 📁 Get-ChildItem List files and directories Get-ChildItem C:\Users 📍 Get-Location Show current directory Get-Location 📂 Set-Location Change current directory Set-Location C:\Temp 📃 Get-Content Read content from a file Get-Content .\file.txt 📝 Set-Content Overwrite content or create a file Set-Content .\file.txt "Hello world" 📄 Add-Content Append content to a file Add-Content .\file.txt "Appended text" ✂️ Remove-Item Delete files or folders Remove-Item .\file.txt 📋 Copy-Item Copy files or folders Copy-Item .\file.txt .\copy.txt 🏃‍♂️ Move-Item Move or rename files/folders Move-Item .\copy.txt .\newcopy.txt 📦 New-Item Create new file/folder New-Item -Path .\newfile.txt -ItemType File 🔍 Get-Process List running processes Get-Process chrome ⚙️ Start-Process Start a new process Start-Process notepad.exe 🛑 Stop-Process Stop running process Stop-Process -Name notepad ⚙️ Get-Service Get Windows services Get-Service wuauserv 🆕 Start-Service Start Windows service Start-Service wuauserv 🛑 Stop-Service Stop Windows service Stop-Service wuauserv 🕵️ Get-EventLog Read event logs Get-EventLog -LogName System -Newest 10 📊 Measure-Object Measure object properties (count, sum, average) Get-ChildItem | Measure-Object 🧩 Select-Object Select specific properties or objects Get-Process | Select-Object -Property ProcessName,Id 🔄 Sort-Object Sort objects Get-Process | Sort-Object CPU -Descending 📜 Format-Table Format output as a table Get-Process | Format-Table -Property Id,ProcessName 📜 Format-List Format output as a list Get-Service | Format-List ✒️ Write-Output Display output on console Write-Output "Hello, PowerShell" 🧹 Clear-Host Clear the console screen Clear-Host 🕰️ Get-Date Get date and time Get-Date 📅 Set-Date Set system date/time Set-Date "August 25, 2025 10:00:00 AM" 👁️ Test-Path Check if item exists Test-Path .\file.txt 🧪 Invoke-WebRequest Perform HTTP web request Invoke-WebRequest https://example.com 💾 Export-Csv Export objects to CSV Get-Process | Export-Csv processes.csv 📥 Import-Csv Import CSV data into objects Import-Csv processes.csv ⚙️ Get-Member Get members (properties, methods) of objects Get-Process | Get-Member ⌛ Start-Job Start a background job Start-Job -ScriptBlock { Get-Process } ⌛ Get-Job List background jobs Get-Job ⌛ Receive-Job Receive job output Receive-Job -Id 1 ⌛ Stop-Job Stop a background job Stop-Job -Id 1 💡 ForEach-Object Process each item in pipeline Get-Process | ForEach-Object { $_.Id } 🕵️ Where-Object Filter objects Get-Process | Where-Object { $_.CPU -gt 100 } 🗂️ Import-Module Import PowerShell module Import-Module Az 💾 Export-ModuleMember Export functions or variables from a module Export-ModuleMember -Function Get-MyCmdlet 🛠️ New-Alias Create alias New-Alias ll Get-ChildItem 🔄 Clear-Variable Clear variable value Clear-Variable -Name myVar 🧱 Get-Variable Get variable details Get-Variable -Name myVar ♻️ Set-Variable Set variable value Set-Variable -Name myVar -Value 42 ⚡ Test-Connection Send ICMP echo request (ping) Test-Connection -ComputerName google.com 🕵️ Test-NetConnection Extended network diagnostics Test-NetConnection -ComputerName google.com -Port 443 🔍 Resolve-DnsName Perform DNS query Resolve-DnsName -Name powershell.com -Type A 🌐 Get-NetIPAddress Display IP address configuration Get-NetIPAddress 🌐 Get-NetIPInterface Get IP interface details Get-NetIPInterface 🌐 Get-NetAdapter Get network adapters and their status Get-NetAdapter 🌐 Restart-NetAdapter Restart network adapter Restart-NetAdapter -Name "Ethernet" 🌐 Enable-NetAdapter Enable network adapter Enable-NetAdapter -Name "Wi-Fi" 🌐 Disable-NetAdapter Disable network adapter Disable-NetAdapter -Name "Wi-Fi" 🌐 Get-NetRoute Display routing table Get-NetRoute 🌐 New-NetRoute Add new route New-NetRoute –DestinationPrefix "10.0.0.0/24" –InterfaceAlias "Ethernet" –NextHop "192.168.1.1" 🌐 Remove-NetRoute Remove specific route Remove-NetRoute –DestinationPrefix "10.0.0.0/24" –Confirm:$false 🌐 Get-NetTCPConnection Display active TCP connections Get-NetTCPConnection -State Established 🌐 Get-NetUDPEndpoint Display active UDP endpoints Get-NetUDPEndpoint 🌐 Get-DnsClientCache View DNS client cache Get-DnsClientCache 🌐 Clear-DnsClientCache Clear DNS cache Clear-DnsClientCache 🌐 Get-DnsClientServerAddress Get DNS server IP addresses Get-DnsClientServerAddress 🌐 Set-DnsClientServerAddress Set DNS server IP addresses Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses ("8.8.8.8","8.8.4.4") 🌐 Register-DnsClient Register DNS client Register-DnsClient -InterfaceAlias "Ethernet" 🌐 Set-DnsClientGlobalSetting Set DNS client settings Set-DnsClientGlobalSetting -UseSuffixWhenRegistering $true 🧰 Invoke-Command Execute commands on local or remote computers Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process } ⛵ Enter-PSSession Start interactive remote PowerShell session Enter-PSSession -ComputerName Server01 🏃‍♂️ Exit-PSSession Exit remote PowerShell session Exit-PSSession ⚙️ Get-WmiObject Retrieve WMI objects Get-WmiObject -Class Win32_Processor ================================================================================================================================================================================================================================================================ 🪓 Active Directory PowerShell Commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔎 Get-ADDomain Get Active Directory domain details Get-ADDomain 📋 Get-ADDomainController List domain controllers and their properties Get-ADDomainController -Filter * 🔐 Get-ADDefaultDomainPasswordPolicy View domain default password policy Get-ADDefaultDomainPasswordPolicy 🔎 Get-ADFineGrainedPasswordPolicy List fine-grained password policies Get-ADFineGrainedPasswordPolicy -Filter * 👥 Get-ADUser Get user or users from Active Directory Get-ADUser -Identity jsmith 👥 Get-ADUser -Filter Get users filtered by criteria Get-ADUser -Filter {Name -like "*Smith*"} 👥 Get-ADUser -Properties Retrieve user properties Get-ADUser -Identity jsmith -Properties mail,department 📦 New-ADUser Create a new Active Directory user New-ADUser -Name "Jane Doe" -SamAccountName jdoe -AccountPassword (Read-Host -AsSecureString "Password") -Enabled $true 🛠️ Set-ADUser Modify properties of an AD user Set-ADUser -Identity jdoe -Department "IT" 👥 Remove-ADUser Delete an Active Directory user Remove-ADUser -Identity jdoe 🔑 Unlock-ADAccount Unlock a locked user account Unlock-ADAccount -Identity jsmith 🛑 Disable-ADAccount Disable an AD user account Disable-ADAccount -Identity jsmith ✅ Enable-ADAccount Enable an AD user account Enable-ADAccount -Identity jsmith 🕵️ Search-ADAccount Search for accounts with specific criteria Search-ADAccount -AccountDisabled 🔒 Set-ADAccountPassword Reset user password Set-ADAccountPassword -Identity jdoe -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "P@ssw0rd!" -Force) 🔐 Set-ADUser -ChangePasswordAtLogon Set user to change password at next logon Set-ADUser -Identity jdoe -ChangePasswordAtLogon $true 🗂️ Get-ADGroup Get Active Directory group Get-ADGroup -Identity "Domain Users" 🧑‍🤝‍🧑 Add-ADGroupMember Add member(s) to an AD group Add-ADGroupMember -Identity "Domain Admins" -Members jdoe ➖ Remove-ADGroupMember Remove member(s) from group Remove-ADGroupMember -Identity "Domain Admins" -Members jdoe 🏗️ New-ADGroup Create a new AD group New-ADGroup -Name "HR Group" -GroupScope Global -GroupCategory Security -Path "OU=Groups,DC=domain,DC=com" 🚪 Get-ADOrganizationalUnit List organizational units Get-ADOrganizationalUnit -Filter * 🏗️ New-ADOrganizationalUnit Create an OU New-ADOrganizationalUnit -Name "HR" -Path "DC=domain,DC=com" 🧭 Move-ADObject Move AD object (user, group, OU, etc) Move-ADObject -Identity "CN=John Smith,OU=Users,DC=domain,DC=com" -TargetPath "OU=HR,DC=domain,DC=com" 🏢 Get-ADComputer Get computer accounts Get-ADComputer -Filter * 🏗️ New-ADComputer Create computer object New-ADComputer -Name "COMP01" -Path "OU=Computers,DC=domain,DC=com" 🛑 Remove-ADComputer Delete a computer account Remove-ADComputer -Identity "COMP01" 🔍 Get-ADReplicationFailure Check for replication failures Get-ADReplicationFailure -Scope Site -Target "Default-First-Site-Name" 🔍 Get-ADDomainControllerPasswordReplicationPolicy Get password replication policy for DC Get-ADDomainControllerPasswordReplicationPolicy -Identity "DC01" 📅 Get-ADUserPasswordExpirationDate Get password expiration date for users Get-ADUser -Identity jsmith -Properties "msDS-UserPasswordExpiryTimeComputed" Select-Object Name,@{Name="PasswordExpiry"; ⇢⇢ ⇢⇢ Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} 🔐 Get-ADServiceAccount Get managed service accounts Get-ADServiceAccount -Filter * ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 🐳 Docker & ☸️ kubectl Commands ================================================================================================================================================================================================================================================================ 🐳 Docker Commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🐳 docker run Run container from image docker run -d -p 80:80 nginx 📦 docker build Build image from Dockerfile docker build -t myapp:latest . 📥 docker pull Pull image from registry docker pull ubuntu:20.04 📤 docker push Push image to registry docker push myrepo/myapp:latest 🚀 docker start Start stopped container docker start my_container 🛑 docker stop Stop running container docker stop my_container ❌ docker rm Remove container docker rm my_container ❌ docker rmi Remove image docker rmi myapp:latest 📋 docker ps List running containers docker ps 📋 docker ps -a List all containers (running & stopped) docker ps -a 📜 docker logs View container logs docker logs my_container ⚙️ docker exec Run command inside container docker exec -it my_container /bin/bash 🔍 docker inspect Show container/image details docker inspect my_container 🔄 docker restart Restart container docker restart my_container 💾 docker commit Commit changes to new image docker commit my_container mynewimage:1.0 🛠️ docker update Update resource constraints docker update --memory 500m my_container 🔗 docker network create Create new Docker network docker network create mynetwork 🔗 docker network ls List Docker networks docker network ls 🐳 docker network connect Connect container to network docker network connect mynetwork my_container 🐳 docker network disconnect Disconnect container from network docker network disconnect mynetwork my_container 🔐 docker login Log in to Docker registry docker login -u username -p password 🔐 docker logout Log out of registry docker logout ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ☸️ kubectl Commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ☸️ kubectl apply Apply configuration file kubectl apply -f deployment.yaml 📜 kubectl create Create resource from file kubectl create -f pod.yaml 📄 kubectl get Get resources kubectl get pods 📄 kubectl get all Get all resource types kubectl get all 🗑️ kubectl delete Delete resources kubectl delete -f deployment.yaml 🔍 kubectl describe Describe resource details kubectl describe pod mypod 📜 kubectl logs Get pod/container logs kubectl logs mypod 🚀 kubectl exec Execute command in container kubectl exec -it mypod -- /bin/bash 💡 kubectl explain Explain resource and field documentation kubectl explain deployment.spec 💾 kubectl rollout Manage rollout of deployment kubectl rollout status deployment/myapp 💾 kubectl rollout restart Restart deployment kubectl rollout restart deployment/myapp 🚦 kubectl scale Scale resources kubectl scale --replicas=3 deployment/myapp 🕵️ kubectl port-forward Forward local port to pod port kubectl port-forward pod/mypod 8080:80 ⚙️ kubectl config Modify kubeconfig kubectl config view 🖥️ kubectl proxy Run a proxy to the Kubernetes API server kubectl proxy ⚙️ kubectl cluster-info Display cluster info kubectl cluster-info 📆 kubectl top Display resource usage kubectl top pod 🧱 kubectl label Add/update labels on resources kubectl label pod mypod version=v1 🧱 kubectl annotate Add/update annotations kubectl annotate pod mypod description="frontend pod" ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 😼 GIT commands 😼 GitHub commands ================================================================================================================================================================================================================================================================ 🔧 git --version Display Git version git --version 🆕 git init Initialize new Git repository git init 📖 git help Show help for a command git help init 📁 git clone Clone a repository git clone https://github.com/example/repo.git 📁 git remote -v List configured remotes git remote -v ⚙️ git config --global user.name Set Git username globally git config --global user.name "UserName" ⚙️ git config --global user.email Set Git email globally git config --global user.email user@example.com 📄 git status Show working tree status git status ➕ git add Add file(s) to staging area git add testfile.txt 📜 git commit -m "" Commit staged changes with message git commit -m "Initial commit" 📜 git commit -am "" Add modified tracked files and commit git commit -am "Update files" 📊 git log Show commit history git log 🔍 git diff Show changes not yet staged git diff 🔍 git diff --cached Show staged changes git diff --cached 🔄 git checkout Switch branch git checkout feature-branch 🆕 git switch Switch branch (newer syntax) git switch main 🌱 git branch List branches git branch ➕ git branch Create new branch git branch feature-1 🗑️ git branch -d Delete a branch git branch -d feature-1 🔄 git merge Merge branch into current git merge feature-1 📥 git pull Fetch and merge changes from remote git pull origin main 📤 git push Push commits to remote git push origin main 💾 git fetch Download objects and refs from remote git fetch origin ♻️ git reset --soft HEAD~1 Move HEAD backwards, keep staged and working git reset HEAD~1 --soft ♻️ git reset --mixed HEAD~1 Move HEAD backwards, reset staged only git reset HEAD~1 --mixed ♻️ git reset --hard HEAD~1 Move HEAD backwards, reset staged and working git reset HEAD~1 --hard 🧹 git rm Delete file and stage removal git rm unwanted_file.txt 🧹 git rm --cached Unstage file but keep it in working directory git rm --cached file.txt 📦 git tag Create a lightweight tag git tag v1.0.0 📦 git tag -a -m """ Create annotated tag git tag -a v1.0.1 -m "Release update" 🌐 git remote add origin Add remote named origin git remote add origin https://github.com/example/repo.git 🌐 git remote set-url origin Change URL for remote origin git remote set-url origin https://github.com/example/repo2.git 🔍 git show Show commit or tag details git show v1.0.0 📤 git push --tags Push tags to remote git push --tags 🪣 git stash Temporarily save changes git stash 🪣 git stash pop Apply last stash and remove it git stash pop ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔧 git --version Display Git version git --version 🆕 git init Initialize new Git repository git init 📖 git help Show detailed help for command git help init 📁 git clone Clone a remote repository git clone https://github.com/example/repo.git 📁 git clone Clone into named folder git clone https://github.com/example/repo.git myrepo 📋 git remote -v View configured remotes git remote -v 🌐 git remote add origin Add remote named origin git remote add origin https://github.com/example/repo.git 🌐 git remote set-url origin Update URL of remote origin git remote set-url origin https://github.com/example/repo2.git 🚀 git push Push commits to remote repository git push origin main 🚀 git push --tags Push tags to remote git push --tags 📥 git fetch Download objects and refs from remote git fetch origin 📥 git pull Fetch and merge changes git pull origin main 📥 git pull --rebase Fetch and rebase changes git pull --rebase origin main 📄 git status Show changes in working directory git status ➕ git add Stage file for next commit git add testfile.txt ➕ git add --all Add all changes (new, modified, deleted) git add --all 🗑️ git rm Remove file and stage deletion git rm obsolete.txt 🗑️ git rm --cached Unstage file (keep locally) git rm --cached temp.txt 📜 git commit -m "" Commit staged changes with message git commit -m "Initial commit" 📜 git commit -am "" Stage and commit modifications git commit -am "Updated files" ⏮️ git log View commit history git log 🕸️ git log --graph View commit history as graph git log --oneline --graph --decorate --all 🔍 git diff View unstaged changes git diff 🔍 git diff --cached View staged changes git diff --cached 🔀 git branch List branches git branch 🔀 git branch Create new branch git branch feature 🆕 git switch Switch branches git switch feature ❌ git branch -d Delete branch git branch -d feature 🔄 git merge Merge branch into current git merge feature ♻️ git rebase Reapply commits on top of another branch git rebase main ♻️ git rebase --continue Resume rebasing after conflict git rebase --continue 🚫 git reset --soft Move HEAD, keep staged and working git reset --soft HEAD~1 🚫 git reset --mixed Move HEAD, reset staged but keep working git reset HEAD~1 --mixed 🚫 git reset --hard Move HEAD and reset staging and working git reset HEAD~1 --hard 🔖 git tag Create inexpensive tag git tag v1.0 📜 git tag -a -m "" Create annotated tag git tag -a v1.0 -m "Release" 📥 git stash Save changes temporarily git stash 📥 git stash list List stashed changes git stash list 📥 git stash pop Apply and drop last stash git stash pop 🧮 git show Show details for commit or tag git show v1.0 📄 git cat-file -t Show object type git cat-file -t HEAD 📄 git cat-file -p Show object content git cat-file -p HEAD ⚙️ git config --global user.name Set global user name git config --global user.name "Your Name" ⚙️ git config --global user.email Set global user email git config --global user.email you@example.com 🧩 git blame Show line by line commit info git blame README.md 📤 git push --force Force push changes (dangerous) git push --force origin main 👀 git remote show Show remote details git remote show origin 🧹 git clean -fd Remove untracked files git clean -fd 🎛️ git reflog Show HEAD change history git reflog 👷 git bisect start Start bisecting to find bad commit git bisect start 👷 git bisect good Mark good commit git bisect good HEAD~10 👷 git bisect bad Mark bad commit git bisect bad HEAD~3 ================================================================================================================================================================================================================================================================ 💪 Bicep & 🌎𝔸zure Pipelines related 😼 GIT commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ⚙️ git config --global init.defaultBranch main Set default branch on init git config --global init.defaultBranch main 🧰 git commit --amend Edit last commit git commit --amend -m "Updated commit message" 🧰 git push origin HEAD:refs/heads/main Push current branch to main on remote git push origin HEAD:refs/heads/main 🛠️ git checkout -b Create and switch to new branch git checkout -b deployment-config-update 🧰 git merge --no-ff Merge with explicit merge commit git merge --no-ff feature/new-bicep-config ⚡ git tag -a release-2025.09.04 -m "Bicep infra release" Create annotated release tag git tag -a release-2025.09.04 -m "Bicep infra release" 🏗️ git pull origin main Update local branch git pull origin main 🧪 git fetch origin Fetch changes from remote git fetch origin 🚦 git push origin main Push commits to remote main branch git push origin main 🔄 git rebase main Rebase current branch on main git rebase main ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🌎𝔸zure DevOps & 😼 GitHub YAML pipeline specific commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🧰 git config --global user.email "buildagent@example.com" Set build agent identity in pipeline git config --global user.email "buildagent@example.com" 🧰 git config --global user.name "Azure DevOps" Set build agent user name git config --global user.name "Azure DevOps" 📂 git ls-files List repository files in pipeline git ls-files 🪄 git checkout $(Build.SourceBranchName) Check out branch in pipeline git checkout refs/heads/feature-branch 📥 git pull origin $(Build.SourceBranchName) Pull changes in pipeline git pull origin feature-branch 🚀 git push origin HEAD:refs/heads/feature-branch Push changes after build git push origin HEAD:refs/heads/feature-branch 💥 git push --force-with-lease Push force respecting remote changes git push --force-with-lease ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 📜 JavaScript Commands ================================================================================================================================================================================================================================================================ 📦 require() Imports a module or file const express = require('express') 🚦 app.get(path, callback) Defines a route handler for HTTP GET requests app.get('/', (req, res) => { res.send('Hello World!') }) 📤 res.send(data) Sends a response to the client res.send('Hello World!') 🖥️ res.json(obj) Sends a JSON response res.json({ countries }) 🧩 app.use(middleware) Registers middleware for error or request handling app.use((err, req, res, next) => { res.status(500).json({ message: `Server Error: ${err}`}) }) 🔌 app.listen(port, callback) Starts server listening on port app.listen(8080, () => { console.log('Server started') }) 🗝️ Object.keys(obj) Gets array of property names from an object Object.keys(data) 🔁 array.map(callback) Transforms elements of an array countryCodes.map(code => ({ code, name: data[code].location })) 🔎 array.find(callback) Finds first element matching condition countryData.data.find(d => d.date === req.params.date) 🌐 req.params Accesses route parameters from URL req.params.country ❓ req.query Accesses query string parameters req.query.page ⏰ Date.now() Returns current timestamp in milliseconds const now = Date.now() 📡 XMLHttpRequest() Creates new AJAX request object const xhr = new XMLHttpRequest() 📬 xhr.open(method, url, async) Initializes AJAX request xhr.open('GET', url, true) 📤 xhr.send(data) Sends AJAX request xhr.send() 🧩 JSON.parse(text) Parses JSON text into a JavaScript object const obj = JSON.parse(xhr.responseText) 📝 document.write(text) Writes text/HTML directly to the page document.write('

Hello

') 🖥️ console.log(data) Outputs message to browser console console.log('Server running') 🌍 navigator.onLine Returns true/false if browser is online const online = navigator.onLine 🏠 window.location.hostname Gets current page's hostname const host = window.location.hostname ⏲️ setTimeout(func, delay) Executes function after delay setTimeout(() => { console.log('Hello') }, 1000) ❌ clearTimeout(id) Cancels a timeout set by setTimeout clearTimeout(timeoutId) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📜 JavaScript Commands, Methods & Functions ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command/Method What it Does Example Usage ----------------------------- -------------------------------------------------------- --------------------------------------------------------- 🚦 function name(params) { ... } Declares a named function function greet(name) { return 'Hi, ' + name; } ⚡ const func = () => { ... } Defines an arrow (anonymous) function const square = x => x * x; 🔁 array.map(callback) Applies callback to each array element, returns new array [1,2,3].map(n => n*2); // [2,4,6] 🔍 array.filter(callback) Filters array elements by callback condition [1,2,3,4].filter(n => n%2==0); // [2,4] 🔎 array.find(callback) Returns first element matching callback condition [1,2,3].find(n => n>1); // 2 🔄 array.forEach(callback) Executes function for each array element [1,2,3].forEach(n => console.log(n)); ➕ array.push(element) Adds element to end of array arr.push(4); ➖ array.pop() Removes last element and returns it const last = arr.pop(); 🚪 array.shift() Removes first element and returns it const first = arr.shift(); 🚪 array.unshift(element) Adds element to front of array arr.unshift(0); 🔢 array.reduce(callback, init) Reduces array to single value by accumulating callback [1,2,3].reduce((a,b)=>a+b,0); // 6 🔮 async function name(args) {} Declares an async function returning a Promise async function fetchData() { let res=await fetch(url); } 📡 fetch(url, options) Makes web request, returns a Promise fetch('/data').then(r => r.json()); 📥 Promise.then(success, fail) Handles Promise success or failure promise.then(result => console.log(result)); ⛄ Promise.catch(fail) Handles Promise failure promise.catch(error => console.error(error)); 🕒 setTimeout(func, delay) Runs a function once after delay in ms setTimeout(() => console.log('Delayed'), 1000); 🛑 clearTimeout(timeoutId) Clears a timeout set by setTimeout clearTimeout(myTimeout); 📚 class Name { ... } Defines an ES6 class class Animal { constructor(name) { this.name = name; } } 🔥 constructor(...) { ... } Special class initialization method constructor(name) { this.name = name; } ★ static method() { ... } Defines a static method on a class static info() { return 'Static info'; } 📌 this References current object or execution context this.name 🛠️ Object.keys(obj) Returns array of own property names Object.keys({a:1, b:2}); // ['a','b'] 🛠️ Object.values(obj) Returns array of own property values Object.values({a:1, b:2}); // [1,2] 🛠️ Object.entries(obj) Returns array of [key, value] pairs Object.entries({a:1, b:2}); // [['a',1],['b',2]] 💡 JSON.parse(str) Parses JSON string to object JSON.parse('{"x":1}') 💡 JSON.stringify(obj) Converts object to JSON string JSON.stringify({x:1}) 📰 console.log(data) Writes data to browser console console.log('Debug info') 🌐 window.location.href Gets or sets current URL window.location.href = 'https://example.com'; 🧭 navigator.onLine Boolean indicating if browser is online alert(navigator.onLine); 🖥️ document.getElementById(id) Gets DOM element by ID const el = document.getElementById('root'); 🖥️ document.querySelector(sel) Gets first DOM element matching selector document.querySelector('.className'); ⚙️ Element.addEventListener(ev, fn) Adds event listener to DOM element button.addEventListener('click', () => alert('Clicked')); 🔔 XMLHttpRequest() Creates AJAX request object const xhr = new XMLHttpRequest(); 📤 xhr.open(method, url, async) Initializes AJAX request xhr.open('GET', '/api/data', true); 📤 xhr.send(body) Sends AJAX request xhr.send(); 📅 Date.now() Returns milliseconds since epoch const timestamp = Date.now(); ⏳ new Date() Creates new Date object const d = new Date(); 🧮 Math.random() Returns random number 0 to 1 Math.random(); 📐 Math.floor(n) Rounds number down Math.floor(3.7); 📊 Math.ceil(n) Rounds number up Math.ceil(3.1); ⏹️ clearInterval(intervalId) Stops interval started by setInterval clearInterval(intervalId); ⏰ setInterval(func, delay) Runs function repeatedly at interval delay setInterval(() => console.log('tick'), 1000); 🐞 throw new Error(msg) Throws a custom error throw new Error('Error'); 📜 try { ... } catch(e) { ... } Exception handling try { ... } catch(e) { console.error(e); } 🛠️ require('module') Imports Node.js module const express = require('express'); 🚀 app.listen(port, callback) Starts Express server listening app.listen(8080, () => console.log('Server started')); 🚦 app.get(path, handler) Adds route handler for HTTP GET in Express app.get('/api', (req, res) => res.send('Hello')); 📦 module.exports = { ... } Exports module content module.exports = myFuncs; 🕵️‍♂️ process.env.VAR Access environment variable in Node.js console.log(process.env.PORT); ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 🖥️ Windows Shell & Management Commands — Emoji Decorated, Tabulated List ================================================================================================================================================================================================================================================================ 💀 shutdown /s /t Shutdown computer after specified seconds shutdown /s /t 30 🔄 shutdown /r /t Restart computer after specified seconds shutdown /r /t 10 ❌ shutdown /a Abort pending shutdown shutdown /a 🕵️ systeminfo Display detailed system info systeminfo 🏷️ hostname Show computer hostname hostname ℹ️ winver Show Windows version info winver 🎛️ msconfig System configuration utility msconfig 🧩 mmc Open Microsoft Management Console mmc ➕ mmc /a Add snap-in to MMC mmc /a compmgmt.msc ➕ mmc /s Snap-in with saved console file mmc /s services.msc 📜 eventvwr Event Viewer utility eventvwr 📜 tasklist List currently running processes tasklist 📛 taskkill Terminate a running process taskkill /im notepad.exe /f 🖥 msinfo32 System Information MSC snap-in msinfo32 ================================================================================================================================================================================================================================================================ *.msc snap-in commands: ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🖥 compmgmt.msc Computer Management console compmgmt.msc 🛑 devmgmt.msc Device Manager console devmgmt.msc 🛠 diskmgmt.msc Disk Management console diskmgmt.msc 🗄 eventvwr.msc Event Viewer console eventvwr.msc 🗂 dsa.msc Active Directory Users and Computers console dsa.msc 🖧 ncpa.cpl Network Connections ncpa.cpl 🔐 secpol.msc Local Security Policy console secpol.msc 🧾 perfmon.msc Performance Monitor console perfmon.msc 📊 resmon.exe Resource Monitor resmon.exe 🛡 gpedit.msc Local Group Policy Editor gpedit.msc 📜 lusrmgr.msc Local Users and Groups console lusrmgr.msc 🔒 certmgr.msc Certificate Manager console certmgr.msc 🧹 cleanmgr.exe Disk Cleanup utility cleanmgr.exe 📡 wf.msc Windows Firewall with Advanced Security wf.msc 🖥 devmgmt.msc Device Manager devmgmt.msc 📦 compmgmt.msc Computer Management compmgmt.msc 🛡 secpol.msc Local Security Policy secpol.msc 🔄 taskschd.msc Task Scheduler taskschd.msc 🧰 services.msc Services management services.msc 📄 certsrv.msc Certificate Services certsrv.msc ================================================================================================================================================================================================================================================================ 🖥️ DOS Shell & WMI Commands ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆕 ver Display current Windows version ver 📂 dir List directory files and folders dir C:\Windows 🗂 cd Change current directory cd C:\Temp 🆕 md / mkdir Create new directory md NewFolder 🗑️ rd / rmdir Remove directory (must be empty) rd OldFolder 🗑 del / erase Delete files del file.txt ✂️ copy Copy files copy file1.txt file2.txt 🛠️ xcopy Copy files/folders with options xcopy C:\Folder1 D:\Folder2 /s /e ↪️ move Move or rename file or directory move file1.txt ..\backup\ 📄 type Display file contents type notes.txt ⌛ timeout Pause command prompt for specified seconds timeout /t 10 🔌 ipconfig Display IP configuration ipconfig /all 🔌 ipconfig /release Release DHCP IP address ipconfig /release 🔌 ipconfig /renew Renew DHCP IP address ipconfig /renew ⚡ ping Send ICMP echo request ping google.com ⚡ tracert Trace route packets tracert google.com ⚙ netstat Show active network connections netstat -an ⚙ netstat -o Show connections with owning process IDs netstat -ano 🖥 net user Manage user accounts net user 👥 net user View or set user properties net user jdoe 🔒 net user /active:no Disable user account net user jdoe /active:no 🛡️ net localgroup View local groups net localgroup ➕ net localgroup Add user to local group net localgroup administrators jdoe /add ➖ net localgroup Remove user from group net localgroup administrators jdoe /delete 🔁 net start Start Windows service net start wuauserv 🛑 net stop Stop Windows service net stop spooler 🔍 wmic OS get Caption,Version,SystemDrive Display OS details wmic OS get Caption,Version,SystemDrive 🔍 wmic process list brief List running processes wmic process list brief 🔍 wmic service list brief List Windows services wmic service list brief ================================================================================================================================================================================================================================================================ 🖥 wmic computersystem get Model,Manufacturer,Name,TotalPhysicalMemory Get computer hardware info wmic computersystem get Model,Manufacturer,Name,TotalPhysicalMemory ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔍 wmic cpu get Name,NumberOfCores,MaxClockSpeed Get CPU info wmic cpu get Name,NumberOfCores,MaxClockSpeed 🕰 wmic os get LastBootUpTime Show system boot time wmic os get LastBootUpTime 🖥 wmic useraccount get name,status List AD user accounts wmic useraccount get name,status 🖥 wmic group get name List AD groups wmic group get name 🕵️ wmic product get Name,Version List installed software wmic product get Name,Version 🛠️ wmic computersystem get domain,username Get logged in user domain & username wmic computersystem get domain,username 🗒️ wmic qfe list List installed hotfixes and updates wmic qfe list ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################ 🗂 SQL STATEMENTS ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 📝 CMD 📄 EXPLANATION 💡 EXAMPLE ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🔍 SELECT Query data from one/more tables SELECT * FROM Employees; ➕ INSERT Add a new record INSERT INTO Employees (Name, City) VALUES ('John', 'London'); 📝 UPDATE Modify existing record(s) UPDATE Employees SET City='Berlin' WHERE Name='John'; ❌ DELETE Remove record(s) DELETE FROM Employees WHERE Name='John'; 🗂 CREATE TABLE Define a new table CREATE TABLE Depts (DeptID INT, DeptName VARCHAR(20)); 🗑 DROP TABLE Delete a table & its data DROP TABLE OldData; ✏️ ALTER TABLE Change table structure ALTER TABLE Employees ADD HireDate DATE; 🔗 JOIN (INNER) Combine rows from 2+ tables SELECT e.Name, d.DeptName FROM Employees e INNER JOIN Depts d ON e.DeptID = d.DeptID; 🔎 WHERE Filter results by a condition SELECT * FROM Products WHERE Price > 50; 🔢 ORDER BY Sort query results SELECT Name FROM Users ORDER BY Name DESC; 📊 GROUP BY Aggregate rows with same value(s) SELECT DeptID, COUNT(*) FROM Employees GROUP BY DeptID; 🧮 COUNT Count rows SELECT COUNT(*) FROM Sales; ➡️ LIMIT / TOP Limit number of returned records SELECT * FROM Orders LIMIT 10; or SELECT TOP 10 * FROM Orders; 🔁 DISTINCT Return only unique values SELECT DISTINCT City FROM Customers; 🗃 CREATE DB Create a new database CREATE DATABASE CompanyDB; 🗑 DROP DB Delete a database DROP DATABASE TestDB; 🔎 LIKE Search pattern in string SELECT * FROM Customers WHERE Name LIKE 'A%'; 🔔 HAVING Filter groups (post aggregation) SELECT DeptID, COUNT(*) FROM Employees GROUP BY DeptID HAVING COUNT(*) > 5; 🔐 PRIMARY KEY Uniquely identify each row CREATE TABLE Users (ID INT PRIMARY KEY, Name VARCHAR(50)); 🔗 FOREIGN KEY Reference a key in another table CREATE TABLE Orders (OrderID INT, UserID INT, FOREIGN KEY (UserID) REFERENCES Users(ID)); ➕ CREATE INDEX Create fast lookup index on a column CREATE INDEX idx_name ON Employees (Name); 🗑 DROP INDEX Remove index DROP INDEX idx_name ON Employees; 👁 CREATE VIEW Virtual table based on a SELECT CREATE VIEW ActiveUsers AS SELECT * FROM Users WHERE Active=1; 🗑 DROP VIEW Remove a view DROP VIEW ActiveUsers; 🛠 EXECUTE PROC Run a stored procedure EXEC GetEmployeeList; ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🆔 SQL Statement 📝 Explanation 💡 Example ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1️⃣ SELECT Retrieve data from table SELECT * FROM Customers; 2️⃣ SELECT DISTINCT Get unique values SELECT DISTINCT City FROM Customers; 3️⃣ SELECT INTO Copy data into new table SELECT * INTO BackupCustomers FROM Customers; 4️⃣ SELECT TOP Limit number of returned rows SELECT TOP 10 * FROM Orders; 5️⃣ FROM Specify table(s) to query SELECT Name FROM Employees; 6️⃣ WHERE Filter rows by condition SELECT * FROM Employees WHERE Age > 30; 7️⃣ AND Combine multiple conditions with AND SELECT * FROM Employees WHERE Age>30 AND City='NY'; 8️⃣ OR Combine multiple conditions with OR SELECT * FROM Employees WHERE Age>30 OR City='NY'; 9️⃣ BETWEEN Filter by range SELECT * FROM Orders WHERE OrderDate BETWEEN '2025-01-01' AND '2025-03-31'; 🔟 LIKE Pattern match strings SELECT * FROM Customers WHERE Name LIKE 'A%'; 1️⃣1️⃣ IN Filter against list of values SELECT * FROM Products WHERE Category IN ('Books','Toys'); 1️⃣2️⃣ IS NULL Check for NULL values SELECT * FROM Employees WHERE ManagerID IS NULL; 1️⃣3️⃣ ORDER BY Sort results SELECT * FROM Employees ORDER BY Salary DESC; 1️⃣4️⃣ GROUP BY Aggregate by one or more columns SELECT DeptID, COUNT(*) FROM Employees GROUP BY DeptID; 1️⃣5️⃣ HAVING Filter grouped records SELECT DeptID, COUNT(*) FROM Employees GROUP BY DeptID HAVING COUNT(*) > 5; 1️⃣6️⃣ JOIN (INNER) Combine rows matching in two tables SELECT * FROM Orders o INNER JOIN Customers c ON o.CustID=c.ID; 1️⃣7️⃣ LEFT JOIN All rows left + matched right rows SELECT * FROM Employees e LEFT JOIN Orders o ON e.ID=o.EmpID; 1️⃣8️⃣ RIGHT JOIN All rows right + matched left rows SELECT * FROM Orders o RIGHT JOIN Employees e ON o.EmpID=e.ID; 1️⃣9️⃣ FULL OUTER JOIN All rows both tables, matched where possible SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.ID=TableB.ID; 2️⃣0️⃣ UNION Combine distinct results from queries SELECT City FROM Customers UNION SELECT City FROM Suppliers; 2️⃣1️⃣ UNION ALL Combine all results including duplicates SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers; 2️⃣2️⃣ INSERT INTO Add new records INSERT INTO Employees (Name, Age) VALUES ('Ann', 28); 2️⃣3️⃣ UPDATE Modify existing records UPDATE Employees SET Age=29 WHERE Name='Ann'; 2️⃣4️⃣ DELETE Remove records DELETE FROM Employees WHERE Age < 20; 2️⃣5️⃣ TRUNCATE TABLE Remove all rows fast TRUNCATE TABLE TempData; 2️⃣6️⃣ CREATE TABLE Define a new table CREATE TABLE Products (ID INT, Name VARCHAR(50)); 2️⃣7️⃣ DROP TABLE Delete table and data DROP TABLE OldProducts; 2️⃣8️⃣ ALTER TABLE Change table structure ALTER TABLE Employees ADD Salary DECIMAL(10,2); 2️⃣9️⃣ CREATE INDEX Create index for faster queries CREATE INDEX idx_name ON Employees(Name); 3️⃣0️⃣ DROP INDEX Delete an index DROP INDEX idx_name ON Employees; 3️⃣1️⃣ CREATE VIEW Virtual table based on query CREATE VIEW ActiveEmployees AS SELECT * FROM Employees WHERE Active=1; 3️⃣2️⃣ DROP VIEW Remove view DROP VIEW ActiveEmployees; 3️⃣3️⃣ CREATE PROCEDURE Store a query-run procedure CREATE PROCEDURE GetAllEmployees AS SELECT * FROM Employees; 3️⃣4️⃣ EXECUTE PROCEDURE Run a stored procedure EXEC GetAllEmployees; 3️⃣5️⃣ BEGIN TRANSACTION Start transaction BEGIN TRANSACTION; 3️⃣6️⃣ COMMIT Save transaction changes COMMIT; 3️⃣7️⃣ ROLLBACK Undo changes in current transaction ROLLBACK; 3️⃣8️⃣ GRANT Give user privileges GRANT SELECT ON Employees TO User1; 3️⃣9️⃣ REVOKE Remove user privileges REVOKE SELECT ON Employees FROM User1; 4️⃣0️⃣ CREATE DATABASE Make a new database CREATE DATABASE CompanyDB; 4️⃣1️⃣ DROP DATABASE Delete a database DROP DATABASE OldDB; 4️⃣2️⃣ USE Select the database in context USE CompanyDB; 4️⃣3️⃣ CASE Conditional logic in queries SELECT Name, CASE WHEN Age>30 THEN 'Senior' ELSE 'Junior' END FROM Employees; 4️⃣4️⃣ COALESCE Return first non-NULL value SELECT COALESCE(Phone, 'N/A') FROM Contacts; 4️⃣5️⃣ CAST Convert data type SELECT CAST(Price AS INT) FROM Products; 4️⃣6️⃣ EXISTS Test for existence of rows SELECT * FROM Employees WHERE EXISTS (SELECT 1 FROM Orders WHERE EmpID=Employees.ID); 4️⃣7️⃣ ANY / SOME Compare with any/some value in list SELECT * FROM Products WHERE Price > ANY (SELECT Price FROM Sales); 4️⃣8️⃣ ALL Compare with all values in list SELECT * FROM Products WHERE Price > ALL (SELECT Price FROM Sales); 4️⃣9️⃣ SUBQUERY Nested query in WHERE/SELECT/etc. SELECT Name FROM Employees WHERE DeptID IN (SELECT ID FROM Departments WHERE Location='NY'); 5️⃣0️⃣ DISTINCT ON PostgreSQL unique on specified column SELECT DISTINCT ON (DeptID) * FROM Employees ORDER BY DeptID, Salary DESC; ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- DB TASKS EXAMPLES ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🛠 Backup DB Backup the database BACKUP DATABASE CompanyDB TO DISK = 'backupfile.bak'; 🔙 Restore DB Restore from backup RESTORE DATABASE CompanyDB FROM DISK = 'backupfile.bak'; 🧑‍💼 Add Column Add new column ALTER TABLE Employees ADD Email VARCHAR(100); 🗑 Remove Column Delete column from table ALTER TABLE Employees DROP COLUMN Email; 🎚 Change Datatype Modify datatype ALTER TABLE Employees ALTER COLUMN Phone VARCHAR(20); 🗂 Create User Add new DB user CREATE USER johndoe WITH PASSWORD = 'abc123'; 🗝 Grant Privilege Give permission to user GRANT SELECT ON TABLE Employees TO johndoe; 🚫 Revoke Privilege Revoke user permission REVOKE SELECT ON TABLE Employees FROM johndoe; 🚫 Drop User Remove user DROP USER johndoe; 🤓 Show Tables List all tables in DB SHOW TABLES; ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🗂 Backup Database BACKUP DATABASE MyDB TO DISK = 'C:\Bkp\MyDB.bak'; Create regular DB backup 💾 Restore Database RESTORE DATABASE MyDB FROM DISK = 'C:\Bkp\MyDB.bak'; Load DB from backup file 🛠 Create Table CREATE TABLE Users (ID INT, Name VARCHAR(50)); Start a new table 🗑 Drop Table DROP TABLE Employees; Remove a table 📝 Modify Table ALTER TABLE Users ADD Email VARCHAR(50); Add/remove/change table columns 🔍 Create Index CREATE INDEX idx_name ON Users (Name); Speed lookup w/index 🗑 Remove Index DROP INDEX idx_name; Remove unneeded index 🚦 Monitor Perf SELECT * FROM sys.dm_exec_query_stats; View query perf stats 📈 Optimize Query EXPLAIN SELECT * FROM Orders; See/tune execution plan 🔒 Create User CREATE USER johndoe IDENTIFIED BY 'pass123'; Add access account 🔑 Grant Privilege GRANT SELECT ON Users TO johndoe; Permit user/table ops 🚫 Revoke Privilege REVOKE INSERT ON Users FROM johndoe; Remove permission 🔑 Enforce Security ALTER USER johndoe WITH LOGIN DISABLED; Disable user account ⏱ Schedule Job -- SQL Agent EXEC msdb.dbo.sp_add_job ... Automate tasks (SQL) ⚙️ Update/Patch ALTER DATABASE MyDB SET COMPATIBILITY_LEVEL=150; Change DB version 📊 Generate Report SELECT Dept, COUNT(*) FROM Employees GROUP BY Dept; Get data/extract reports 📉 Rebuild Index ALTER INDEX ALL ON Users REBUILD; Defrag/reorg indexes 🔄 Replication Setup -- (SQL: sample) sp_addpublication ... Start cluster/sync 🧮 Data Migration INSERT Archive SELECT * FROM Users WHERE Left=1; Move/copy data 🔗 Join Tables SELECT u.Name,o.Id FROM Users u JOIN Orders o ON u.Id=o.Uid; Fetch from multiple tables 📞 Check Connectivity SELECT 1; Test if DB is up 📅 Schedule Event CREATE EVENT ev ON SCHEDULE EVERY 1 DAY DO ...; Automate recurring actions 🌦 Cloud Integration -- CLI: az sql db create ... Link cloud platforms 📂 Manage Storage CHECKPOINT; Force DB writes, manage files 🗄 Archive Data INSERT INTO Archive SELECT * FROM Table WHERE Done=1; Offload cold data 📜 Audit Log Setup CREATE AUDIT ... Track changes/compliance 📝 Manage Constraints ALTER TABLE T ADD CONSTRAINT c CHECK (col>0); Ensure good data 🧾 Manage Views CREATE VIEW v AS SELECT Name FROM Users; Build logical table 🔁 Automate Scripts -- Scripting, SQL Agent or cron jobs Batch SQL tasks 🗄 Table Partition CREATE PARTITION FUNCTION ... Improve big data mgmt 🔒 Data Encryption CREATE DATABASE ENCRYPTION KEY ... Secure at rest 🧩 Schema Versioning -- Tool: Liquibase/Flyway Track changes in scripts 🧑‍🤝‍🧑 Manage Roles CREATE ROLE Reader; GRANT SELECT TO Reader; Group security 📋 Monitor Transactions SELECT * FROM sys.dm_tran_locks; See locks/deadlocks ♻️ Failover/Clustering -- cluster tool, or config Resilience/HA 📦 Manage Procs/Functs CREATE PROC listUsers AS SELECT * FROM Users; Encapsulate logic 🔘 Set Resource Limits ALTER RESOURCE GOVERNOR ... Control usage per user 🎛 DB Tuning Params ALTER DATABASE SCOPED CONFIGURATION ... Change settings 📖 Document DB -- External: ER diagrams, docs Track system/env 📊 Capacity Planning SELECT SUM(size) FROM sysfiles; Forecast growth/usage 🗯 Handle Alerts -- Monitoring tool or SQL Agent creates alerts Proactive error action 🧪 Test Restores RESTORE VERIFYONLY FROM DISK='C:\Bkp\MyDB.bak'; Check backups are OK 🚧 Troubleshoot Issues DBCC CHECKDB; Diagnose/fix problems 🛠 Install Server/Client -- Setup wizard, package mgrs, or CLI install Deploy new DB 🔁 Load Testing -- Tool: HammerDB/JMeter/goose Simulate heavy users 👐 Dev Support GRANT SELECT TO devuser; Help with test data 🔬 Review Exec Plans SET SHOWPLAN_ALL ON; SELECT * ...; Examine/tune cost 🧼 Clean Up Objects DROP TABLE old_t; DROP INDEX idx_old; Remove unused items 🌐 Network Security -- Set firewall; GRANT CONNECT ON ENDPOINT ... Control remote access ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- STORED PROCEDURES EXAMPLES ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 🛠 Create Proc Make a procedure CREATE PROCEDURE GetEmployees AS SELECT * FROM Employees; 🏃 Exec Proc Run a procedure EXEC GetEmployees; 🛠 Proc with Param Proc with argument CREATE PROCEDURE GetByDept @DeptID INT AS SELECT * FROM Employees WHERE DeptID = @DeptID; 🏃 Exec Proc Param Run proc with param EXEC GetByDept 2; 🛠 Proc Insert Insert inside proc CREATE PROCEDURE InsertEmp @Name NVARCHAR(50) AS INSERT INTO Employees(Name) VALUES (@Name); 🏃 Exec Insert Proc Run insert proc EXEC InsertEmp 'Alice'; 🛠 Proc Update Update inside proc CREATE PROCEDURE UpdateDept @ID INT, @Dept NVARCHAR(20) AS UPDATE Departments SET DeptName=@Dept WHERE DeptID=@ID; 🏃 Exec Update Proc Run update proc EXEC UpdateDept 2, 'HR'; 🛠 Delete via Proc Delete row via proc CREATE PROCEDURE DeleteOld AS DELETE FROM Employees WHERE HireDate<'2020-01-01'; 🏃 Exec Delete Proc Run delete proc EXEC DeleteOld; ################################################################################################################################################################################################################################################################ |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ################################################################################################################################################################################################################################################################