PowerShell Archives - TEKSpace Blog https://blog.tekspace.io/tag/powershell/ Tech tutorials for Linux, Kubernetes, PowerShell, and Azure Tue, 17 Oct 2023 20:15:37 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://blog.tekspace.io/wp-content/uploads/2023/09/cropped-Tekspace-logo-icon-32x32.png PowerShell Archives - TEKSpace Blog https://blog.tekspace.io/tag/powershell/ 32 32 Exporting Web.config AppSettings to CSV using PowerShell https://blog.tekspace.io/exporting-web-config-appsettings-to-csv-using-powershell/ https://blog.tekspace.io/exporting-web-config-appsettings-to-csv-using-powershell/#respond Tue, 17 Oct 2023 20:15:37 +0000 https://blog.tekspace.io/?p=1800 Managing configurations is a critical part of ensuring that applications run correctly across different environments. In .NET applications, configurations such as appSettings are often stored in a Web.config file. At some point, you might find it essential to export these settings to a CSV file. This will enable you to analyze, share, or create backups

The post Exporting Web.config AppSettings to CSV using PowerShell appeared first on TEKSpace Blog.

]]>
Managing configurations is a critical part of ensuring that applications run correctly across different environments. In .NET applications, configurations such as appSettings are often stored in a Web.config file. At some point, you might find it essential to export these settings to a CSV file. This will enable you to analyze, share, or create backups of the configurations. In this tutorial, we’ll show how to extract appSettings from a Web.config file and save them in a CSV file using PowerShell.

Step 1: Load the Web.config File

Firstly, you will need to load the Web.config file into PowerShell. You can accomplish this using the XmlDocument class.

[xml]$webConfig = Get-Content 'C:\path\to\web.config'

Step 2: Navigate to the appSettings Section

Once the Web.config file is loaded, navigate to the appSettings section to access the key-value pairs. Utilize the SelectNodes method to get all the add elements under the appSettings section.

$appSettings = $webConfig.Configuration.appSettings.add

Step 3: Create an Array to Store Key-Value Pairs

Before iterating through the appSettings, create an array to store the key-value pairs.

$keyValuePairs = @()

Step 4: Extract Key-Value Pairs

Iterate over each added element, create a customized PowerShell object for each key-value pair, and add each object to the array.

foreach ($setting in $appSettings) {
    $obj = New-Object PSObject
    $obj | Add-Member -MemberType NoteProperty -Name "Key" -Value $setting.Key
    $obj | Add-Member -MemberType NoteProperty -Name "Value" -Value $setting.Value
    $keyValuePairs += $obj
}

Step 5: Export Key-Value Pairs to a CSV File

Finally, use the Export-Csv cmdlet to write the key-value pairs to a CSV file.

$keyValuePairs | Export-Csv -Path 'C:\path\to\output.csv' -NoTypeInformation

Using PowerShell, you can extract appSettings from a Web.config file and export them to a CSV file with just a few lines of code. This approach provides a straightforward way to manage and analyze your application configurations. The script can be further customized or wrapped into a reusable function, making it a versatile tool for configuration management in .NET applications.

The post Exporting Web.config AppSettings to CSV using PowerShell appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/exporting-web-config-appsettings-to-csv-using-powershell/feed/ 0
Top 100 Essential PowerShell Commands: Your Must-Know Cheat Sheet https://blog.tekspace.io/top-100-essential-powershell-commands-your-must-know-cheat-sheet/ https://blog.tekspace.io/top-100-essential-powershell-commands-your-must-know-cheat-sheet/#respond Wed, 30 Aug 2023 01:14:54 +0000 https://blog.tekspace.io/?p=1416 PowerShell, an integral component of Windows operating systems, has revolutionized the way administrators and users interact with their systems by offering a robust command-line environment. At its core, PowerShell empowers users to leverage a comprehensive set of commands, often referred to as cmdlets, to perform a wide array of tasks. From basic PowerShell commands like

