```sh $progressPreference = 'silentlyContinue' Write-Information "Downloading WinGet and its dependencies..." Invoke-WebRequest -Uri https://aka.ms/getwinget -OutFile Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle Invoke-WebRequest -Uri https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx -OutFile Microsoft.VCLibs.x64.14.00.Desktop.appx Invoke-WebRequest -Uri https://github.com/microsoft/microsoft-ui-xaml/releases/download/v2.7.3/Microsoft.UI.Xaml.2.7.x64.appx -OutFile Microsoft.UI.Xaml.2.7.x64.appx Add-AppxPackage Microsoft.VCLibs.x64.14.00.Desktop.appx Add-AppxPackage Microsoft.UI.Xaml.2.7.x64.appx Add-AppxPackage Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle ``` Below is code snippet to install Net 7.0 SDK using winget ```sh winget install Microsoft.DotNet.SDK.7 ``` Below is code snippet to install Net 7.0 runtime using winget ```sh winget install dotnet-runtime-7 ```powershell
Azure Cloud Solution Architect, Full-Stack Development in .Net Eco system, Senior Manager at Capgemini
Sunday, November 19, 2023
How to install winget utility using powershell
Windows Package Manager (winget) is a command-line tool that enables users to discoer, install, upgrade, remove and configure application on windows 10 and higher version
We can install winget utility using below powershell script in windows
Sunday, October 8, 2023
Get Folders with Exclude folders recursively
In general , we can use get-childitems to get folders recursively and if we want to exculde any list of folders then we can use Exclude switch but this switch wont work for recursively , it only work for
current depth so we can use below recursive function to get list of folders recursively by excluding list of folders recursively.
```sh function Get-Folders { param ( [string]$Path, [string[]]$Excludes ) $list = New-Object System.Collections.Generic.List[string] $Directories=(gci $path -Directory -Exclude $Excludes ).FullName foreach ( $Directory in $Directories) { $Directory Get-Folders $Directory -Excludes $Excludes } } [string[]]$Excludes=@("bin","obj",".vscode","dialogs","Controllers","AzureOpenAIBot") Get-Folders "C:\Users\codeRep\labs\aztd-OpenAI" -Excludes $Excludes ```
Monday, September 18, 2023
git stash usages
---- Sure, here are some examples of how you gcan use `git stash`: 1. **Save changes to a new stash**: - Suppose you're working on a new feature in a dedicated branch, but you need to switch to another branch to fix a bug. - You've made changes that you don't want to commit yet, so you can stash them. Here's how you can do it: ```bash git stash save "WIP on new feature" ``` This command will save your changes to a new stash with the message "WIP on new feature". You can use any message that helps you remember what changes are in the stash. 2. **List all stashes**: - If you want to see all of the stashes that you've currently saved, you can use this command: ```bash git stash list ``` This command will show you a list of all stashes that you currently have. 3. **Apply changes from the most recent stash**: - Once you're ready to continue working on your new feature, you can apply the changes from your most recent stash using this command: ```bash git stash pop ``` This command will apply the changes from the most recent stash and then remove it from your list of stashes. 4. **Apply changes from a specific stash**: - If you have multiple stashes and you want to apply changes from a specific one, you can do so with this command: ```bash git stash apply stash@{10} ``` This command will apply the changes from the stash named `stash@{10}`. 5. **Discard the most recent stash**: - If you decide that you no longer need the changes in your most recent stash, you can discard it with this command: ```bash git stash drop ``` This command will discard the most recent stash. 6. **Remove all stashes**: - If you want to remove all of your stashes at once, you can use this command: ```bash git stash clear ``` This command will remove all of your stashes. Note Remember, any changes that are stashed are kept locally and are not transferred when you push your commits to a remote repository.
Sunday, September 17, 2023
Ways of Identifying duplicate rows in SQL
---- To find duplicate rows using partition and rank, you can use the following steps: - First, you need to use the PARTITION BY clause to divide the rows in your table into groups based on one or more columns that you want to compare for duplicates. For example, if you want to find duplicate rows based on the name and address columns, you can use PARTITION BY name, address. - Next, you need to use the ORDER BY clause to specify the order of rows within each partition. You can use any column that you want to sort by, such as the ID column. For example, you can use ORDER BY ID. - Then, you need to use the RANK () function to assign a rank to each row within each partition. The rank starts from 1 and increases by 1 for each row. If two or more rows have the same values in the partition columns, they will have the same rank. For example, you can use RANK () OVER (PARTITION BY name, address ORDER BY ID) AS rank. - Finally, you need to select the rows that have a rank greater than 1. These are the duplicate rows that have the same values in the partition columns as another row. You can use a subquery or a common table expression (CTE) to filter these rows. For example, you can use: ```sql -- Using a subquery SELECT * FROM ( SELECT *, RANK () OVER (PARTITION BY name, address ORDER BY ID) AS rank FROM table_name ) t WHERE rank > 1; -- Using a CTE WITH cte AS ( SELECT *, RANK () OVER (PARTITION BY name, address ORDER BY ID) AS rank FROM table_name ) SELECT * FROM cte WHERE rank > 1; ``` There are some other ways to find duplicate rows in SQL, depending on the database system and the requirements. Here are some examples: - You can use the EXISTS or NOT EXISTS operator to check if a row exists in a subquery that matches the values of another row. For example, you can use this query to find duplicate rows based on the name and address columns: ```sql SELECT * FROM table_name t1 WHERE EXISTS ( SELECT 1 FROM table_name t2 WHERE t1.name = t2.name AND t1.address = t2.address AND t1.id <> t2.id ); ``` - You can use the JOIN clause to join a table with itself and compare the values of the columns. For example, you can use this query to find duplicate rows based on the name and address columns: ```sql SELECT t1.* FROM table_name t1 JOIN table_name t2 ON t1.name = t2.name AND t1.address = t2.address AND t1.id <> t2.id; ``` - You can use the DISTINCT or GROUP BY clause to select only the unique values of the columns and then use the EXCEPT or MINUS operator to subtract them from the original table. For example, you can use this query to find duplicate rows based on the name and address columns: ```sql SELECT name, address FROM table_name EXCEPT SELECT DISTINCT name, address FROM table_name; ``` To identify duplicate rows using group by in SQL, you can use the following steps: - First, you need to select the columns that you want to check for duplicates using the SELECT statement. For example, if you want to find duplicate rows based on the name and address columns, you can use SELECT name, address. - Next, you need to use the GROUP BY clause to group the rows by the selected columns. For example, you can use GROUP BY name, address. - Then, you need to use the COUNT function in the HAVING clause to filter the groups that have more than one row. These are the groups that contain duplicates. For example, you can use HAVING COUNT (*) > 1. - Finally, you need to execute the query and see the results. For example, the complete query would look like this: ```sql SELECT name, address FROM table_name GROUP BY name, address HAVING COUNT (*) > 1; ``` This query will return all the rows that have duplicate values in the name and address columns.
Remove port in windows
---- To remove a port in Windows, you need to find and kill the process that is using that port. You can do that by following these steps: - Open a command prompt as an administrator. - Type the command `netstat -ano | findstr :8000` and press Enter. This will show you the process ID (PID) of the process that is using port 8000. - Type the command `taskkill /F /PID` and press Enter, where ` ` is the number you found in the previous step. This will force the process to terminate and free the port. - You can verify that the port is no longer in use by typing the command `netstat -ano | findstr :8000` again and seeing no results. ```sh netstat -ano | findstr :8000 taskkill /F /PID 8992 # example PID 8992 which was return by above statement ```
Wednesday, September 13, 2023
Extract SQL query from Open Database connection in EXCEL
---- 1. This script opens an Excel file, loops through each connection in the workbook, checks if the connection is an OLEDB connection, 2. then prints the command text (SQL query) of each OLEDB connection. 3. Rplace "C:\path\to\your\Spreadshee.xlsx" with the path to your Excel file1. ```sh # Create an Excel COM object $excel = New-Object -ComObject Excel.Application Extracting SQL queries from Excel’s open data connection # Open the workbook $workbook = $excel.Workbooks.Open("C:\path\to\your\Spreadshee.xlsx") # Loop through each connection in the workbook foreach ($connection in $workbook.connections) { # Check if the connection is an OLEDB connection if ($connection.Type -eq 2) { # Get the OLEDB connection $oledbConnection = $connection.OLEDBConnection # Print the command text (SQL query) Write-Output $oledbConnection.CommandText } } # Close the workbook and quit Excel $workbook.Close() $excel.Quit() # Release the COM objects [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() ``` Please note that this script requires Excel to be installed on your machine, as it uses Excel’s COM object model. Also, running scripts that use COM objects might have issues with non-interactive sessions (like a scheduled task or a remote session).
Extract Data from Excel using powershell
---- 1. This script opens an Excel file and reads data from a sheet named Sheet. 2. Replace "SELECT * FROM [Sheet1$]" with the query that suits your needs. 3. Also, please ensure that the Microsoft.ACE.OLEDB.12.0 provider is installed on your machine, as it’s required to read data from Excel1. ```sh #Read data from Excel $cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES';Data Source=c:temptest.xlsx;Mode=Share Deny Write;Jet OLEDB:Engine Type=37;" $cn = New-Object System.Data.OleDb.OleDbConnection $cnStr $cn.Open() $cmd = $cn.CreateCommand() $cmd.CommandText = "SELECT * FROM [Sheet1$]" $rdr = $cmd.ExecuteReader() $dt = new-object System.Data.DataTable $dt.Load($rdr) $dt | Out-GridView ``` Please note that this script reads data from Excel using SQL,but it doesn’t extract SQL queries stored in Excel. If you have SQL queries stored in cells of an Excel sheet and you want to extract them, you would need to adjust the script to select those specific cells.
Saturday, September 9, 2023
Get Team chat details using Microsoft.Graph
---- 1. Install-Module Microsoft.Graph 2. Connect MicrosoftGraph API Module 3. Get chat id using Get-MgChat commandlet 4. Get Chat member for particular chat id using Get-MgChatMember 5. Get chat messages\Chat history for particular chat using Get-MgChatMessage ```sh Install-Module Microsoft.Graph Import-Module Microsoft.Graph Connect-MgGraph <# "Get-MgChat" ,"Get-MgChatMember","Get-MgChatMessage" | & {Process{Find-mggraphcommand Get-MgChat|select permissions| &{Process{Connect-MgGraph -Scopes $_}} }} #> $displayName="< Display Name>" $user=Get-MgUser -Filter "DisplayName eq '$displayName'" Get-MgChat | select Topic,ChatType,id,WebUrl $chatID=$(Get-MgChat | select id -First 1).id #Get all Chat members for chat Get-MgChatMember -ChatId $chatID | select AdditionalProperties).AdditionalProperties #Get ACS chat members (Get-MgChatMember -ChatId $chatID |Where DisplayName -eq raz| select AdditionalProperties).AdditionalProperties #Get AAD chat members (Get-MgChatMember -ChatId $chatID |Where DisplayName -eq 'razesh'| select AdditionalProperties).AdditionalProperties #Get chat messages for chat id Get-MgChatMessage -ChatId $chatID |& {Process{ if ($($_.From.User.DisplayName)) {Write-host "From :$($_.From.User.DisplayName)" ;"Message:$($_.body.Content)"; Write-Host ""}}} ```
Invoke Microsoft Graph API endpoint using accesstoken in az cli
---- To get an access token for Graph API call, you can follow the steps below: Go to the Azure portal and sign in to your account. Navigate to the Azure Active Directory resource that you want to use. 1. Click on the App registrations tab. 2. Select the app that you want to use. 3. Click on the Certificates and secrets tab. 4. Click on the New client secret button. 5. Enter a description for the client secret and select an expiration date. 6. Click on the Add button. 7. Copy the value of the client secret and store it securely. 8 Use the copied client secret value to authenticate your requests. 9. You can use the following code snippet in PowerShell to get an access token: ```sh $tenantId = "< your-tenant-id >" $appId = "<your-app-id >" $clientSecret = "< your-client-secret >" $resource = "https://graph.microsoft.com" $body = @{grant_type="client_credentials";client_id="$appId";client_secret="$clientSecret";resource="$resource"} $oauthUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token" $oauth = Invoke-RestMethod -Method Post -Uri $oauthUrl -Body $body $accessToken = $oauth.access_token # Note: Replace < your-tenant-id >, < your-app-id >, and < your-client-secret > with your own values. ``` ---- Example 1: ```sh $tenantId = "< your-tenant-id >" $appId = "<your-app-id >" $clientSecret = "< your-client-secret >" $resource = "https://graph.microsoft.com" $body = @{grant_type="client_credentials";client_id="$appId";client_secret="$clientSecret";resource="$resource"} $oauthUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token" $oauth = Invoke-RestMethod -Method Post -Uri $oauthUrl -Body $body $accessToken = $oauth.access_token $headers = @{ "Authorization" = "Bearer $accessToken" } $response=Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users" -Headers $headers $response.value | select id , displayname # Note: Replace < your-tenant-id >, < your-app-id >, and < your-client-secret > with your own values. # Note: Need User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All Permissions to access MS graph users API endpoint ``` Example 2: ```sh $tenantId = "< your-tenant-id >" $appId = "<your-app-id >" $clientSecret = "< your-client-secret >" $resource = "https://graph.microsoft.com" $body = @{grant_type="client_credentials";client_id="$appId";client_secret="$clientSecret";resource="$resource"} $oauthUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token" $oauth = Invoke-RestMethod -Method Post -Uri $oauthUrl -Body $body $accessToken = $oauth.access_token $headers = @{ "Authorization" = "Bearer $accessToken" } $response=Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users" -Headers $headers $response. value | select id , displayname (Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/groups?$filter=resourceProvisioningOptions/Any (x:x eq 'Team')" -Headers $headers).value |select id , displayname , mailNickName , mail # Note: Replace < your-tenant-id >, < your-app-id >, and < your-client-secret > with your own values. # Note: Need Group.Read.All, Group.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All Permissions to access MS graph groups API endpoint ``` Example 3: ```sh $tenantId = "< your-tenant-id >" $appId = "<your-app-id >" $clientSecret = "< your-client-secret >" $displayName ="< displayName>" $resource = "https://graph.microsoft.com" $body = @{grant_type="client_credentials";client_id="$appId";client_secret="$clientSecret";resource="$resource"} $oauthUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token" $oauth = Invoke-RestMethod -Method Post -Uri $oauthUrl -Body $body $accessToken = $oauth.access_token $headers = @{ "Authorization" = "Bearer $accessToken" "Content-Type" = "application/json" } $filter='$filter' $uri = "https://graph.microsoft.com/v1.0/users?$filter=displayName eq '$displayName' " $response=Invoke-RestMethod -Uri $uri -Headers $headers $response. value | select id , displayname # Note: Replace < your-tenant-id >, < your-app-id >, and < your-client-secret > with your own values. # Note: Need User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All Permissions to access MS graph users API endpoint ```
How to invoke Azure Management API with Access token using AZ CLI
#### list of steps to invoke Azure Management API with Azure access token using AZ CLI. 1. log into Azure using Az CLI 2. Get access token using account get-access-token 3. add bearer accesstoken as authorization Header 4. Invoke Azure Managment API ```sh az login $subId=(az account list --query "[?isDefault].id" )|ConvertFrom-Json $accesstoken = [string](az account get-access-token | ConvertFrom-Json).accessToken $headers = @{ Authorization = "Bearer $accesstoken" } $url="< Azure Management API >" $r= Invoke-WebRequest -Uri $url -Headers $headers If ($r.StatusCode -eq 200 ) {($r.Content |ConvertFrom-Json).value} # Replace < Azure Management API > with your values ``` Example: ```sh az login $subId=(az account list --query "[?isDefault].id" )|ConvertFrom-Json $accesstoken = [string](az account get-access-token | ConvertFrom-Json).accessToken $headers = @{ Authorization = "Bearer $accesstoken" } $url="https://management.azure.com/subscriptions/$subId/providers/Microsoft.Compute/locations/eastus/runCommands?api-version=2022-11-01" $r= Invoke-WebRequest -Uri $url -Headers $headers If ($r.StatusCode -eq 200 ) {($r.Content |ConvertFrom-Json).value} ``` ________
App Registration in Azure
---- #### Register App using AZ Cli 1. Login into azure using az cli 2. Create azure active directory service principle usign AZ CLI ```sh $AppName="<AppName >" az login $subId=az account list --query "[?isDefault].id" | ConvertFrom-Json az account set --subscription $subid az ad sp create-for-rbac -n $AppName ``` ----- #### Register App using AZ Portal 1. Go to the Azure portal and sign in to your account. 2. Navigate to the Azure Active Directory resource that you want to use. 3. Click on the App registrations tab and click on New registration 4. Enter User-facing Display name and click on Register
Saturday, September 2, 2023
Create Azure Communication identity and token using az cli
### Add the Azure Communication Services extension for Azure CLI by using the az extension command. 1. Add communication extension in az cli (one time activity) 2. Connect to Azure using Az Cli 3. Create Identity using az communication user-identity 4. Issue Identity Token for specific scope (voip, chat) ```sh az extension add --name communication $acsName="< acs-Name >" $resouceGroup="< Resource Group Name >" $connection=az communication list-key --name $acsName --resource-group $resouceGroup --query "primaryConnectionString" $rawId=az communication user-identity user create --connection-string $connection --query "rawId" az communication identity token issue --scope chat voip --user $rawId --connection-string $connection --query "token" Note: #$rawId=az communication identity user create --connection-string $connection --query "rawId" #This command is implicitly deprecated because command group 'communication identity token' is deprecated and will be removed in a future release. Use communication user-identity token' instead. ``` ___ Example : ```sh az extension add --name communication az login $acsName="aztds-acs-poc0821" $resouceGroup="rg-aztds-acs-poc" $connection=az communication list-key --name $acsName --resource-group $resouceGroup --query "primaryConnectionString" $rawId=az communication user-identity user create --connection-string $connection --query "rawId" az communication identity token issue --scope chat voip --user $rawId --connection-string $connection --query "token" ```
Get Teams User's Availability using Microsoft Graph API
Get Teams User's Availability using Microsoft Graph API through Invoke-RestMethod ```sh # Import the required modules Install-Module -Name AzureAD Install-Module MicrosoftTeams Import-Module AzureAD Import-Module MicrosoftTeams # Connect to Azure AD Connect-AzureAD # Get an access token for the Graph API $accessToken = (Get-AzureADToken -Resource "https://graph.microsoft.com").AccessToken # Set the Graph API endpoint URL $graphApiUrl = "https://graph.microsoft.com/v1.0/users//presence" # Set the headers for the request $headers = @{ "Authorization" = "Bearer $accessToken" } # Send the request to the Graph API and get the response $response = Invoke-RestMethod -Method Get -Uri $graphApiUrl -Headers $headers # Output the presence status of the user $response.availability ```
Get Teams User id using Microsoft Grapth API
Get Teams User id using Microsoft Grapth API ```sh Install-Module Microsoft.Graph # Import the required module Import-Module Microsoft.Graph # Connect to Microsoft Graph Connect-MgGraph # Get the user object for the specified user $user = Get-MgUser -Filter "mail eq '[email protected]'" # Output the user ID $user.Id ```
Post message using Microsoft Graph powershell moduel
Post message using Microsoft Graph powershell moduel <\i>
```sh Install-Module Microsoft.Graph -Scope CurrentUser Install-Module Microsoft.Graph.Beta Import-Module Microsoft.Graph -Scope CurrentUser # Connect to MgGraph Connect-MgGraph Find-MgGraphCommand -command Get-MgUser | Select -First 1 -ExpandProperty Permissions #Grant permission Connect-MgGraph -Scopes "User.Read.All","Group.ReadWrite.All" $user = Get-MgUser -Filter "displayName eq 'Raj'" # Get Teams for user Get-MgUserJoinedTeam -UserId $user.Id # Get Teams for user $TeamId=$(Get-MgUserJoinedTeam -UserId $user.Id).ID $team = Get-MgTeam -TeamId $TeamId # Get Team channel for specific Team $channel = Get-MgTeamChannel -TeamId $team.Id -Filter "displayName eq 'General'" # Post message in specific Team channel New-MgTeamChannelMessage -TeamId $team.Id -ChannelId $channel.Id -Body @{ Content="Hello Teams"} # Post message in specific Team channel New-MgTeamChannelMessage -TeamId $team.Id -ChannelId $channel.Id -Body @{ Content="Hello World" } -Importance "urgent" # DisConnect to MgGraph Disconnect-MgGraph ```
clone git repository with specific branch only
clone git repository with specific branch only
```sh #syntax git clone --single-branch --branch <branch-name > git-url #example git clone --single-branch --branch master https://github.com/career-tutorials/ck.git --progress ```
Re install NPM Packages
Reinstall all NPM Packages
Remove modules under node_modules on Linux or Mac OS ```sh rm -rf node_modules && npm install ``` Remove modules under node_modules on Windows ```sh del /s /q node_modules && npm install ``` Clean modules from cache , rebuild and install packages ```sh npm cache clean --force npm rebuild npm install ``` The npm audit fix command will install any packages that are missing in node_modules but it’s present in package.json ```sh npm audit fix ``` npm update will update any packages that are present in the project. ```sh npm update #so we can run this to reinstall any packages that are missing. ```
Availability of Teams user using Microsoft.Graph and Microsoft.Graph.CloudCommunications communication module
Availability of Teams user using Microsoft.Graph and
Microsoft.Graph.CloudCommunications Poweshell module
```sh #Install Module Install-Module Microsoft.Graph -Scope CurrentUser Install-Module Microsoft.Graph.CloudCommunications #Import Module Import-Module Microsoft.Graph Import-Module Microsoft.Graph.CloudCommunications # Connect to Microsoft Graph Connect-MgGraph # Fina required permission for Get-MgCommunicationPresenceByUserId Find-MgGraphCommand -command Get-MgCommunicationPresenceByUserId | Select -First 1 -ExpandProperty Permissions # Grant scope of access Connect-MgGraph -Scopes "Presence.Read.All","Presence.Read" # get user details using Microsoft Graph $user1 = Get-MgUser -Filter "displayName eq 'Rajesh'" $user2 = Get-MgUser -All | Where-Object {$_.DisplayName -like "*Mark*"} $params = @{ ids = @( $user1.Id $user2.Id ) } # Get Presence by user id #Get-MgCommunicationPresenceByUserId -BodyParameter $params # Get Presence by user id for Availability other than offline ,DoNotDisturb ,BeRightBack, Away Get-MgCommunicationPresenceByUserId -BodyParameter $params | where Availability -NotIn 'Offline','DoNotDisturb','BeRightBack','Away' # Get Presence by user id who are available Get-MgCommunicationPresenceByUserId -BodyParameter $params | where Availability -EQ 'Available' #There is other way Get Presence for user id Get-MgUserPresence -UserId $user1.Id ```
Wednesday, August 30, 2023
Performance of process, CPU Utilization and Memory Utilization for specific system
Performance of each process in the machine
```sh $servername ="Machine1" # update Machine \hostname gwmi Win32_PerfFormattedData_PerfProc_Process -filter "Name <> '_Total' and Name <> 'Idle'" -Computer $servername | where { $_.PercentProcessorTime -gt 0 } | select PSComputerName, Name, PercentProcessorTime | sort PercentProcessorTime -Descending ```CPU Utilization
```sh $serverName ="Machine1" # update Machine \hostname $ProcessorTime = (Get-WmiObject -ComputerName $serverName -Class win32_processor -ErrorAction Stop | Measure-Object -Property LoadPercentage -Average | Select-Object Average).Average $ProcessorTime ```Memory Utilization
```sh $serverName ="Machine1" # update Machine \hostname $ComputerMemory = Get-WmiObject -ComputerName $ServerName -Class win32_operatingsystem -ErrorAction Stop; $MemoryUtilization = ((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize); $RoundMemory = [math]::Round($Memory, 2) $MemoryUtilization ```
Saturday, August 26, 2023
How to get Teams User id using Microsoft Teams Module
We can get Teams user id using MicrosoftTeams powershell module 1.Install MicrosoftTeams Powershell module ```sh # Install Microsoft Team powershell module Get-module *teams* Install-Module -Name MicrosoftTeams Update-Module MicrosoftT ``` 2.Connect to Team Tenant ```sh # Connect to Team Tenant Connect-MicrosoftTeams # It will prompt for AAD Login else # or you can specify credentials through script $credential = Get-Credential Connect-MicrosoftTeams -Credential $credential ``` ` Note :Unfortunately, it is not possible to connect to Microsoft Teams using the Connect-MicrosoftTeams cmdlet with **MFA enabled without using an interactive login**. If you want to automate the process of connecting to Microsoft Teams, you may need to use a service account that does not have MFA enabled or use a different method of authentication, such as using a certificate or an application ID 3.Get group id for Your teams group ```sh $groupid=$(Get-Team -DisplayName 'Your-Teams-Group' |select GroupId) ``` 4.Get teams UserId ```sh $users=$(Get-TeamUser -GroupId $groupid ) $UserID=$(Get-TeamUser -GroupId $groupid | where name -EQ "Your-User-Name").UserID ``` Complete Script ```sh Get-module *teams* Install-Module -Name MicrosoftTeams Update-Module MicrosoftTeams Connect-MicrosoftTeams $groupid=$(Get-Team -DisplayName 'Notifications' |select GroupId).groupid $UserID=$(Get-TeamUser -GroupId $groupid | where name -eq "Raj").UserI ```
Monday, August 21, 2023
Invoke Web request by -passing proxy
We can invoke web request by passing proxy if proxy is configured at windows level ```sh $request=[System.Net.WebRequest]::Create("https://test/v1/healtcheck") $request.Proxy=[System.Net.WebProxy]::new() #blank proxy $response=$request.GetResponse() ```
Tuesday, August 15, 2023
Dotnet SDK installation using package manager CLI in Windows and Linux
#### Install .NET updates using the Windows Package Manager CLI (winget): - Install the .NET 7 sdk ```sh winget install dotnet-sdk-7 ``` - Install the .NET 7 runtime, run ```sh winget install dotnet-runtime-7 ``` - To update an existing installation: ```sh winget upgrade winget upgrade --include-unknown ``` - Install dotnet SDK using packages in Linux ```sh #update all packages before install .net sudo apt update # following command will install dotnet core 2.1, 2.2, 3.0 and 3.1 sudo apt install dotnet-sdk* # following command will install dotnet 6.0 if not able to find package then we can install using manuall steps using below steps sudo apt install dotnet-sdk-6.0 # following command will install dotnet 7.0 if not able to find package then we can install using manuall steps using below steps sudo apt install dotnet-sdk-7.0 #following command will install runtime sudo apt install dotnet-host #following command will upgrade\update dotnet SDK package sudo apt upgrade dotnet-sdk-7.0 #uninstall dotnet SDK packges using apt remove sudo apt-get remove dotnet-sdk-6.0 sudo apt remove dotnet* sudo apt remove netstandard* sudo apt remove aspnetcore* ``` ### Install dotnet 6.0 7.0 SDK in Linux using manual steps ```sh wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh chmod +x ./dotnet-install.sh # following command will install dotnet 6.0 version ./dotnet-install.sh --version latest # following command will install dotnet 7.0 version ./dotnet-install.sh --channel 7.0 #Add below environment variable to add dotnet path in path variable export DOTNET_ROOT=$HOME/.dotnet export PATH=$PATH:$DOTNET_ROOT:$DOTNET_ROOT/tools #Note- add these environment variables in ~/.bashrc ~/.profile to avoid define these variables for each linux instance ``` ### Install dotnet 8.0 preview SDK in Linux using manual steps ```sh # following command will install dotnet 8.0 preview version wget https://download.visualstudio.microsoft.com/download/pr/32f2c846-5581-4638-a428-5891dd76f630/ee8beef066f06c57998058c5af6df222/dotnet-sdk-8.0.100-preview.7.23376.3-linux-x64.tar.gz -O dotnet-sdk-8.0.100-preview.7.23376.3-linux-x64.tar.gz mkdir -p $HOME/.dotnet && tar zxf dotnet-sdk-8.0.100-preview.7.23376.3-linux-x64.tar.gz -C $HOME/.dotnet export DOTNET_ROOT=$HOME/.dotnet export PATH=$PATH:$HOME/.dotnet ``` ### Install project templates using dotnet CLI in windows \Linux ```sh # syntax dotnet new install <TemplateName> # we can install templates for chat bot projects using dotnet cli in windows\linux dotnet new install Microsoft.Bot.Framework.CSharp.CoreBot dotnet new install Microsoft.Bot.Framework.CSharp.EmptyBot dotnet new install Microsoft.Bot.Framework.CSharp.EchoBot # we can install templates for clean Architecture using dotnet cli in windows\linux dotnet new install Ardalis.CleanArchitecture.Template dotnet new install Clean.Architecture.Solution.Template::8.0.0-preview.6.18 # to list of installed templated dotnet new uninstall ``` ### The .NET entity framework is available as a .NET global tool. We can install the tool with the following command in windows \Linux OS ```sh dotnet tool install --global dotnet-ef ``` ### The .NET Upgrade Assistant is also available as a .NET global tool. We can install the tool with the following command in windows \Linux OS ```sh dotnet tool install -g upgrade-assistant ``` - NET Upgrade Assistant is installed as a .NET tool, it can be easily updated by running following command in windows \Linux OS ```sh dotnet tool update -g upgrade-assistant ``` Now we can upgrade existing project to new .net framework ```sh #usage upgrade-assistant upgrade upgrade-assistant upgradeupgrade-assistant upgrade --operation Inplace --targetFramework net6.0 upgrade-assistant upgrade --operation SideBySide --targetFramework LTS --destination ```
Sunday, August 6, 2023
How to get New GUID in bat programming
We can generate new GUID using command let GUID class in Powershell ```sh New-GUID [guid]::NewGuid().ToString() ``` We can leverage invoking poweshell from batch programming ```sh POWERSHELL -COMMAND "$([guid]::NewGuid().ToString())" FOR /F %a IN ('POWERSHELL -COMMAND "$([guid]::NewGuid().ToString())"') DO ( SET NEWGUID=%a ) echo %NEWGUID% ```
How to generate Sequence dates, Random number table in Excel
We can generate sequence Dates using Sequence functions. ```sh #Following is the formula to generate sequence Dates =TEXT(DATE(2024,1,1)+SEQUENCE(1,7,0,1),"DD-mmm-YYYY") #Following is the formula to generate sequence Months =TEXT(DATE(YEAR(TODAY()),MONTH(TODAY())+SEQUENCE(1,7),DAY(TODAY())),"mmm-YYYY") #Following is the formula to generate sequence Years =TEXT(DATE(YEAR(TODAY()+SEQUENCE(1,7)),MONTH(TODAY()),DAY(TODAY())),"YYYY") ``` We can codes\ids with particular number increment ```sh #Following is the formula to generate codes \ids in 5 rows with starts with 1000 and increment of 1000 =SEQUENCE(5,1,1000,1000) #Following is the formula to generate codes \ids in 5 columns with starts with 1001 and increment of 1000 =SEQUENCE(1,5,1001,1000) ``` We can generate table with random numbers ```sh =SEQUENCE(5,5,INT(RAND()*100),INT(RAND()*100)) ```
Saturday, August 5, 2023
How to install dotnet cli in Linux or WSL
1. Download Dotnet-install shell script ```sh wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh chmod +x ./dotnet-install.sh ``` 2. Install latest.NET SDK using dotnet-install.sh ```sh ./dotnet-install.sh --version latest ``` 2.1 Install .NET Runtime instead of the SDK, use the --runtime parameter. ```sh ./dotnet-install.sh --version latest --runtime aspnetcore ``` You can install a specific major version with the --channel parameter to indicate the specific version. The following command installs .NET 7.0 SDK. ``` Bash ./dotnet-install.sh --channel 7.0 ``` 3. Set Environment variables for DOTNET_Root and update Path environment variable ```sh ~/.bashrc export DOTNET_ROOT=$HOME/.dotnet export PATH=$PATH:$DOTNET_ROOT:$DOTNET_ROOT/tools ```
How to call PowerShell command -let or PowerShell script from C#
We can call poweshell command-let from C# ```sh Install Powershell SDK package then Add reference of System.Management.Automation #Install-Package Microsoft.PowerShell.SDK# #dotnet add package Microsoft.PowerShell.SDK ``` Following is the code to invoke powershell command-let ```sh #usings - using System.Management.Automation; using System.Management.Automation.Runspaces; using (PowerShell ps = PowerShell.Create()){ ps.AddCommand("Get-Process"); ps.AddParameter("Name", "excel"); foreach (PSObject result in ps.Invoke()){ Console.WriteLine(result); } } ``` We can call powershell script file from C# ```sh Following is the code to invoke powershell script #usings using System.Management.Automation; using System.Management.Automation.Runspaces; var ps1File = @"C:\Users\\install-scheme.ps1"; var startInfo = new ProcessStartInfo(){ FileName = "powershell.exe", Arguments = $"-NoProfile -ExecutionPolicy ByPass -File \"{ps1File}\"", UseShellExecute = false }; Process.Start(startInfo); ``` We can invoke powershell command-let \cli from C# using CliWrap ```sh #Install Package dotnet add package CliWrap -Version 3.6.4 # Install-Package CliWrap -Version 3.6.4 # using using CliWrap; using CliWrap.Buffered; using System; using System.Threading; using System.Threading.Tasks; var result= await cli.Wrap("powershell") .WithArguments(new[]{"Get-Process"," -Name",\"devenv"}) .ExecuteBufferedASync(); Console.WriteLine(result.StandardOutput); Console.WriteLine(result.StandardError); ``` ```
Friday, August 4, 2023
How to generate sequence id number in Excel
We can generate sequence number using row is haivng data Following is the formula to generate sequence number in A2 column when B2 column ```sh IF(ISBLANK(B2),"",COUNTA(B$2:B2)) # We can also do it with sequence formula , Note 1 is offset if we used first row for header SEQUENCE(COUNTA(B:B)-1) ``` We can do it both COUNTA and Sequence when data in column B is not empty ```sh IF(ISBLANK(B2),"",SEQUENCE(COUNTA(B$2:B2))) # if want to fill the sequence number when entered data in cell Ctrl+G then cick on Special then click on blanks ```
Monday, July 31, 2023
Create nuget package
Nuget package is compressed file with extension *.nupkg extension and this package can be shared to other teams. we can create nuget packages using nuget cli or dotnet cli #### Prerequisites Install [Nuget.exe](https://dist.nuget.org/win-x86-commandline/latest/nuget.exe) CLI dotnet.exe with [DotNet SDK](https://www.microsoft.com/net/download/) #### 1. Generate Manifest (.nuspec) we can generate initial .nuspec file from project ```sh # we can generate .nuspec file from project file nuget spec Logger.csproj #we can generate .nuspec file from project dll as well nuget spec.dll ``` Note: NuGet throws error if you try to create a package with default values in .nuspec file, so you must change the following fields before proceeding. - licenseUrl - projectUrl - iconUrl - releaseNotes - tags #### 2.1 Create Package using nuget cli ```sh # generate package by running nuget pack where cs project located nuget pack # generate package by specifying project location and configuration nuget pack .\Logger\Logger.csproj -properties Configuration=Release # generate package for specifying project and configuration nuget pack Logger.csproj -properties Configuration=Release # generate package for specifying project after building project with build configuration release and include referenced projected if project is using external project references nuget pack Logger.csproj -Build -properties Configuration=Release -IncludeReferencedProjects # Create a package from Logger.csproj, using MSBuild version 12 to build the project and package properties (owner and version) nuget pack Logger.csproj -Build -Symbols -MSBuildVersion 12 -Properties owners=scott,rob;version="1.0.0" #create a package using nuspec file and exclude exe and bat files nuget pack logger.nuspec -exclude "*.exe" -exclude "*.bat" ``` #### 2.2 Create Package using dotnet cli ```sh # generate package by running nuget pack where cs project located dotnet pack # generate package by specifying project location and configuration dotnet pack .\Logger\Logger.csproj -properties Configuration=Release # generate package for specifying project and configuration dotnet pack Logger.csproj -properties Configuration=Release # generate package for specifying project after building project with build configuration release and include referenced projected if project is using external project references dotnet pack Logger.csproj -Build -properties Configuration=Release -IncludeReferencedProjects # Create a package from Logger.csproj, using MSBuild version 12 to build the project and package properties (owner and version) dotnet pack Logger.csproj -Build -Symbols -MSBuildVersion 12 -Properties owners=scott,rob;version="1.0.0" #create a package using nuspec file and exclude exe and bat files dotnet pack logger.nuspec -exclude "*.exe" -exclude "*.bat" ``` #### 3. Publish Package in nuget repository Once .nupkg file is created , you can publish to [nuget repository](https://nuget.org) - Sign into [nuget.org](https://nuget.org) account or create an account if you don't have one already. - Click on your username which is on the upper right, and select API Keys and then on webpage click on Create. ```sh nuget push Logger.1.0.0.nupkg oz5fgepyspx6fzm67guqybyr8vanjboudmner4e1gsy24b -Source https://api.nuget.org/v3/index.json #push package using dotnet cli to the default push source specified in the NuGet config file dotnet nuget push foo.nupkg -k 3003d786-dd37-6004-efef-d4f3e8ef9b3a #push package using dotnet cli to nuget repository dotnet nuget push foo.nupkg -k 6003d786-cc36-6004-efef-d4d3e8ef9b3a -s https://api.nuget.org/v3/index.json ``` #### 3. Publish Package in Nexus repository Once .nupkg file is created , if want to push a NuGet package to a Nexus repository, we can use the nuget push command. This command requires to use the NuGet API Key and the URL of the target hosted repository For example, if your Nexus server is located at http://nexus_server and your repository is named nexus_nuget_repository ```sh nuget push [logger.nupkg] -Source http://nexus_server/repository/nexus_nuget_repository/ -ApiKey [api_key] #push package using dotnet cli to nuget repository dotnet nuget push logger.nupkg -k 6003d786-cc36-6004-efef-d4d3e8ef9b3a -s http://nexus_server/repository/nexus_nuget_repository/ ```
How to install VS code in WSL \ Linux
### Option:1 [install using apt install ] 1. If wget is not installed, please install it using the command 2. if apt-transport-https is not installed then install it using the command ```sh sudo apt-get install wget sudo apt install apt-transport-https ``` 3. Install code package ```sh sudo apt update sudo apt install code # or code-insiders ``` Note: To avoid prompting when open VS code , set DONT_PROMPT_WSL_INSTALL environment variable as 1 ```sh export DONT_PROMPT_WSL_INSTALL=1 #add below variable in ~/.bashrc to avoid adding environment in each instance of wsl distribution alias code='DONT_PROMPT_WSL_INSTALL=1 code' ``` ### Option:2 [Install using VS code debian package] 1. downdload debian package for [VS code installer for linux](https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-x64) 2. Move package to WSL home location ```sh mv /mnt/c/Users//<HostOS-UserId>/Downloads/code_1.80.2-1690491597_amd64.deb /home/<WSL-UserId> ``` 3. Install VS code debian package [code_1.80.2-1690491597_amd64.deb] ```sh sudo apt install ./code_1.80.2-1690491597_amd64.deb ```
Saturday, July 29, 2023
System information
We can get System information using system info utility ```sh # if want to see OS Name OS version and BIOS Version ❯ systeminfo | Select-String "OS Name","OS Version" /*Result*/ OS Name: Microsoft Windows 10 Pro OS Version: 10.0.19045 N/A Build 19045 BIOS Version: HP Q78 Ver. 01.17.00, 8/4/2021 ``` ```sh # if want to see OS Name OS version ❯ systeminfo | Select-String "OS Name","^OS Version" /*Result*/ OS Name: Microsoft Windows 10 Pro OS Version: 10.0.19045 N/A Build 19045 ``` ```sh # if want to see OS Name OS ,version and Hyper-V ❯ systeminfo | Select-String "OS Name","^OS Version" ,"Hyper-V Requirements:" OS Name: Microsoft Windows 10 Pro OS Version: 10.0.19045 N/A Build 19045 Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed. ```
WSL CLI commands
### 1. Version (wsl --version (or) wsl -v ) ```sh # wsl --version (or) wsl -v will provide version of wsl , version of distributions or version of windows PS> wsl --version /*Result */ WSL version: 1.2.5.0 Kernel version: 5.15.90.1 WSLg version: 1.0.51 MSRDC version: 1.2.3770 Direct3D version: 1.608.2-61064218 DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp Windows version: 10.0.19045.3208 ``` ### 2. List (wsl --list (or) wsl -l [Options] Lists distributions. Options: --all List all distributions, including distributions that are currently being installed or uninstalled. --running List only distributions that are currently running. --quiet, -q Only show distribution names. --verbose, -v Show detailed information about all distributions. --online, -o Displays a list of available distributions for install with 'wsl.exe --install'. ```sh ❯ wsl --list /*Result */ Windows Subsystem for Linux Distributions: Ubuntu (Default) SLES-12 ❯ wsl -l /*Result */ Windows Subsystem for Linux Distributions: Ubuntu (Default) SLES-12 ❯ wsl -l --running /*Result */ There are no running distributions. ❯ wsl -l -q /*Result */ Ubuntu SLES-12 ❯ wsl -l -v /*Result */ NAME STATE VERSION * Ubuntu Running 1 SLES-12 Stopped 1 ❯ wsl -l --online /*Result */ The following is a list of valid distributions that can be installed. Install using 'wsl.exe --install'. NAME FRIENDLY NAME Ubuntu Ubuntu Debian Debian GNU/Linux kali-linux Kali Linux Rolling Ubuntu-18.04 Ubuntu 18.04 LTS Ubuntu-20.04 Ubuntu 20.04 LTS Ubuntu-22.04 Ubuntu 22.04 LTS OracleLinux_7_9 Oracle Linux 7.9 OracleLinux_8_7 Oracle Linux 8.7 OracleLinux_9_1 Oracle Linux 9.1 openSUSE-Leap-15.5 openSUSE Leap 15.5 SUSE-Linux-Enterprise-Server-15-SP4 SUSE Linux Enterprise Server 15 SP4 SUSE-Linux-Enterprise-15-SP5 SUSE Linux Enterprise 15 SP5 openSUSE-Tumbleweed openSUSE Tumbleweed ``` ### 3. Run the specified distribution. (wsl -d \ wsl --distribution) ```sh # list all distributions with status > wsl -l -v /*Result */ NAME STATE VERSION * Ubuntu Stopped 1 SLES-12 Stopped 1 > wsl -d SLES-12 /*Result */ /mnt/c/Users/user> ❯ wsl -l -v /*Result */ NAME STATE VERSION * Ubuntu Stopped 1 SLES-12 Running 1 > /mnt/c/Users/user> exit /*Result */ logout ``` ### 4. terminate the specified distribution. (wsl -d \ wsl --distribution) ```sh #wsl --terminate, -t ❯ wsl -t SLES-12 /*Result */ The operation completed successfully. ``` ### 5. Update \ upgrate wsl package ```sh # update wsl package using internet instead of microsoft store > wsl --update --web-download /*Result */ Checking for updates. The most recent version of Windows Subsystem for Linux is already installed. ``` ### 6. Set WSL version 2 ```sh > wsl --set-default-version 2 /*Result */ For information on key differences with WSL 2 please visit https://aka.ms/wsl2 The operation completed successfully. ``` ### 7. Changes the version of the specified distribution. ```sh > wsl --set-version SLES-12 2 /*Result */ For information on key differences with WSL 2 please visit https://aka.ms/wsl2 Conversion in progress, this may take a few minutes. The operation completed successfully. > wsl -l -v /*Result */ NAME STATE VERSION * Ubuntu Stopped 1 SLES-12 Stopped 2 > wsl --set-version ubuntu 2 /*Result */ For information on key differences with WSL 2 please visit https://aka.ms/wsl2 Conversion in progress, this may take a few minutes.... The operation completed successfully. > wsl -l -v /*Result */ NAME STATE VERSION * Ubuntu Stopped 2 SLES-12 Stopped 2 ``` ### 8. unregister the specified distribution ```sh #Unregisters the distribution and deletes the root filesystem. #wsl --unregister > wsl --unregister SLES-12 ``` ### 9. WSL SEr ```sh > wsl --status /*Result */ Default Distribution: Ubuntu Default Version: 2 ```
RunAS
When open application in windows. Application will run under logged-in user context if want to run application under other than logged in user context from command prompt ```sh runas /user:"Domain\Users" "powershell" ``` To start the process, command, or app under other than logged in user context from powershell ```sh $cred = (Get-Credential) Start-Process -FilePath "Ssms.exe" -Credential $cred Start-Process -FilePath "powershell" -Credential $Cred ``` if you can get user credentials interactively through Windows Security prompt ```sh # Run as Administrator Start-Process -FilePath "powershell" -Verb RunAs # Run as from another user Start-Process -FilePath "ssms " -Verb RunAsUser ```
Thursday, July 27, 2023
Merge Hashtables in Powershell
We can merge hashtables and perform some operations on merged hashtable ```sh #Function is used to merge hashtables. function Merge-Hashtables([ScriptBlock]$Operator) { $Output = @{} ForEach ($hashtable in $input) { If ($Hashtable -is [Hashtable]) { ForEach ($key in $hashtable.Keys) {$Output.$key = If ($Output.ContainsKey($key)) {@($Output.$key) + $hashtable.$key} Else {$hashtable.$key}} } } If ($Operator) {ForEach ($Key in @($Output.Keys)) {$_ = @($Output.$Key); $Output.$Key = Invoke-Command $Operator}} $Output } # Usage $hash1 = @{ Number = 1; Shape = "Rectangle"; Color = "Blue"} $hash2 = @{ Number = 2; Shape = "Square"; Color ="Red"} $hash3 = @{ Number = 3; Shape = "Circle"; Color ="Green"} ``` ### Example-1 ``` sh $hash1,$hash2,$hash3 | Merge-Hashtables #Result Name Value Color {Blue, Red, Green} Shape {Rectangle, Square, Circle} Number {1, 2, 3} ``` ### Example-2 ``` sh $hash1,$hash2,$hash3 |Merge-Hashtables {$_ -join ","} #Result Name Value ---- ----- Color Blue,Red,Green Shape Rectangle,Square,Circle Number 1,2,3 ``` ### Example-3 ```sh $hash1,$hash2,$hash3 | Merge-Hashtables {$_ | Sort-Object} #Result Name Value ---- ----- Color {Blue, Green, Red} Shape {Circle, Rectangle, Square} Number {1, 2, 3} ``` ### Example-4 ```sh $hash1,$hash2,$hash3 | Merge-Hashtables {$_ | Select -First 1} #Result Name Value ---- ----- Color Blue Shape Rectangle Number 1 ``` ### Example-5 ```sh $hash1,$hash2,$hash3 | Merge-Hashtables { $_ | Select -First 2} #Result Name Value ---- ----- Color {Blue, Red} Shape {Rectangle, Square} Number {1, 2} ```
Get assembly details using PowerShell
#### We can get details of assembly\dll using powershell ```sh $AppBin="c:\<appPath>\<bin>" Get-ChildItem -Path $AppBin -Filter *.dll -Recurse | &{Process { try { $AssemblyInfo=[Reflection.AssemblyName]::GetAssemblyName($_.FullName) $_ | Add-Member NoteProperty FileVersion ($_.VersionInfo.FileVersion) $_ | Add-Member NoteProperty AssemblyVersion ($AssemblyInfo.Version) $_ | Add-Member NoteProperty Flags ($AssemblyInfo.Flags) $_ | Add-Member NoteProperty CultureName ($AssemblyInfo.CultureName) $_ | Add-Member NoteProperty FullyQualifiedName ($AssemblyInfo.FullName) $_ | Add-Member NoteProperty PublicKeyToken ($AssemblyInfo.GetPublicKeyToken()) } catch {}, $_ }} | Select Name,FileVersion,AssemblyVersion ,Flags,CultureName,FullyQualifiedName,PublicKeyToken # otherway around $AppBin="c:\<appPath>\<bin>" Get-ChildItem -Path $AppBin -Filter *.dll -Recurse | Select-Object Name ,@{n='FileVersion';e={$_.VersionInfo.FileVersion}} ,@{n='AssemblyVersion';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).Version}} ,@{n='Flags';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).Flags}} ,@{n='CultureName';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).CultureName}} ,@{n='FullyQualifiedName';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).FullName}} ,@{n='PublicKeyToken';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).GetPublicKeyToken()}} ``` #### Get details of assemblies loaded in the current powershell session ```sh [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object Location | Sort-Object -Property FullName | Select-Object -Property FullName , Location , GlobalAssemblyCache , IsFullyTrusted | Out-GridView ```
Wednesday, July 26, 2023
WSL file system and access Host OS file system from WSL
Access Host OS file system from WSL distribution ```sh /mnt/c/users/<HostOS-UserId> ``` WSL home path ```sh /home /<WSL-UserId> ``` Access WSL installed distribution location from Host OS (Windows) ```sh \\wsl$\ \\wsl$\<distribution-name> ```
Configuring a proxy for WSL
Guest OS (WSL) is not able to connect to undleying internet of Host OS (Windows) when we connect to VPN in the Host OS (Windows) Before configuring Proxy in guest OS (WSL). First we need to perform communication check whether Guest OS (WSL) and Host OS are communicating each other not - Communication check between Guest OS and Host OS<\u> 1. To know IPV4 Address of Ethernet Adapter for WSL, type ipconfig (or) ipconfig /all in command shell of Host OS. 2. To know Ip address of proxy , type pingin command shell of Host OS 3. to know ip address of WSL , type , hostname -I (or) ifconfig in guest OS (WSL) Then 1. Ping ip address of WSL from Host OS ( ex: Ping <ip-Address-of-WSL>). if packets are transferred and received successfully then it means HostOS is able to communicate with Guest OS (WSL) 2. ping IPV4 Address of Ethernet Adapter for WSL and ping Ip address of proxy from Guest OS (WSL) . if packets are transferred and received successfully then it means Guest-OS (WSL) is able to communicate with Host-OS. if both are communicating each other then follow below steps to configure proxy in WSL. ### Proxy DNS name resolution in Guest OS ```sh # To resolve proxy dns name in Guest OS , add proxy ip address and dns names of proxy in /etc/hosts sudo nano /etc/hosts #Add below text with proper ip address and dns names of Proxy #xxx.xx.xx.xx proxy.example.com proxy-dev.example.com ``` ### Add proxy configuration in /etc/apt/apt.conf.d/proxy.conf file for execute apt-get , apt install command with internet ```sh #Open /etc/apt/apt.conf.d/proxy.conf in nano editor. note: use vi editor sudo nano /etc/apt/apt.conf.d/proxy.conf Acquire::http::proxy http://proxy.example.com:7007; Acquire::ftp::proxy http://proxy.example.com:7007; Acquire::https::proxy http://proxy.example.com:7007; #Note: Please use correct proxy URL and port number #if proxy configuration is enable in proxy.conf . no need to add proxy config in apt.conf else you can add . this configuration will be used by apt command sudo nano /etc/apt/apt.conf Acquire::http::proxy http://proxy.example.com:7007; Acquire::ftp::proxy http://proxy.example.com:7007; Acquire::https::proxy http://proxy.example.com:7007; #Note: Please use correct proxy URL and port number # then you can upgrade packages and install new packages using apt cli #example #sudo apt-get update -y #sudo apt install ipmiutil #sudo apt install dotnet-host #sudo apt install net-tools ``` To avoid updating proxy configuration in conf file by restarting WSL. You can add proxy configuration in profile ```sh sudo nano ~/.profile export https_proxy=http://proxy.example.com:7007 export http_proxy=http://proxy.example.com:7007 #Note: Please use correct proxy URL and port number #To avoid restarting the WSL you can run the command: source ~/.profile ``` ### Below is the proxy configuration for wget command ```sh sudo nano ~/.wgetrc http_proxy=http://proxy.example.com:7007 https_proxy=http://proxy.example.com:7007 use_proxy=on #Note: Please use correct proxy URL and port number ``` ### Below is the proxy configuration for git ```sh git config —-global http.proxy http://proxy.example.com:7007 ``` ### Below is the proxy configuration for git ```sh npm set proxy http://proxy.example.com:7007 npm set https-proxy http://proxy.example.com:7007 ```
Tuesday, July 25, 2023
Upload and Download files.
The Start-BitsTransfer cmdlet creates a Background Intelligent Transfer service (BITS) transfer job to transfer one or more files between a client computer and server. ### 1.following command will create BITS transfer job that downloads a file from server ```sh Start-BitsTransfer -Source "http://server/test/file1.txt" -Destination "C:\clientdocs\testfile1.txt" #or Start-BitsTransfer "http://server/test/file1.txt" "C:\clientdocs\testfile1.txt" ``` ### 2.following command will create BITS transfer job that upload a file to server ```sh Start-BitsTransfer -Source "C:\docs\testfile1.txt" -Destination "http://server/test/file1.txt" -TransferType Upload #or Start-BitsTransfer "C:\docs\testfile1.txt" "http://server/test/file1.txt" -TransferType Upload ``` ### 3.following command will create BITS transfer jobs that download multiple files ```sh Import-CSV filesToDownload.txt | Start-BitsTransfer -Asynchronous -Priority Normal #Note: The content of the filesToDownload.txt resemble the following information <# Source , Destination "http://server/test/file1.txt","C:\clientdocs\testfile1.txt" "http://server/test/file2.txt","C:\clientdocs\testfile2.txt" "http://server/test/file2.txt","C:\clientdocs\testfile2.txt" #># ``` ### 4.following command will create BITS transfer jobs that download multiple files. ```sh Start-BitsTransfer -Source "C:\docs\*.log" -Destination "\\server1\docs\" -TransferType Download ``` ### 5.following command will create BITS transfer jobs that download multiple files ```sh Import-CSV filestoUpload.txt |Start-BitsTransfer -TransferType Upload #Note: The content of the files.txt resemble the following information <# Source , Destination "C:\clientLogs\testfile1.log" , "http://server/logs/file1.log" "C:\clientLogs\testfile2.log" , "http://server/logs/file2.log" "C:\clientLogs\testfile2.log" , "http://server/logs/file2.log" #> ```
Monday, July 24, 2023
Chocolatey Package Manager
Chocolatey is a package manager for Windows that allows you to install software packages from the command line. It is similar to apt-get on Linux ### Installation of Chocolatey package CLI ```sh Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) ``` ### Install software package using Chocolatey CLI. We can install software packages in Windows using choco CLI Syntax ```sh choco install``` Examples ```sh choco install keeweb <# install keeweb package using choco CLI #> choco install visualstudio2019-workload-python <# install VS 2019 template to python development#> ``` ### List out installed chocolatey packages in the windows system. Syntax ```sh choco list ``` ### Uninstall software package using Chocolatey CLI. We can install software packages in Windows using choco CLI Syntax ```sh choco uninstall ``` Examples ```sh choco uninstall keeweb <# uninstall keeweb package using choco CLI #> choco uninstall visualstudio2019-workload-python <# uninstall VS 2019 template to python development#> ``` ### Upgrade software package using Chocolatey CLI. We can upgrade software packages in Windows using choco CLI Syntax ```sh choco upgrade ``` Examples ```sh choco upgrade keeweb <# upgrade keeweb package using choco CLI #> choco upgrade visualstudio2019-workload-python <# upgrade VS 2019 template to python development#> choco upgrade chocolatey <# upgrade chocolatey package #> choco upgrade notepadplusplus googlechrome atom 7zip <# upgrade notepadplusplus,googlechrome ,atom,7zip packages #> choco upgrade all --except="skype,conemu" <# will upgrade all packages except for Skype and ConEmu #> ```
How to log message using Select query in SQL and Print statement
Sometimes , Its not easy to write log\print messages for DML operations on set of rows in table.
We can use store text in xml using select query and print messages for logging when performing DML operations on set of rows in table ```sql Declare @NewLine As char(2) = char(13)+ char(10) ,@empty as char(1)='' ,@xmltext as xml, ,@CurrentTimp as DateTime =Current_timestamp ,@CurrentUser as Varchar(20) =Current_User ,@ActivityID =12; Declare @folios as table ( ID INT Identity(1,1),PortfolioId int, Name Varchar (10) , UserName varchar(15) , SSN Char(9)) Insert @folios Select PortfolioId,Name, UserName,SSN,IsActive from Portfolio (nolock) Pf where pf.IsActive=0 and pf.SSN not like '000%' BEGIN Try BEGIN Transaction Update Portfolio Set IsActive =1 from @folios fol join Portfolio (nolock) Pf on pf.PortfolioId=fol.PortfolioId if (@@rowcount >0 ) Begin Insert into AuditLog(ActivityID ,Message ,AcivityTimeStamp ,User) Select @ActivityID ,'Portfolio -'+pf.Name+ 'has been active for user '+ pf.UserName +' with SSN '+ STUFF(pf.SSN,1,5,'XXX-XX-') , @CurrentTimp , @CurrentUser From @folios Select @xmltext =(Select 'Portfolio -'+pf.Name+ 'has been active for user '+ pf.UserName +' with SSN '+ STUFF(pf.SSN,1,5,'XXX-XX-') From @folios [temp] for XML Auto) PRINT Replace(Replace(Convert(NVARCHAR(MAX) ,@xmltext),'<temp txt="',@empty),'/<',@NewLine) END Commit Transaction END TRY Begin Catch Select Error_Number() as ErrorNumber , Error_Message() as ErrorMessage; if (XACT_State())=-1 Begin Print N 'The Transaction is in an uncommittable state. Rolling back transaction.' Rollback Transaction; End if (XACT_STATE())=1 Begin PRINT N'The Transaction is committable. Committing transaction.' COMMIT Transaction End End Catch ```
Sunday, July 23, 2023
How to use crypto currency value using CryptoFinance extension
Go to Extensions > Add-ons > Get Add-Ons Search for CryptoFinance in Marketplace and install ``` Syntax =CRYPTOFINANCE(Curryticker) Usuage \Examples : =CRYPTOFINANCE("DOGEUSD") =CRYPTOFINANCE("ETHUSD") =CRYPTOFINANCE("BTCUSD") ```
Wednesday, July 19, 2023
Azure Functions Core Tools -Installation
1. install using [MSI](https://go.microsoft.com/fwlink/?linkid=2174087) 2. install using npm ```sh npm i -g azure-functions-core-tools@4 --unsafe-perm true ``` 3. install using chocolatey ```sh choco install azure-functions-core-tools ``` 4. install using winget ```sh winget install Microsoft.AzureFunctionsCoreTools ``` 5. Set up package feed in Linux machine ``` sh # Setup package feed wget -q https://packages.microsoft.com/config/ubuntu/19.04/packages-microsoft-prod.deb sudo dpkg -i packages-microsoft-prod.deb # install sudo apt-get update sudo apt-get install azure-functions-core-tools-4 ```
Compress and Expand archive files.
- We can compress files into archive file using ps script. ```sh # Example $compress = @{ Path = "C:\Reference\Readme-draft.md", "C:\Users\Downloads\*.pdf" CompressionLevel = "Fastest" DestinationPath = "C:\Archives\Draft-docs.zip" } Compress-Archive @compress ``` - We can expand archive file using ps script. ```sh #Example-1 Expand-Archive -LiteralPath 'C:\Downloads\Azure.Functions.Cli.min.win-x64.4.0.4865.zip' ` -DestinationPath C:\Users\rkolla\Downloads\Azure.Functions.Cli.min.win-x64.4.0.4865 #Example-2 Expand-Archive -LiteralPath 'C:\Downloads\node-v18.17.0-win-x64.zip' ` -DestinationPath C:\Users\rkolla\Downloads\node-v18.17.0-win-x64 ```
Tuesday, July 18, 2023
Tips for Excel
1. We can set auto row width and auto column width in the excel ```sh # Ctrl+A - Select all columns (or) select particular area (set of column & rows) # Alt+H+O+A - Set Auto Row Height # Alt+H+O+I - Set Auto Column Width ``` 2. We can apply filters for table data in Excel spreadsheet ```sh # Ctrl+A - Select all columns (or) select particular area (set of column & rows) # Alt+H+S+F - Apply Filters ``` 3. We can apply boards to shell in Excel spreadsheet ```sh # Ctrl+A - Select all columns (or) select particular area (set of column & rows) # Alt+H+B+A - Apply all boarders ``` <\pre>
How to insert convert Comma\tab separated text into table
We can insert \convert comma(or) tab separted text into table ```sh # Ctrl+A - Select text to insert into table . # Alt+N+T+I - Convert into table. ``` <\pre>
View IIS logs in grid view mode
We can view today's iis logs in grid view mode using below ps script. ```sh $IISLogs ="C:\\InetPub\\Logs\\LogFiles\\W3SVC1\\" $Today=$(Get-Date -F 'yyMMdd') Function Out-GridViewIISLog ($File) { $Headers = @((Get-Content -Path $File -ReadCount 4 -TotalCount 4)[3].split(' ') | Where-Object { $_ -ne '#Fields:' }); Import-Csv -Delimiter ' ' -Header $Headers -Path $File | Where-Object { $_.date -notlike '#*' } | Out-GridView -Title "IIS log: $File"; }; Out-GridViewIISLog -File $(Join-path $IISLogs "u_ex.$Today.log") ```
Tuesday, June 27, 2023
Windows Subsystem for Linux (WSL)
Here are the installation Steps for Windows Subsystem for Linux (WSL). ## 1. Enable the Windows Subsystem for Linux ### 1.1 You should first enable the "Windows Subsystem for Linux" optional feature before installing any Linux distributions on Windows. > Open Powershell in Adminstrative mode and execute below command to enable WSL feature ```sh dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart ``` ### 1.2 To update to WSL 2 , Machine should have window 10 or Windows 11 > For x64 systems: Version 1903 or later, with Build 18362.1049 or later. > For ARM64 systems: Version 2004 or later, with Build 19041 or later. ### 1.3 Enable Virtual Machine Feature > Open Powershell in Adminstrative mode and execute below command to enable virtual machine feature. ```sh dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart ``` ### 1.4 Download the Linux kernel update package Download the latest package : [WSL2 Linux kernel update package for x64 machines](https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi) Once downloaded Linux kernal update package from above link then double click to run with elevated permissions. ### 1.5 Set WSL 2 as a default version Open PowerShell and run this command to set WSL 2 as the default version when installing a new Linux distribution ```sh wsl --set-default-version 2 ``` ## 2. Installation steps for WSL (Windows Subsystem for Linux) Terminal ### 2.1. We can install WSL Terminal using chocolatey Package manager. if chocolatey Package manager CLI is not installed in your machine . > Please execute below powershell commands in Powershell ISE (Adminstrative mode) ```sh Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) ``` ### 2.2. Need to install dependecy package( Microsoft.VCLibs.x64.14.00.Desktop.appx) > Execute below powershell commands in Powershell ISE (Adminstrative mode) to install dependecy package( Microsoft.VCLibs.x64.14.00.Desktop.appx) ```sh $packageURL=https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx ## https://aka.ms/Microsoft.VCLibs.x86.14.00.Desktop.appx URL for X86 version of VCLibs.x86.14.00.Desktop package. $pageName= Split-Path -Leaf $packageURL $packagePath = "$env:TEMP\$pageName" (New-Object System.Net.WebClient).DownloadFile($packageURL, $packagePath) Add-AppxPackage $packagePath Remove-Item $packagePath ``` ### 2.3. Now We can install WSL (Windows Subsystem for Linux) Terminal using below commands with the help of choco package manager CLI > Execute below powershell commands in Powershell ISE (Adminstrative mode) to install - WSL Terminal. ```sh choco install -y microsoft-windows-terminal --version 1.12.10732.0 -force choco upgrade microsoft-windows-terminal -y ``` > 2.4. Reboot machine > 2.5. serach for Terminial ## 3. Installation steps for install Ubuntu os on WSL in Windows Machine. we can see list of WSL Distributions already installed in your machine or Open the Microsoft Store and select your favorite Linux distribution. ```sh wsl --list Output : Windows Subsystem for Linux Distributions: Ubuntu (Default) ``` If you are allowed to install WSL distributions from Microsoft store then we can see list of available WSL distributions list and install linux distribution using "wsl --install -d" ```sh wsl --list --online Output: The following is a list of valid distributions that can be installed using 'wsl --install -d '. NAME FRIENDLY NAME Ubuntu Ubuntu Debian Debian GNU/Linux kali-linux Kali Linux Rolling Ubuntu-18.04 Ubuntu 18.04 LTS Ubuntu-20.04 Ubuntu 20.04 LTS Ubuntu-22.04 Ubuntu 22.04 LTS OracleLinux_7_9 Oracle Linux 7.9 OracleLinux_8_7 Oracle Linux 8.7 OracleLinux_9_1 Oracle Linux 9.1 SUSE-Linux-Enterprise-Server-15-SP4 SUSE Linux Enterprise Server 15 SP4 openSUSE-Leap-15.4 openSUSE Leap 15.4 ``` > Example wsl --install -d Ubuntu However, Most of the organization will not provide access to Microsoft store so We can install WSL ubuntu distribution using AppxPackage. > 3.1 if you want to install Ubuntu distribution using AppxPackage , Execute below powershell command in powershell-ISE (in Admintrative mode) ```sh Invoke-WebRequest -Uri https://aka.ms/wslubuntu2004 -OutFile Ubuntu.appx -UseBasicParsing Add-AppxPackage .\Ubuntu.appx $userenv = [System.Environment]::GetEnvironmentVariable("Path", "User") [System.Environment]::SetEnvironmentVariable("PATH", $userenv + "; C:\Users\Administrator\Ubuntu", "User") #Note : If you are using Windows server, or run into problems running the command above you can find the alternate install instructions on the Windows Server documentation page to install the .appx file by changing it to a zip file. ``` |Distribution links | |----------------------| |[Ubuntu](https://aka.ms/wslubuntu)| |[Ubuntu 22.04 LTS](https://aka.ms/wslubuntu2204)| | [Ubuntu 20.04](https://aka.ms/wslubuntu2004| |[Ubuntu 20.04 ARM](https://aka.ms/wslubuntu2004arm)| |[Ubuntu 18.04](https://aka.ms/wsl-ubuntu-1804)| |[Ubuntu 18.04 ARM](https://aka.ms/wsl-ubuntu-1804-arm)| |[Ubuntu 16.04](https://aka.ms/wsl-ubuntu-1604)| |[Debian GNU/Linux](https://aka.ms/wsl-debian-gnulinux)| |[Kali Linux](https://aka.ms/wsl-kali-linux-new)| |[Kali Linux](https://aka.ms/wsl-kali-linux-new)| |[SUSE Linux Enterprise Server 12](https://aka.ms/wsl-sles-12)| |[SUSE Linux Enterprise Server 15 SP2](https://aka.ms/wsl-SUSELinuxEnterpriseServer15SP2)| |[SUSE Linux Enterprise Server 15 SP3](https://aka.ms/wsl-SUSELinuxEnterpriseServer15SP3)| |[openSUSE Tumbleweed](https://aka.ms/wsl-opensuse-tumbleweed)| |[openSUSE Leap 15.3](https://aka.ms/wsl-opensuseleap15-3)| |[openSUSE Leap 15.2](https://aka.ms/wsl-opensuseleap15-2)| |[Oracle Linux 8.5](https://aka.ms/wsl-oraclelinux-8-5)| |[Oracle Linux 7.9](https://aka.ms/wsl-oraclelinux-7-9)| |[Fedora Remix for WSL](https://github.com/WhitewaterFoundry/WSLFedoraRemix/releases/)|| > 3.2. Reboot machine and seach for ubuntu app > 3.3 Connect to Ubuntu Linux distribution from WSL terminial Open WSL and click on (+) new tab select Ubuntu linux distribution > 3.4 Reset password for user /Forgot password To change password for user in Linux distribution (WSL) . We can type "passwd" then it will prompt for current password , new password ,Re-enter Password > 3.5 connect to ubuntu with root user ```sh ssh <user>@<HostName> ``` > 3.6 update/upgrade package ```sh apt list --upgradable sudo apt update sudo apt upgrade ```
Merge multiple files
### Following code snippet is used to merge multiple fiels ```sh $Logpaths=("D:\Logs\App1\*.txt","D:\Logs\*.log","D:\MsgLog\*.log","D:\ErrorLog\*.log") Get-Content $Logpaths |Set-content "D:\Logs\merge_log.txt" ```
Tuesday, May 2, 2023
How to show no of items per every hour
### Following SQL Query used to report Hourly items and repot details of last n hour(s) data ```SQL SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED Declare @FromPastXhour int=1 /*Common Table Expression */ ; With cte As( Select Item Select S.Product_id, p.Name, isnull(s.Quantity,0), isnull(s.Price,0.00) , (isnull(s.Quantity,0)* isnull(s.Price,0.00) ) as Total, dateadd(hh,datediff(hh,'20010101',s.SaleDateTime),'20010101') as Hourly from Product p join Sale s on p.id = s.product_id and s.SaleDateTime >= Cast(GetDate() as Date) ) Select * into #list from cte /*No of product items per hour */ Select Hourly, Name from #list group by [Hourly],[Name] order by 1 /*product and sales details since last x hour(s)*/ select * from #list where SaleDateTime> DateAdd(hh,-1*@FromPastXhour,Getdate()) /*Reporting on all days*/ select cast(SaleDateTime as date), total from Sale (nolock) group by cast(SaleDateTime as date) order by 1; if Object_ID('tempdb..#list') is not null Drop table #list ```
Monday, May 1, 2023
How to load hash table from file in PowerShell script
### We can defne hashtabe in file and load that hashtable from file in PS , we can use this hashtable as configuration information.
Following PS_Utility.psd1 manifestfile is having hashtable. ```sh @{ # Script module or binary module file associated with this manifest. RootModule = 'PS-Utility.psm1' # Version number of this module. ModuleVersion = '1.0.0' # Supported PSEditions # CompatiblePSEditions = @() # Description of the functionality provided by this module Description = '' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '' # Name of the Windows PowerShell host required by this module PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @() # Assemblies that must be loaded prior to importing this module RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @("Convert-ToHashTable" , "Get-ConfigValues" , "Get-Parent" , "Get-Servers" , "Get-UtilityScriptPath" , "Convert-ToList" , "Convert-ToString" , "New-ItemIfNotExits" , "Test-ChangeTransactionID" , "Initialize-Logging" , "Get-ErrorLog" , "Get-MessageLog" , "Write-Error" , "Write-Message" , "Write-Failure" , "Write-Success" , "Get-TranscriptRunningState" , "Set-TranscriptRunningState" , "Initialize-SendEmail" , "Send-Email" ) } ``` Following code can read manifest PS-Utility.psd1 file and load into Powershell session ```sh $ManifestFile =".\PS-Utility.ps1" if (Test-Path $ModuleName){ $ModuleConfig=(Invoke-Expression $(Get-Content $ManifestFile | out-string )) $RootModule=$ModuleConfig["RootModule"] $ModuleConfig["FunctionsToExport"] |&{Process{ $_}} } ```
Thursday, April 27, 2023
Linux Basic Commands
## 1. User Environment
Details | commands | Remarks |
---|---|---|
loggedInUser | whoami | |
Current User | id | |
Current directory | Pwd | |
List of files \directories | ls ls -lr ls -ltr |
Details | commands | Remarks |
---|---|---|
System login processes | who -l who -l -H | |
Count all login names and number of users logged on | who -q -H who -H | |
Display the current run level | who -r | |
Display system boot level | who -b | who -b -r |
Display all information | who -a |
-a : Same as -b -d –login -p -r -t -T -u -b Time of last system boot -d Print dead processes -H Print line of column headings -l Print system login processes -m Only hostname and user associated with stdin -p Print active processes spawned by init -q All login names and number of users logged on -r Print current runlevel -t Print last system clock change -T Add user’s message status as +, – or ? -u List users logged in |
## 2. File Management:
Details | Commands | Remarks |
---|---|---|
Create directory | mkdir testdir | |
Copy files | cp ./dir/ ./dir2/ | cp file.doc newfile.doc cp main.cs demo.html lib.vb backup cp main.c demo.h lib.c /home/project/backup/ #Preserve file attributes cp -p filename /path/to/new/location/myfile #Copy all files in backup folder cp * /home//backup #Copy all doc files in backup folder cp *.doc /home/backup #Copy all files recursively in backup folder cp -R * /home/backup #Copy file command with interactive option cp -i foo bar # Verbose output with cp command cp -v file1 file2 -r - recursive -v - verbose |
Copy files & directories recursively | cp ./dir/ ./dir2/ -r | -r - recursive -v - verbose |
Move files | mv ./file1 ./dir1/ | -r - recursive -v - verbose |
Rename files | mv ./file1 ./file2 | -r - recursive -v - verbose |
Move files from one directory to other directory | mv ./dir1 ./dir2 | -r - recursive -v - verbose |
Delete files | rm ./filename rm ./filename1 ./filename2 ./filename3 rm *.pdf | -r - recursive -v - verbose |
Delete directories | rmdir ./dirName/ | -r - recursive -v - verbose -i confirmation |
To view content of file | cat filename | cat file cat /path/file |
To create a file called “test.txt” | cat > test.txt | ##Type following test files and press Ctrl+D at the end of the file This is a line1 in test file. This is a line2 in file. ## press control-D cat test.txt |
To view big files using shell filters (more, less) | cat dwh-log.log | more cat dwh-log.log | less | more dwh-log.log less dwh-log.log |
To combine two or more files | cat test1.txt test2.txt > test-log.txt cat test-log.txt | |
To view file with line numbers | cat -n test1.txt cat -number test1.txt | |
To display TAB characters as ^I | cat -T test.txt | |
To display $ at end of each line, | cat -E test.txt cat --show-ends test.txt | |
Use ^ and M- notation, except for LFD and TAB and show all nonprinting | cat -v test.txt cat --show-nonprinting testfile.txt | |
To show all | cat -A test.txt cat --vET test.txt | |
View all files in directory | cat * cat *.cs | |
joining binary files | cat file1.bin file2.bin file3.bin > large.tar.gz ### extract it tar -zxvf large.tar.gz | |
To show all | cat -A test.txt cat --vET test.txt |
### 2.1 finding lines using cat , sed and awk commands:
Details | Commands | Remarks |
---|---|---|
Read last 100 lines of the file | cat {filename} | tail -100 tail -100f {filename} | Example: cat hugfile.txt| tail -100 tail -100f hugfile.txt |
Read first 100 lines of the file | cat {filename} | head -100 head -100f {filename} | Example: cat hugfile.txt | head -100 head -100f hugfile.txt |
Print \Read nth line of the file using SED (stream editor) | cat {filename} | awk 'NR=={n}' | Example: cat hugefile.txt | awk 'NR==25' |
Print \Read nth line of the file using awk | cat {filename} | sed -n '{n}p' sed -n '{n}p' < {filename} |
Example: cat hugfile.txt | sed -n '100p' sed -n '100p' < hugfile.txt |
Print \Read from mth line to nth lines of the file using SED (stream editor) | cat {filename} | sed -n '{n},{m}p' sed -n '{n},{m}p' < {filename} |
Example: cat hugfile.txt | sed -n '10,50p' sed -n '10,55p' < hugfile.txt |
Print \Read from mth line and nth lines of the file using SED (stream editor) | cat {filename} | sed -n '{m}p;{n}p' sed -n '{m}p;{n}p' < {filename} |
Example: cat hugfile.txt | sed -n '10p;40p' sed -n '10p;40p' < hugfile.txt |
### 2.2 Replace words file using sed (stream editor) command:
Details | Commands | Remarks |
---|---|---|
Replacing or substituting string: Sed command is mostly used to replace the text in a file. | sed 's/{word}/{replacewith}/' {filename} | Example: The below simple sed command replaces the word “data” with “DWH” in the file. sed 's/data/DWH/' hugefile.txt |
Replacing or substituting string: Sed command is mostly used to replace the text in a file. | sed 's/{word}/{replacewith}/' {filename} | Example: The below simple sed command replaces the word “data” with “DWH” in the file. sed 's/data/DWH/' hugefile.txt |
Replacing the nth occurrence of a pattern in a line: Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line.: | sed 's/{word}/{replacewith}/{n}' {filename} | Example: The below simple sed command replaces the word “data” with “DWH” in the file for 2nd occurance. sed 's/data/DWH/2' hugefile.txt |
Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. | sed 's/{word}/{replacewith}/g' {filename} | Example: The below simple sed command replaces the word “data” with “DWH” in the file fora all occurance. sed 's/data/DWH/g' hugefile.txt |
Replacing from nth occurrence to all occurrences in a line : The substitute flag /{n}g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. | sed 's/{word}/{replacewith}/{n}g' {filename} | Example: The below simple sed command replaces the word “data” with “DWH” in the file for all occurance from nth occurance. sed 's/data/DWH/5g' hugefile.txt |
Replacing from nth occurrence to all occurrences in a line : The substitute flag /{n}g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. | sed 's/{word}/{replacewith}/{n}g' {filename} | Example: The below simple sed command replaces the word “data” with “DWH” in the file for all occurance from nth occurance. sed 's/data/DWH/5g' hugefile.txt |
Parenthesize first character of each word : This sed example prints the first character of every word in parenthesis. | echo "{Tex}" | sed 's/\(\b[A-Z]\)/\(\1\)/g' | Example: echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' |
Replacing string on a specific line number: restrict the sed command to replace the string on a specific line number. | sed '{n} s/{data}/{ReplaceWith}/' {File} | Example: sed '3 s/data/SWH/' hugefile.txt |
Duplicating the replaced line with /p flag: The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once. | sed 's/{data}/{ReplaceWith}/p' {File.txt} | Example: sed 's/data/SWH/p' hugefile.txt |
Replacing string on a range of lines: can specify a range of line numbers to the sed command for replacing a string. | sed '1,3 s/{data}/{ReplaceWith}' {file} | Example: sed '1,3 s/data/DWH' hugefile.txt |
### 2.3 Deleting lines from a particular file using sed (stream editor) command:
#### 2.3.1 To Delete a particular line say n in this example ```sh # Syntax: sed 'nd' {filename} # Example: sed '5d' hugefile.txt ``` #### 2.3.2 To Delete a last line ```sh # Syntax: sed '$d' {filename} #Example: sed '$d' hugefile.txt ``` #### 2.3.3 To Delete line from range x to y ```sh #Syntax: sed 'x,yd' {filename} #Example: sed '3,6d' hugefile.txt ``` #### 2.3.4 To Delete from nth to last line ```sh #Syntax: sed 'nth,$d' {filename} #Example: sed '12,$d' hugefile.txt ``` #### 2.3.5. To Delete pattern matching line ```sh #Syntax: sed '/pattern/d' {filename} #Example: sed '/data/d' hugefile.txt ```
### 2.3 File Management-vi Editor with Commands: * The vi editor is elaborated as visual editor. It is installed in every Unix system. The vi editor has two modes: **Command Mode**: In command mode, actions are taken on the file. The vi editor starts in command mode.To enter text, you have to be in insert mode, just type `i`
**Insert Mode**: In insert mode, entered text will be inserted into the file. The Esc key will take you to the command mode from insert mode.
By default, the vi editor starts in Command mode. **To save and quit**:
save and quit vi editor from command mode.
Before writing save or quit command you have to press colon (:). Colon allows you to give instructions to vi. exit vi Commands: ------------------ |Commands| Action|Remarks| | :--- | :---: | ---: | |:wq |Save and quit| | |:w |Save| | |:q |Quit| | |:w fname |Save as fname | | |ZZ || Save and quit| | |:q! | Quit discarding changes made | | |:w! |Save (and write to non-writable file) ||
### 2.4 File Management-list files \directories:
Details | commands |
---|---|
List all directories in Unix | ls -l | grep '^d' |
list directories for the current directory | ls -d */ find . -maxdepth 1 -type d |
List of directories for given directory | ls -d /etc/*/ | more |
List only files in current directory: | ls -l | grep -v '^d' |
List all directories in a directory recursively | find . -type d -ls |more find /etc/ -type d -ls |
List all files in a directory recursively | find . -type f -ls find /etc/ -type f -ls | more |
Put above two aliases in your bash shell startup file:> | $ cd $ vi .bash_profile Append two lines: You can create two aliases as follows to list only directories and files. alias lf="ls -l | egrep -v '^d'" alias ldir='ls -d */' #alias ldir="ls -l | egrep '^d'" |
text in files | find . -exec grep -rl "<searchText>" {} \; examples: find . -exec grep -rl "user" {} \; |
###2.5 File Management-How to copy \move files between two unix \linux servers using scp ```sh scp [options] username1@source_host:directory1/filename1 \ username2@destination_host:directory2/filename2 ``` **Details** * The location of the source file is specified by username1@source_host:directory1/filename1, which includes the: * Name of the account on the host computer (username1) * Hostname of the computer on which the source file resides (source_host) * Name of the directory containing the source file (directory1) * Filename of the source file (filename1) * The location to which the source file will be copied is specified by username2@destination_host:directory2/filename2, which includes the: * Name of the account on the destination computer (username2) * Hostname of the computer to which the source file will be copied (destination_host) * Name of the directory to which the source file will be copied (directory2) * Filename of the copy (filename2) **Examples**: ```sh scp ~/sample.txt raz@dev1.aztd.com:~/testdir # It will copy sample.txt from current connected server to testdir folder in dev1 server/ ``` ```sh scp -r raz@dev1.aztd.com:~/dev1-test ~/testdir # it will copy all files in dev1-test directory from dev1 server to testdir directory in connected server recursively. ``` ```sh scp - raz@dev1.aztd.com:"~/dev1-test/*.txt ~/testdir # it will copy all text files in dev1-test directory from dev1 server to testdir directory in connected server. ``` ```sh scp raz@dev1.aztd.com:~/dev1-test/*.pdf raz@dev2.aztd.com:~/dev2-test ~/testdir # it will copy all pdf files in dev1-test directory from dev1 server to testdir directory in dev2 server. ```
###2.6 File Management- Archiving -Z commands
Details | commands | Remarks |
---|---|---|
Uncompressing or UnPacking files | gzip -d test.ods.gz | Display content after uncompress file cat test.ods |less |
Display the contents of a compressed file | zless data.ods.gz zmore data.ods.gz | |
Concatenate compressed files with out using gzip & cat | zcat TestReadme.gz | |
Compare compressed files. | zdiff file1.gz file2.gz zcmp test1.gz test2.gz | |
Search word in Compressed files | zegrep -w '^Test1|Test2' Test.gz
zgrep 'wordToSearch' Test.gz |
zgrep 'Test' /path/to/log/file.gz zgrep 'mail' /var/log/maillog-*.gz zgrep 'error' /var/log/error.log*.gz zgrep --color 'Failed login for' /var/log/secure* |
Search files in a ZIP archive for lines matching a pattern: | zipgrep *.cs Project.zip | |
Search files in a ZIP archive for lines matching a pattern: | zipgrep *.cs Project.zip |
## 3.Networking
### 3.1 Networking-How to check connectivity of another server server ```sh ping <ipAddress> ping <hostName> ping <FQDNForHostname> Example: ping 172.24.541.100 ping aztd1.azure.com ```
###3.2 Networking-How to check connectivity of another server server over particular port using ssh ```sh ssh -p <portNumer> -v <ipAddress> ssh -p <portNumer> -v <hostName> ssh -p <portNumer> -v <FQDNForHostname> Example: ssh -p 9050 172.24.541.100 ssh -p 9040 aztd1.azure.com ```
Subscribe to:
Posts (Atom)