PowerShell Archives - TEKSpace Blog https://blog.tekspace.io/category/powershell/ Tech tutorials for Linux, Kubernetes, PowerShell, and Azure Thu, 23 May 2024 14:32:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://blog.tekspace.io/wp-content/uploads/2023/09/cropped-Tekspace-logo-icon-32x32.png PowerShell Archives - TEKSpace Blog https://blog.tekspace.io/category/powershell/ 32 32 Basic Authentication in PowerShell Using Invoke-RestMethod https://blog.tekspace.io/basic-authentication-in-powershell-using-invoke-restmethod/ https://blog.tekspace.io/basic-authentication-in-powershell-using-invoke-restmethod/#respond Thu, 23 May 2024 14:32:10 +0000 https://blog.tekspace.io/?p=1849 Learn how to use basic authentication with PowerShell's Invoke-RestMethod cmdlet. Follow our step-by-step guide and secure your REST API requests.

The post Basic Authentication in PowerShell Using Invoke-RestMethod appeared first on TEKSpace Blog.

]]>
Basic authentication is a simple and widely used method for making authenticated requests to web services. In PowerShell, the Invoke-RestMethod cmdlet is a powerful tool for interacting with REST APIs. This blog post will guide you through the basics of using Invoke-RestMethod with basic authentication, complete with example code to illustrate the process.

Understanding Basic Authentication

Basic authentication is a method where the client sends the username and password encoded in Base64 as part of the request header. It’s important to note that while easy to implement, basic authentication is not secure by itself and should always be used over HTTPS to protect the credentials.

Using Invoke-RestMethod with Basic Authentication

PowerShell’s Invoke-RestMethod cmdlet makes it straightforward to perform REST API requests. To use basic authentication, you’ll need to include an authorization header with your request. Here’s a step-by-step guide:

Step 1: Encode Credentials

First, you need to encode your username and password in Base64. This can be done easily in PowerShell:

# Define your username and password
$username = "your_username"
$password = "your_password"

# Combine username and password
$pair = "$username:$password"

# Encode the combined string in Base64
$encodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair))

# Create the authorization header
$headers = @{
    Authorization = "Basic $encodedCredentials"
}

Step 2: Make the REST API Request

With the credentials encoded and the authorization header set, you can now use Invoke-RestMethod to make the authenticated request. Here’s an example:

# Define the API endpoint URL
$url = "https://api.example.com/data"

# Make the request with the authorization header
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Get

# Output the response
$response

Complete Example

Putting it all together, here is the complete example code:

# Step 1: Encode credentials
$username = "your_username"
$password = "your_password"
$pair = "$username:$password"
$encodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair))
$headers = @{
    Authorization = "Basic $encodedCredentials"
}

# Step 2: Make the REST API request
$url = "https://api.example.com/data"
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Get

# Output the response
$response

Benefits and Best Practices

Benefits

  • Ease of Use: Basic authentication is simple to set up and use, making it suitable for quick tests and simple integrations.
  • Compatibility: It is widely supported across different platforms and programming languages.

Best Practices

  • Use HTTPS: Always use HTTPS to encrypt the credentials and protect them from being intercepted.
  • Avoid Hardcoding Credentials: Store credentials securely and avoid hardcoding them in scripts. Use secure methods like environment variables or secure credential stores.
  • Rotate Credentials Regularly: Regularly update and rotate credentials to minimize security risks.

Using Invoke-RestMethod with basic authentication in PowerShell is a straightforward process that involves encoding your credentials and setting the appropriate headers. While convenient, always ensure you are following best practices to keep your credentials secure. Happy scripting!

By following this guide, you can easily integrate basic authentication into your PowerShell scripts and interact with REST APIs securely and efficiently.

The post Basic Authentication in PowerShell Using Invoke-RestMethod appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/basic-authentication-in-powershell-using-invoke-restmethod/feed/ 0
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
PowerShell convert string to base64 value https://blog.tekspace.io/powershell-convert-string-to-base64-value/ https://blog.tekspace.io/powershell-convert-string-to-base64-value/#respond Mon, 14 Sep 2020 19:03:49 +0000 https://blog.tekspace.io/index.php/2020/09/14/powershell-convert-string-to-base64-value/ To convert string value to base64, follow the below steps in the PowerShell command line window: Encoding to base64 string: Output: Decoding base64 string: Output:

The post PowerShell convert string to base64 value appeared first on TEKSpace Blog.

]]>
To convert string value to base64, follow the below steps in the PowerShell command line window:

Encoding to base64 string:

$encoded  = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("test"))write-output $encoded

Output:

dGVzdA==

Decoding base64 string:

$decoded = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encoded))write-output $decoded

Output:

test

The post PowerShell convert string to base64 value appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/powershell-convert-string-to-base64-value/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
Generate Self-Signed certificate in Windows 7 https://blog.tekspace.io/generate-self-signed-certificate-in-windows-7/ https://blog.tekspace.io/generate-self-signed-certificate-in-windows-7/#respond Tue, 20 Feb 2018 20:13:48 +0000 https://blog.tekspace.io/index.php/2018/02/20/generate-self-signed-certificate-in-windows-7/ To generate self-signed certificates we will use makecert.exe. You will need to first download Windows SDK for Windows 7 or later. Download and install Windows SDK. Once you have downloaded and installed Windows SDK. Go to SDK folder by executing the below command. Generate Root CA Now, we will generate a root certificate. We will […]

The post Generate Self-Signed certificate in Windows 7 appeared first on TEKSpace Blog.

]]>
To generate self-signed certificates we will use makecert.exe. You will need to first download Windows SDK for Windows 7 or later.

Download and install Windows SDK.

Once you have downloaded and installed Windows SDK. Go to SDK folder by executing the below command.

cd C:\Program Files (x86)\Windows Kits\10\bin\x64

Generate Root CA

Now, we will generate a root certificate. We will use the root ca certificate to bind with client certificate later in this article.

makecert -sky exchange -r -n "CN=MyRootCert" -pe -a sha256 -len 2048 -ss Root

The above command will generate root ca and load it in Trusted Root Certificate -> Certificates folder.

Create client certificate

makecert.exe -n "CN=client.example.com" -pe -sky exchange -m 96 -ss My -in "MyRootCert" -is root -a sha256

The above command will create client certificate called client.example.com with MyRootCert binded together and load it in Personal -> Certificates folder under your user profile.

NOTE: If you have Windows 10 or Windows Server 2016 OS. You can use native PowerShell cmdlets to generate self-signed certificates.

The post Generate Self-Signed certificate in Windows 7 appeared first on TEKSpace Blog.

]]>
https://blog.tekspace.io/generate-self-signed-certificate-in-windows-7/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