The post Top 100 Essential PowerShell Commands: Your Must-Know Cheat Sheet appeared first on TEKSpace Blog.

]]>
PowerShell, an integral component of Windows operating systems, has revolutionized the way administrators and users interact with their systems by offering a robust command-line environment. At its core, PowerShell empowers users to leverage a comprehensive set of commands, often referred to as cmdlets, to perform a wide array of tasks. From basic PowerShell commands like ‘Get-ChildItem’ for navigating files and directories to more complex operations involving system management and automation, this environment has become an indispensable tool for Windows users.

Unlike the traditional command-line interface (CLI) like the Command Prompt, PowerShell’s flexibility comes from its ability to work with objects and data streams. By utilizing cmdlets, users can perform operations on data objects directly, making it easier to manipulate and manage information. Moreover, PowerShell offers the capability to create and execute scripts, enabling users to automate intricate processes and repetitive tasks efficiently.

However, before harnessing the full potential of PowerShell commands and scripts, one must navigate the concept of execution policies. These policies dictate the level of trust PowerShell places in various scripts and configurations. Understanding and managing these policies ensures a secure and controlled environment for executing scripts and commands. Whether it’s for automating routine tasks, managing systems at scale, or extracting insights from data, Windows PowerShell serves as an indispensable platform that empowers users to achieve efficient and streamlined operations within the Windows environment.

Here are the top 100 PowerShell commands to use and everyone should master:

NoCommandDescriptionExample
1Get-HelpDisplays information about PowerShell commands.Get-Help Get-Process
2Get-CommandLists all available commands in PowerShell.Get-Command
3Get-ChildItemRetrieves files and folders in a specified location.Get-ChildItem C:\
4Set-LocationChanges the current working directory.Set-Location D:\
5Get-ContentReads the content of a file.Get-Content file.txt
6Out-FileWrites output to a file.Get-Process | Out-File processes.txt
7Write-OutputSends output to the pipeline.Write-Output “Hello, PowerShell!”
8Select-ObjectSelects specific properties of objects.Get-Process | Select-Object Name, CPU
9Where-ObjectFilters objects based on specified criteria.Get-Service | Where-Object { $_.Status -eq “Running” }
10ForEach-ObjectPerforms an operation on each object in a pipeline.1..5 | ForEach-Object { $_ * 2 }
11Format-TableFormats output as a table.Get-Process | Format-Table -AutoSize
12Sort-ObjectSorts objects by specified properties.Get-Service | Sort-Object Status
13Measure-ObjectCalculates properties of objects (e.g., length).“Hello, PowerShell!” | Measure-Object -Character
14New-ItemCreates a new item (file, folder, etc.).New-Item newfile.txt -ItemType File
15Remove-ItemDeletes an item.Remove-Item file.txt
16Copy-ItemCopies files or folders.Copy-Item file.txt newfolder
17Rename-ItemRenames an item.Rename-Item file.txt newname.txt
18Test-PathChecks if a file or folder exists.Test-Path file.txt
19Get-ServiceRetrieves services.Get-Service
20Start-ServiceStarts a service.Start-Service serviceName
21Stop-ServiceStops a service.Stop-Service serviceName
22Restart-ServiceRestarts a service.Restart-Service serviceName
23Get-ProcessRetrieves processes.Get-Process
24Start-ProcessStarts a process.Start-Process notepad
25Stop-ProcessStops a process.Stop-Process -Name notepad
26Get-WmiObjectRetrieves management information using WMI.Get-WmiObject Win32_ComputerSystem
27Get-EventLogRetrieves event log data.Get-EventLog -LogName Application
28Get-ContentReads the content of a file.Get-Content file.txt
29Set-ContentWrites content to a file.Set-Content file.txt “New content”
30Test-ConnectionTests network connectivity.Test-Connection google.com
31Test-NetConnectionComprehensive network connectivity test.Test-NetConnection google.com
32Invoke-WebRequestPerforms HTTP requests.Invoke-WebRequest https://www.example.com
33ConvertTo-JsonConverts objects to JSON format.Get-Process | ConvertTo-Json
34ConvertFrom-JsonConverts JSON data to objects.‘{“Name”:”John”,”Age”:30}’ | ConvertFrom-Json
35Get-DateRetrieves the current date and time.Get-Date
36New-ObjectCreates a new object.New-Object PSObject
37Get-ContentReads the content of a file.Get-Content file.txt
38Set-ContentWrites content to a file.Set-Content file.txt “New content”
39Invoke-ExpressionInvokes a command or expression as if by typing it.Invoke-Expression ‘Get-Process’
40Write-HostDisplays messages to the console.Write-Host “Hello, PowerShell!”
41Out-GridViewDisplays data in a graphical table.Get-Process | Out-GridView
42Out-PrinterSends output to a printer.Get-Process | Out-Printer
43Get-HostRetrieves host information.Get-Host
44Get-ModuleLists the modules imported into the session.Get-Module
45Import-ModuleImports a module into the session.Import-Module MyModule
46Remove-ModuleRemoves imported modules from the session.Remove-Module MyModule
47Get-CommandLists available commands.Get-Command
48Get-AliasLists aliases.Get-Alias
49Set-AliasCreates or changes aliases.Set-Alias np Notepad
50Clear-HostClears the console screen.Clear-Host
51Clear-ContentClears the content of a file.Clear-Content file.txt
52Clear-ItemRemoves the content of an item.Clear-Item file.txt
53Clear-VariableRemoves variable values.Clear-Variable varName
54Clear-RecycleBinClears the contents of the Recycle Bin.Clear-RecycleBin
55Compare-ObjectCompares two sets of objects.Compare-Object object1 object2
56Complete-TransactionCompletes a transaction.Complete-Transaction
57ConvertFrom-CsvConverts CSV-formatted data to objects.Get-Content data.csv | ConvertFrom-Csv
58ConvertTo-CsvConverts objects to CSV format.Get-Process | ConvertTo-Csv -NoTypeInformation
59Debug-ProcessDebugs a process.Debug-Process -Id processId
60Disable-PSBreakpointDisables breakpoints.Disable-PSBreakpoint -Id breakpointId
61Enable-PSBreakpointEnables breakpoints.Enable-PSBreakpoint -Id breakpointId
62ExitExits the current session.Exit
63Export-AliasExports aliases to a file.Get-Alias | Export-Alias -Path aliases.txt
64Export-ClixmlExports objects to an XML file.Get-Process | Export-Clixml process.xml
65Export-CsvExports objects to a CSV file.Get-Process | Export-Csv process.csv
66ForEach-ObjectIterates through objects in the pipeline.1..5 | ForEach-Object { $_ * 2 }
67Format-CustomFormats output using a customized view.Get-Process | Format-Custom
68Format-HexFormats data as hexadecimal values.Format-Hex 123
69Format-ListFormats output as a list of properties.Get-Process | Format-List
70Format-TableFormats output as a table.Get-Process | Format-Table -AutoSize
71Format-WideFormats output as a table with a single wide column.Get-Process | Format-Wide
72Get-AclRetrieves access control lists (ACLs).Get-Acl file.txt
73Set-AclSets access control lists (ACLs).Set-Acl file.txt -AclObject $aclObj
74Get-AliasGets aliases.Get-Alias
75Get-AuthenticodeSignatureRetrieves digital signatures.Get-AuthenticodeSignature file.exe
76Get-ChildItemRetrieves items in a location.Get-ChildItem C:\
77Get-ClipboardRetrieves the current clipboard contents.Get-Clipboard
78Get-CommandGets commands.Get-Command
79Get-ComputerInfoRetrieves computer information.Get-ComputerInfo
80Get-ContentRetrieves the content of an item.Get-Content file.txt
81Get-CredentialRetrieves stored credentials.Get-Credential
82Get-CultureRetrieves culture information.Get-Culture
83Get-DateRetrieves the current date and time.Get-Date
84Get-EventRetrieves events.Get-Event
85Get-HistoryRetrieves the command history.Get-History
86Get-HostRetrieves host information.Get-Host
87Get-HotFixRetrieves installed hotfixes.Get-HotFix
88Get-ItemRetrieves items.Get-Item
89Get-ItemPropertyRetrieves property values of an item.Get-ItemProperty file.txt -Name Length
90Get-JobRetrieves background jobs.Get-Job
91Get-LocationRetrieves the current location.Get-Location
92Get-MemberRetrieves members of an object.Get-Process | Get-Member
93Get-ModuleLists the modules imported into the session.Get-Module
94Get-OSVersionRetrieves the operating system version.Get-WmiObject Win32_OperatingSystem | Select-Object Caption
95Get-ProcessRetrieves processes.Get-Process
96Get-RandomGenerates random numbers.Get-Random -Minimum 1 -Maximum 100
97Get-ServiceRetrieves services.Get-Service
98Get-TransactionRetrieves transactions.Get-Transaction
99Get-UICultureRetrieves user interface culture information.Get-UICulture
100Get-UniqueRetrieves unique items.Get-ChildItem | Get-Unique

The post Top 100 Essential PowerShell Commands: Your Must-Know Cheat Sheet appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/top-100-essential-powershell-commands-your-must-know-cheat-sheet/feed/ 0
Access Azure REST API using PowerShell https://blog.tekspace.io/access-azure-rest-api-using-powershell/ https://blog.tekspace.io/access-azure-rest-api-using-powershell/#respond Mon, 05 Mar 2018 08:06:49 +0000 https://blog.tekspace.io/index.php/2018/03/05/access-azure-rest-api-using-powershell/ PowerShell can be used as a REST client to access Azure REST APIs. To access Azure REST methods, you will need to have access to subscription with Azure AD App Registration. If you haven’t done Azure AD App registration. You can follow this article here. Make sure you capture client secret key after app is

The post Access Azure REST API using PowerShell appeared first on TEKSpace Blog.

]]>
PowerShell can be used as a REST client to access Azure REST APIs. To access Azure REST methods, you will need to have access to subscription with Azure AD App Registration. If you haven’t done Azure AD App registration. You can follow this article here. Make sure you capture client secret key after app is registered. Once you have tenant id, client id, client secret, and subscription id you can proceed forward with below instructions.

To make life easier, I have checked my PowerShell code on Github. Feel free to download them and modify them to your needs.

In this tutorial, I will go over how to get resource groups from Azure REST API. One of the basic CRUD operations, I will perform.

Create a file called Get-AzureResourceGroup.ps1. Let’s create the required variables. Make sure to fill in the required variables from your Azure subscription.

Variables

# Variables
$TenantId = "" # Enter Tenant Id.
$ClientId = "" # Enter Client Id.
$ClientSecret = "" # Enter Client Secret.
$Resource = "https://management.core.windows.net/"
$SubscriptionId = "" # Enter Subscription Id.

Once you have updated the above required values. Let’s make a first REST call to get access token.

We will use the below URL to make a REST call to get access token.

POST https://login.microsoftonline.com/{tenantId}/oauth2/token

Request Access Token

Add the following code to your PowerShell script after variables.

$RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"

$body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret&resource=$Resource"

$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'

Write-Host "Print Token" -ForegroundColor Green
Write-Output $Token

After you have retrieved the access token, we will use that to authorize Azure REST methods.

Get Resource groups

To retrieve all resource groups in Azure. We will use the below URL.

GET https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups?api-version=2017-05-10

Enter below code to Get-AzureResourceGroup.ps1.

# Get Azure Resource Groups
$ResourceGroupApiUri = "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups?api-version=2017-05-10"

$Headers = @{}

$Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")

$ResourceGroups = Invoke-RestMethod -Method Get -Uri $ResourceGroupApiUri -Headers $Headers

Write-Host "Print Resource groups" -ForegroundColor Green
Write-Output $ResourceGroups

The above line of code should return all the resource groups from an Azure subscription.

Below is the full script and output.

# Variables
$TenantId = "" # Enter Tenant Id.
$ClientId = "" # Enter Client Id.
$ClientSecret = "" # Enter Client Secret.
$Resource = "https://management.core.windows.net/"
$SubscriptionId = "" # Enter Subscription Id.

$RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"

$body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret&resource=$Resource"

$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'

Write-Host "Print Token" -ForegroundColor Green
Write-Output $Token

# Get Azure Resource Groups
$ResourceGroupApiUri = "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups?api-version=2017-05-10"

$Headers = @{}

$Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")

$ResourceGroups = Invoke-RestMethod -Method Get -Uri $ResourceGroupApiUri -Headers $Headers

Write-Host "Print Resource groups" -ForegroundColor Green
Write-Output $ResourceGroups

Output:

The post Access Azure REST API using PowerShell appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/access-azure-rest-api-using-powershell/feed/ 0
Convert certificate from pfx to base64 with PowerShell https://blog.tekspace.io/convert-certificate-from-pfx-to-base64-with-powershell/ https://blog.tekspace.io/convert-certificate-from-pfx-to-base64-with-powershell/#respond Thu, 15 Feb 2018 19:44:25 +0000 https://blog.tekspace.io/index.php/2018/02/15/convert-certificate-from-pfx-to-base64-with-powershell/ To convert a certificate that is in .pfx to base64 format in PowerShell, you can use .NET namespace available in PowerShell to convert. I had a scenario where I was required to use base64 encoding to upload a certificate to Azure to secure communication to backend instance. Since Microsoft Azure provides a rich API to

The post Convert certificate from pfx to base64 with PowerShell appeared first on TEKSpace Blog.

]]>
To convert a certificate that is in .pfx to base64 format in PowerShell, you can use .NET namespace available in PowerShell to convert. I had a scenario where I was required to use base64 encoding to upload a certificate to Azure to secure communication to backend instance. Since Microsoft Azure provides a rich API to work with. I was able to make a patch request and push a certificate to Azure.

In this tutorial, I will show you how to convert a certificate from .pfx to base64.

Open PowerShell as an administrator.

Now that we have a PowerShell console opened. Let’s first load the content into a variable.

$pfx_cert = get-content 'c:\certificate.pfx' -Encoding Byte

The above command will load the content with byte encoding. If you print $pfx_cert in the PowerShell console, you will see random numbers. In order to convert to base64 format, we will use system namespace from Windows system.

To convert a certificate in base64, execute the below command.

$base64 = [System.Convert]::ToBase64String($pfx_cert)

The above command will save it in $base64 variable, and now you can use this variable or output it to a file depending on your scenario.

The post Convert certificate from pfx to base64 with PowerShell appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/convert-certificate-from-pfx-to-base64-with-powershell/feed/ 0
Kubernetes Services Watch For New Events https://blog.tekspace.io/kubernetes-services-watch-for-new-events/ https://blog.tekspace.io/kubernetes-services-watch-for-new-events/#respond Mon, 12 Feb 2018 01:57:33 +0000 https://blog.tekspace.io/index.php/2018/02/11/kubernetes-services-watch-for-new-events/ Are you one of those who likes to understand how giant cloud providers create load balancer virtual IP address in cloud? If yes, you are in the right place. I will go over how to establish connection to Kubernetes API; and then I will go over how to listen for new changes in Kubernetes watch

The post Kubernetes Services Watch For New Events appeared first on TEKSpace Blog.

]]>
Are you one of those who likes to understand how giant cloud providers create load balancer virtual IP address in cloud? If yes, you are in the right place. I will go over how to establish connection to Kubernetes API; and then I will go over how to listen for new changes in Kubernetes watch API for services and perform action accordingly.

I will be using PowerShell to listen for new changes. You can use any scripting / programing language you like. I chose PowerShell because I would like to manage my Kubernetes Cluster via the Windows system.

Before I get into details, I recommend following this articles on

Understanding Kubernetes API

Kubernetes API provides access to Kubernetes Cluster to manage Pods, Services, and much more. You can get more details from Kubernetes Reference Documentation.. One of the challenge I had was finding right examples on above reference doc from kubernetes site. But I was able to manage to understand how the API worked using Kubernetes Dashboard and using Fiddler to monitor calls made my Kubernetes Dashboard.

If you followed my articles from above. You will see that accessing API via Kubectl proxy makes it much more easier. You can then write your code in any language and make request to proxy URL that already has all the authentication and access mechanism created for you. So you don’t have to add that in your code.

In this tutorial, I will use a proxy URL to make API calls. You can choose any method you like by referring to Kubernetes Documentation.

From your remote machine where you have kubectl and kube config file setup, execute below command to proxy your API requests.

kubectl proxy

The above link will provide you a proxy URL that then you can use in your script to watch for events. You should receive something similar as shown below.

Starting to serve on 127.0.0.1:8001

The default API URL is http://127.0.0.1:8001/api/v1. Depending on when you are reading this blog, the API version may change. You can get the API version from http://127.0.0.1:8001/ and then you can use that in your code.

Now that you know how to access API. Let’s go deep on how make a get request to watch for changes in services API.

Accessing Services API

Services API can be accessed by making a GET request to http://127.0.0.1:8001/api/v1/services. This will give you all the available services as JSON.

There is also a watch API where you can make GET request, which will keep the connection open as long as your proxy is up and running. You can make the request at http://127.0.0.1:8001/api/v1/watch/services. This will return all the events that are created in all the namespaces. If you want to make a get request on a specific namespace, you can use /api/v1/watch/namespaces/{namespace}/services/{name} and change values that are in {}. I will use /api/v1/watch/services to watch for events for all the namespaces and then filter out on what I need.

I have created a repository on Git that contains PowerShell script that will watch for new events. You can download it and make appropriate changes for your environments from here.

The script contains following logic that will run in while loop and perform action accordingly.

#regions HTTP Watch Request
$request = [System.Net.WebRequest]::Create($watch_services_url)
# Get Response
$resp = $request.GetResponse()
# Get Response Stream
$reqstream = $resp.GetResponseStream()
# Create new object for StreamReader
$sr = New-Object System.IO.StreamReader $reqstream
# Create a loop for listening for new events
while (!$sr.EndOfStream)
{
    # Read the line
    $line = $sr.ReadLine();
    # Convert json string to PSObject
    $line_object = $line | ConvertFrom-Json
    # Get Metadata
    $metadata = $line_object.object.metadata
    # Get request type
    $type = $line_object.type

    # Process data returned
    Process-Request -object $line_object
}
# Function
function Process-Request
{
    Param
    (
        [psobject]$object
    )
    $data = $object
    $data = Remove-Old-Events -object $data
    if ($data.type -eq "ADDED")
    {
        # Create Load balancer
        $metadata = Create-LB-Metadata -object $data
        Create-LoadBalancer -object $metadata
    }
    if ($data.type -eq "DELETED")
    {
        # Delete Load balancer
        # Add logic here

    }
    if ($data.type -eq "MODIFIED")
    {
        # Modify Load balancer 
        # Add logic here

    }
}
#endregions

The above while loop example will run until it reaches the end of the stream. The watch request that we made to Kubernetes API, will continuously run and connection will stay open between client and master node for infinitely unless there is a network disconnect or master node is unreachable. You will have to write your own logic to add retry function in case you have lost access to API.

In the script, I left Create-LoadBalancer & Delete-LoadBalancer empty. You can insert your own business logic to create proxy or virtual IP via your external load balancer.

This tutorial is created to understand how API works for watch events and does not go very deep to it. As long as you understand how the integration to API works, you should be able to add your own custom logic depending on your environment.

The post Kubernetes Services Watch For New Events appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/kubernetes-services-watch-for-new-events/feed/ 0