Snippets Collections
type $env:USERPROFILE\.ssh\ | ssh {IP-ADDRESS-OR-FQDN} "cat >> .ssh/authorized_keys"
$role = "DHCP"
$feature = "RSAT-DHCP"
$computers = "Server1", "Server2", "Server3"
$action = Read-Host "Enter 'install', 'uninstall', or 'check' for the role/feature"

foreach ($computer in $computers) {
    Invoke-Command -ComputerName $computer -ScriptBlock {
        if ($action -eq "install") {
            Install-WindowsFeature -Name $role, $feature -IncludeAllSubFeature -IncludeManagementTools
        } elseif ($action -eq "uninstall") {
            Uninstall-WindowsFeature -Name $role, $feature -Remove
        } elseif ($action -eq "check") {
            Get-WindowsFeature -Name $role, $feature | Format-Table -Property Name, DisplayName, Installed
        } else {
            Write-Host "Invalid action specified"
$eventlogs = "Application", "Security", "System"
$lognames = $eventlogs | ForEach-Object {$_ + ".evtx"}
$path = "C:\EventLogs\"
$date = (Get-Date).AddDays(-30)

foreach ($logname in $lognames) {
    $log = Get-WinEvent -LogName $logname -FilterXPath "*[System[TimeCreated[@SystemTime>='$date']]]"
    $log | Export-EventLog -Path "$path$logname"
Import-Module ActiveDirectory

$username = Read-Host "Enter the username"
$password = Read-Host "Enter the password" -AsSecureString
$firstname = Read-Host "Enter the first name"
$lastname = Read-Host "Enter the last name"
$groupname = Read-Host "Enter the group name"

New-ADUser -Name "$firstname $lastname" -SamAccountName $username -UserPrincipalName "$" -GivenName $firstname -Surname $lastname -Enabled $true -AccountPassword $password -ChangePasswordAtLogon $true
Add-ADGroupMember -Identity $groupname -Members $username
Finding the Current Date with PowerShell
One of the easiest ways to discover the current date with PowerShell is by using the Get-Date cmdlet. This command displays the current date and time as shown below.

PS> Get-Date
Sunday, November 22, 2020 1:25:57 AM

By default, PowerShell Get Date command looks like it only returns the current date and time but, in reality, it’s actually returning a lot more information. To find this information pipe the output to the Format-List cmdlet as shown below.

PS> Get-Date | Format-List
DisplayHint : DateTime
Date        : 11/22/2020 12:00:00 AM
Day         : 22
DayOfWeek   : Sunday
DayOfYear   : 327
Hour        : 1
Kind        : Local
Millisecond : 163
Minute      : 26
Month       : 11
Second      : 2
Ticks       : 637416051621635773
TimeOfDay   : 01:26:02.1635773
Year        : 2020
DateTime    : Sunday, November 22, 2020 1:26:02 AM

You can also use the Get-Member cmdlet to find all of the object properties by running Get-Date | Get-Member -MemberType Properties also.

If you check the type of object Get-Date returns, you’ll notice it’s a System.DateTime object type. This class is what exposes all of the different properties and methods you see. You can discover it’s object type by using Get-Member or using the GetType() as shown below.

PS> (Get-Date).GetType().FullName

Once you see all of the available properties you have available, you can then reference them with dot notation as shown below.

PS> (Get-Date).Year

PS> (Get-Date).DayOfWeek

PS> (Get-Date).Month

PS> (Get-Date).DayOfYear

Is dot notation a bit too “devvy” for you? If so, you can also use the DisplayHint parameter to achieve the same result.

PS> Get-Date -DisplayHint Date
Sunday, November 22, 2020

PS> Get-Date -DisplayHint Time
2:29:35 AM

PS> Get-Date -DisplayHint DateTime
Sunday, November 22, 2020 2:29:39 AM

Using PowerShell Get Date is the simplest way to find the current date and various attributes but you can do so much more!

Date Arithmetic with PowerShell
Let’s say that you need to know the date and/or time a certain number of days, years, or minutes in the past or in the future. You can find this information using methods.

Using DateTime Methods
The System.DateTime object that PowerShell Get Date command returns has various methods you can invoke to add or remove chunks of time. If you run Get-Date | Get-Member, you’ll see various methods that start with Add.

AddDays              Method         datetime AddDays(double value)
AddHours             Method         datetime AddHours(double value)
AddMilliseconds      Method         datetime AddMilliseconds(double value)
AddMinutes           Method         datetime AddMinutes(double value)
AddMonths            Method         datetime AddMonths(int months)
AddSeconds           Method         datetime AddSeconds(double value)
AddTicks             Method         datetime AddTicks(long value)
AddYears             Method         datetime AddYears(int value)

You can call each of these methods to find a date/time in the future or in the past. Below you’ll see a few examples of invoking each of these methods and their output.

#Adding 8 days to the current date
PS> (Get-Date).AddDays(8)
Monday, November 30, 2020 1:59:39 AM

#Adding 3 hours to the current time
PS> (Get-Date).AddHours(3)
Sunday, November 22, 2020 4:59:51 AM

#Adding five years to the current date
PS> (Get-Date).AddYears(5)
Saturday, November 22, 2025 2:00:11 AM

#Subtracting 8 days from the current date using a negative number.
PS> (Get-Date).AddDays(-8)
Saturday, November 14, 2020 2:02:43 AM

Using New-Timespan
What if you wanted to know the difference between two dates; not just adding a specific number of time chunks? One way to do this is to use the New-Timespan cmdlet. The New-Timespan cmdlet generates TimeSpan objects which represent date/time differences or spans.

Use the New-TimeSpan cmdlet by providing a Start and End date/time as parameters. For example, if you’d like to find the difference between November 23rd, 2020 at midnight to December 31st, 2020 at midnight, you could use the following code snippet.

Using TimeSpan objects, you can find date/time differences in just about any increment you’d like.

PS> $StartDate = Get-Date -Month 11 -Day 23 -Year 2020 -Hour 00 -Minute 00 -Second 00
PS> $EndDate = Get-Date -Month 12 -Day 31 -Year 2020 -Hour 00 -Minute 00 -Second 00
PS> $StartDate
Monday, November 23, 2020 12:00:00 AM

PS> $EndDate
Thursday, December 31, 2020 12:00:00 AM

PS> New-TimeSpan -Start $StartDate -End $EndDate

Days              : 38
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 672
Ticks             : 32832006722080
TotalDays         : 38.0000077801852
TotalHours        : 912.000186724444
TotalMinutes      : 54720.0112034667
TotalSeconds      : 3283200.672208
TotalMilliseconds : 3283200672.208

Comparing Dates
Not only can you find differences in dates and times but you can also compare them using standard PowerShell operators. PowerShell knows when a date is “less than” (earlier than) or “greater than” (later than) another date.

To compare dates, simply create two DateTime objects using PowerShell Get Date command or perhaps by casting strings with [DateTime] and then using standard PowerShell operators like lt or gt.

You can see a simple example of comparing dates below.

#Declaring the date
PS> $Date1 = (Get-Date -Month 11 -Day 14 -Year 2020)
PS> $Date2 = Get-Date
PS> $Date1 -lt $Date2

Converting (Casting) Strings to DateTime Objects
PowerShell can also display dates in various formats. For example, let’s say you have a CSV file or spreadsheet with various dates defined in the format you see below in the date_time_utc column. The format is currently YYYY-MM-DDThh:mm:ss.0000000Z.

You’d like to parse this file and find all of the rows with a date seven days or older.

PowerShell, by default, doesn’t know that 2020-09-07T13:35:08.4780000Z is a date and time; it just thinks it’s a simple string. To make PowerShell understand, you must first convert it to a DateTime object like Get-Date returns.

To cast a string to a DateTime object, preface the string (or variable) with [DateTime]. When you do this, PowerShell tries to interpret the string as a date and time then provides you with all of the properties and methods available on this object type.

PS> $Date = "2020-09-07T13:35:08.4780000Z"
PS> [DateTime]$Date
Monday, September 07, 2020 1:35:08 PM

Using PowerShell Get Date : PowerShell Date Formatting
Now that you are aware of the basic methods of using dates, it’s time to delve deeper into the topic. Let’s play around a bit more by using different formats to display dates.

Whenever you run the PowerShell Get Date command, you will see an output like Monday, September 07, 2020 1:35:08 PM. This output is actually a DateTime object with properties and methods; not a simple string. But, you can convert this DateTime object to a string and represent it differently using various date formatting methods.

DateTime Methods
One way to change up how a DateTime object is displayed is by using methods on the DateTime object. The DateTime object has four methods you can use to change up the formatting:

You can see an example of using the ToShortDateString() and ToShortTimeString() methods below.

PS> [DateTime]$Date = $Date
PS> $date.ToShortDateString() + " " + $date.ToShortTimeString()
9/7/2020 7:05 PM

The Format Parameter
One way to change the date format of a DateTime object is by using Get-Date to generate the object and the Format parameter to change the format. The Format parameter accepts a string of characters each representing how a date/time string should look.

You can see a few examples of the characters you can use with the Format parameter.

#To display full date pattern with short time pattern
PS> Get-Date -Format f
Sunday, November 22, 2020 4:26 AM

#To display full date pattern with long time pattern
PS> Get-Date -Format F
Sunday, November 22, 2020 4:26:31 AM

#To display short date pattern
PS> Get-Date -Format d

#To display long date pattern
PS> Get-Date -Format D
Sunday, November 22, 2020

#Year month pattern
PS> Get-Date -Format Y
November 2020

## Combining format characters
PS> Get-Date -Format "dddd dd-MM-yyyy HH:mm K"
Sunday 22-11-2020 03:41 +05:30

function Get-MSIProperties {
  param (
    [System.IO.FileInfo] $path,

    [string[]] $properties = @('ProductCode', 'ProductVersion', 'ProductName', 'Manufacturer', 'ProductLanguage')
  begin {
    $windowsInstaller = (New-Object -ComObject WindowsInstaller.Installer)
  process {
    $table = @{}
    $msi = $windowsInstaller.GetType().InvokeMember('OpenDatabase', 'InvokeMethod', $null, $windowsInstaller, @($Path.FullName, 0))
    foreach ($property in $properties) {
      try {
        $view = $msi.GetType().InvokeMember('OpenView', 'InvokeMethod', $null, $msi, ("SELECT Value FROM Property WHERE Property = '$($property)'"))
        $view.GetType().InvokeMember('Execute', 'InvokeMethod', $null, $view, $null)
        $record = $view.GetType().InvokeMember('Fetch', 'InvokeMethod', $null, $view, $null)
        $table.add($property, $record.GetType().InvokeMember('StringData', 'GetProperty', $null, $record, 1))
      catch {
        $table.add($property, $null)
    $msi.GetType().InvokeMember('Commit', 'InvokeMethod', $null, $msi, $null)
    $view.GetType().InvokeMember('Close', 'InvokeMethod', $null, $view, $null)
    $msi = $null
    $view = $null
    return $table
  end {
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($windowsInstaller) | Out-Null
function Get-TimesResult {

Param ([int]$a,[int]$b)

$c = $a * $b

Write-Output $c

[Collections.Generic.List[object]]$people = @()
for ($i=0;$i -le '10';$i++) {
  $output = @{
    name = "Person $i"
    ID = $i
    Phone = "555$i"
  $people.Add( [pscustomobject]$output )
Compare-Object $(Get-Content .\TestDoc1.txt) $(Get-Content .\TestDoc2.txt) | Out-File .\TestDoc3.txt
$output = for ($i = 0; $i -le 10; $i++) {
      server = "servername$i"
      cluster = "clustername$i"
      error = $null
[pscustomobject]@{ Name = 'bob'; Id = 20 }
# can be
[Employee]@{ Name = 'bob'; Id = 20 }

# Create class that we can populate
class Employee {    

[Employee]@{ Name = 'bob'; Id = 20 }
[Employee]@{ Name = 'Jen'; Id = 33 }

# OR add object to a list

$list = [system.collections.generic.List[object]]::new()
class Person {

$Person = [Person]@{
    name = "Noah"
    location = "here"
    age = "old enough"

### FUNCTION: Generate New Complex Password
Function generateNewComplexPassword([int]$passwordNrChars) {
	Process {
		$iterations = 0
        Do {
			If ($iterations -ge 20) {
				Logging "  --> Complex password generation failed after '$iterations' iterations..." "ERROR"
				Logging "" "ERROR"
			$pwdBytes = @()
			$rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
			Do {
				[byte[]]$byte = [byte]1
				If ($byte[0] -lt 33 -or $byte[0] -gt 126) {
                $pwdBytes += $byte[0]
			While ($pwdBytes.Count -lt $passwordNrChars)
				$pwd = ([char[]]$pwdBytes) -join ''
        Until (confirmPasswordIsComplex $pwd)
        Return $pwd

Send email with optional attachments


PowerShelll script for a function to send email with optional attachments. It accepts a comma-separated list of attachments, or no attachments at all.

For dot-source inclusion to work if the script is hosted on a UNC path, you may need to add the url "file:\\unc-path-to-share" to the Internet Explorer local Intranet site list on the server running the script.






PS> .\Send-Email.ps1
Send-Email -EmailTo "" -EmailSubject "Log files attached" -EmailBody "Please find attached the log files" -EmailAttachments "C:\logs\Logfile.txt","C:\logs\Logfile2.txt"

This command sends an email with 2 attachments


PS> .\Send-Email.ps1
$EmailRecipients = @("","","")
Send-Email -EmailTo $EmailRecipients -EmailSubject "Test message" -EmailBody "Hello"

These commands send an email to multiple recipients


PS> .\Send-Email.ps1
Send-Email -EmailTo "" -EmailFrom "" -EmailSMTPServer "" -EmailSubject "Log file attached" -EmailBody "Please find attached the log file" -EmailAttachments "C:\logs\Logfile.txt"

This command shows all parameters



#        Script: Send-Email.ps1
#      Author: Dan Tonge,
#     Version:  1.0 2013-04-11
#     Version:  1.1 2015-06-01  Added multiple recipient syntax examples
#     Version:  1.2 2020-06-08  Added comment-based help for the script

Function Send-Email
            [parameter(Mandatory=$true,HelpMessage="Email To Address")] $EmailTo,
            [parameter(HelpMessage="Email From Address")] $EmailFrom = [String]$env:computerName.ToLower() + '',
            [parameter()] $EmailSMTPServer = '',
            [parameter(Mandatory=$true,HelpMessage="Email subject line")] $EmailSubject,
            [parameter(Mandatory=$true,HelpMessage="Email content")] $EmailBody,
            [parameter(HelpMessage="Optional Attachments")] $EmailAttachments
         ) #end Param

    # build a "splat" parameter: a hash of {parameter name, parameter value} to avoid passing the Attachments parameter when not needed
    $attachments = @()
        if ($EmailAttachments) 
                $attachments += $EmailAttachments

    $params = @{}
        if ($attachments.Length -gt 0)
                $params['Attachments'] = $attachments

    Send-MailMessage @params -To $EmailTo -From $EmailFrom -SmtpServer $EmailSMTPServer -Subject $EmailSubject -Body $EmailBody
$filename = 'D:\PS\CSV\PowerShell-EventLogs.csv'    

# Get file size in bytes
(Get-Item -Path $filename).Length

# get file size in KB in PowerShell
(Get-Item -Path $filename).Length/1KB

# get file size in MB in PowerShell   
(Get-Item -Path $filename).Length/1MB

# get file size in GB in PowerShell
(Get-Item -Path $filename).Length/1GB  
$setRoAttributeTo = $true
Get-ChildItem -Path $folderPath | foreach {
    Set-ItemProperty -Path $folderPath\TestFile.txt -Name IsReadOnly -Value $setRoAttributeTo
PS> Get-ItemProperty -Path $folderPath\TestFile.txt | Select-Object IsReadOnly

# Author cvucic (

Function List-Programs {
    [string[]]$ComputerName = $env:computername

    begin {

    process {
        foreach ($Computer in $ComputerName) {
            Write-Verbose "Working on $Computer"
            if (Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
                $HKLM = [microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine', $computer)
                $UninstallRef = $HKLM.OpenSubKey($UninstallRegKey)
                $Applications = $UninstallRef.GetSubKeyNames()

                foreach ($App in $Applications) {
                    $AppRegistryKey = $UninstallRegKey + "\\" + $App
                    $AppDetails = $HKLM.OpenSubKey($AppRegistryKey)
                    $AppGUID = $App
                    $AppDisplayName = $($AppDetails.GetValue("DisplayName"))
                    $AppVersion = $($AppDetails.GetValue("DisplayVersion"))
                    $AppPublisher = $($AppDetails.GetValue("Publisher"))
                    $AppInstalledDate = $($AppDetails.GetValue("InstallDate"))
                    $AppUninstall = $($AppDetails.GetValue("UninstallString"))
                    if (!$AppDisplayName) { continue }
                    $OutputObj = New-Object -TypeName PSobject
                    $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
                    $OutputObj | Add-Member -MemberType NoteProperty -Name AppName -Value $AppDisplayName
                    $OutputObj | Add-Member -MemberType NoteProperty -Name AppVersion -Value $AppVersion
                    $OutputObj | Add-Member -MemberType NoteProperty -Name AppVendor -Value $AppPublisher
                    $OutputObj | Add-Member -MemberType NoteProperty -Name InstalledDate -Value $AppInstalledDate
                    $OutputObj | Add-Member -MemberType NoteProperty -Name UninstallKey -Value $AppUninstall
                    $OutputObj | Add-Member -MemberType NoteProperty -Name AppGUID -Value $AppGUID
                    $OutputObj# | Select ComputerName, DriveName

    end {}

Function Uninstall-Program {
    param (
    [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [string]$ComputerName = $env:computername,
    try {
        $returnval = ([WMICLASS]"\\$computerName\ROOT\CIMV2:win32_process").Create($UninstallKey + " /VERYSILENT /SUPPRESSMSGBOXES /NORESTART")
    catch {
        write-error "Failed to trigger the uninstallation. Review the error message"
        exit 1
    switch ($($returnval.returnvalue)) {
        0 { "Uninstallation command triggered successfully" }
        2 { "You don't have sufficient permissions to trigger the command on $Computer" }
        3 { "You don't have sufficient permissions to trigger the command on $Computer" }
        8 { "An unknown error has occurred" }
        9 { "Path Not Found" }
        10 { "Invalid Parameter"}

function Uninstall-MBAM {
    try {
        $UninstallKey = (List-Programs -ComputerName $computername | where {$_.AppName -like "*Malwarebytes*"}).UninstallKey
        Uninstall-Program -computername $computername -UninstallKey $UninstallKey
    catch {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName
        Write-Host "There was an error on $computername.`r`n$FailedItem`r`nMessage: $ErrorMessage"

Uninstall-MBAM -computername $env:computername

$TcpClient = New-Object System.Net.Sockets.TcpClient
[byte[]]$buffer = ,0 * 64
$TcpClient.Connect('', 13)
$TcpStream = $TcpClient.GetStream()
$length = $TcpStream.Read($buffer, 0, $buffer.Length);
$raw = [Text.Encoding]::ASCII.GetString($buffer)
Set-Date ([DateTime]::ParseExact($raw.SubString(7,17), 'yy-MM-dd HH:mm:ss', $null).toLocalTime())

$Username = "Administrator"
$Password = "****"

$group = "Administrators"

$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$existing = $adsi.Children | where {$_.SchemaClassName -eq 'user' -and $_.Name -eq $Username }

if ($existing -eq $null) {

    Write-Host "Creating new local user $Username."
    & NET USER $Username $Password /add /y /expires:never
    Write-Host "Adding local user $Username to $group."
    & NET LOCALGROUP $group $Username /add

else {
    Write-Host "Setting password for existing local user $Username."

Write-Host "Ensuring password for $Username never expires."
& WMIC USERACCOUNT WHERE "Name='$Username'" SET PasswordExpires=FALSE

$logs = get-eventlog -list | foreach {$_.log}
foreach ($l in $logs) {
    limit-eventlog -logname $l -MaximumSize 40MB
get-eventlog -list
exit 0

Restart-Service Spooler
$printer = Get-CimInstance win32_printer -Filter "Default = 1"
Invoke-CimMethod -MethodName PrintTestPage -InputObject $printer
exit 0

Get-ComputerRestorePoint | Format-Table -Wrap -Auto
Get-ADComputer -Filter * -Property Name, OperatingSystem, OperatingSystemServicePack, OperatingSystemVersion | Format-Table Name, OperatingSystem, OperatingSystemServicePack, OperatingSystemVersion -Wrap -Auto
Get-ADDomain | Select InfrastructureMaster, RIDMaster, PDCEmulator
Get-ADForest | Select DomainNamingMaster, SchemaMaster
Get-ADDomainController -Filter * | Select-Object Name, Domain, Forest, OperationMasterRoles | Where-Object {$_.OperationMasterRoles} | Format-Table -AutoSize

Get-ADDomain | Select InfrastructureMaster, RIDMaster, PDCEmulator
Get-ADForest | Select DomainNamingMaster, SchemaMaster
Get-ADDomainController -Filter * | Select-Object Name, Domain, Forest, OperationMasterRoles | Where-Object {$_.OperationMasterRoles} | Format-Table -AutoSize

$version = (Get-CimInstance Win32_OperatingSystem).Version
$major = $version.split(".")[0]
if ($major -eq 10) {
	Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value "0"
} ElseIf ($major -eq 6) {
	$minor = $version.split(".")[1]
    if ($minor -eq 1 -or $minor -eq 0) {
		Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value "0"
    } Else {
		Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value "0"
} ElseIf ($major -eq 5) {
	Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value "0"
} Else {
	Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value "0"

# generate public key using Powershell
# email at the end is just a signature that you created it
ssh-keygen -t rsa -b 4096 -C ""

# then cd to a folder with files and run this in PS:
icacls * /reset /t /c /q   #

# start the ssh-agent in the background using GIT
eval "$(ssh-agent)"

# using GIT add private key to SSH agent: (PowerShell does not work for some reason)
# cd to .ssh folder first "cd C:/Users/oserdyuk/.ssh"
ssh-add ~/.ssh id_rsa

# add public key to a GitHub repository: Left top corner--> settings

# Clone repository using GIT
# make sure you are in GIT repository : "cd C:/Users/oserdyuk/Documents/AzureProjects/azure-resume"
git clone

						### Push changes to GIT  ###
# save what you've done
git add -A
# say what you've done
git commit -m "Deployed storage and bla bla"
# push what you've done
git push

# if a project created in vs code and then need to be pushed to github
git push --set-upstream master

# Troubleshooting

# add Private key to ssh agent using PS
ssh-add C:/Users/oserdyuk/.ssh/
# or make sure you are in c:/oserdyuk and run
ssh-add .\.ssh\id_rsa

#if error: Error loading key "C:/Users/oserdyuk/.ssh/": invalid format
# you can either overrite key in a right format: (it changes email to oserdyuk@oserdyuk-vm - not sure why)
ssh-keygen -f C:/Users/oserdyuk/.ssh/   # click Enter to ignore password

git clone

# to remove keys from SSH agent
ssh-add -D

# service OpenSSH Authentification Agent. Make sure it's running.
# start service in powershell
Start-Service -Name "OpenSSH Authentication Agent"
# check if it started
Get-Service ssh-agent

# start the ssh-agent in the background
eval "$(ssh-agent)"

echo "$(ssh-agent)"

# check whether agent is running or not (GIT)
if ps -p $SSH_AGENT_PID > /dev/null
   echo "ssh-agent is already running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
eval `ssh-agent -s`

# list all keys that are present in the agent PS or GIT
ssh-add -l

# overwrite the key. Just please enter (to ignore password)
 ssh-keygen -f C:/Users/oserdyuk/.ssh/

ssh-add -L # copy the key, place it into GitHub. Worked

ssh-add "C:/Users/oserdyuk/.ssh/"  -- Error loading key. Invalid format

ssh-add ~/.ssh my_id_rsa
Invoke-Expression (New-Object System.Net.WebClient).DownloadString('')
for ($num = 1 ; $num -le 10 ; $num++) { mkdir "your-prefix-$num"}
# view content of the folder
$reportServerUri = ''
$folderName = "/AFH/Align General/Programs"
Get-RsFolderContent -ReportServerUri $reportServerUri -RsFolder $folderName | Format-Table -AutoSize

# Return existing data source information for "GrossBudget" report. If multiple datasources uses for queries - it will return all of them. 
$ReportPortalUri = ""
Get-RsRestItemDataSource -RsItem "/AFH/GrossBudget" -ReportPortalUri $ReportPortalUri

# Get connection string info for "Construction - AY Loss Ratios" report
$ReportPortalUri = ""
Get-RsRestItemDataSource -RsItem "/AFH/Align General/Programs/Construction - AY Loss Ratios" -ReportPortalUri $ReportPortalUri
# change connection string for Catalytic reports using catalyticSSRS username
$ReportPortalUri = ""
$ReportName = '/AFH/Catalytic/Underwriter Reports/Underwriter Production'
$Username = 'catalyticSSRS'
$Password = 'RND1101!'
$ServerName = ''
# grab parameters that are currently exists in a report
$parameters = Get-RsRestItemDataModelParameters $ReportName -ReportPortalUri $ReportPortalUri
# Map to a dictionary to access the parameter values.
$parameterdictionary = @{}
foreach ($parameter in $parameters) { $parameterdictionary.Add($parameter.Name, $parameter); }
# change parameter value
$parameterdictionary[“ServerName”].Value = $ServerName
# update parameters that are currentl in a report
Set-RsRestItemDataModelParameters -RsItem $ReportName -ReportPortalUri $ReportPortalUri -DataModelParameters $parameters
# print what changed
# set authentification mode, username and password
$dataSources = Get-RsRestItemDataSource -RsItem $ReportName -ReportPortalUri $ReportPortalUri
$dataSources[0].DataModelDataSource.AuthType = 'UsernamePassword' # UsernamePassword should be used when specifying SQL or Basic Credentials
$dataSources[0].DataModelDataSource.Username = $Username
$dataSources[0].DataModelDataSource.Secret = $Password
Set-RsRestItemDataSource -RsItem $ReportName -RsItemType PowerBIReport -DataSources $datasources
cd <span class="token string">"C:\Program Files\Oracle\VirtualBox\"</span>
VBoxManage<span class="token punctuation">.</span>exe modifyvm <span class="token string">"VM Name"</span> <span class="token operator">--</span>cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff
VBoxManage setextradata <span class="token string">"VM Name"</span> <span class="token string">"VBoxInternal/Devices/efi/0/Config/DmiSystemProduct"</span> <span class="token string">"iMac19,1"</span>
VBoxManage setextradata <span class="token string">"VM Name"</span> <span class="token string">"VBoxInternal/Devices/efi/0/Config/DmiSystemVersion"</span> <span class="token string">"1.0"</span>
VBoxManage setextradata <span class="token string">"VM Name"</span> <span class="token string">"VBoxInternal/Devices/efi/0/Config/DmiBoardProduct"</span> <span class="token string">"Mac-AA95B1DDAB278B95"</span>
VBoxManage setextradata <span class="token string">"VM Name"</span> <span class="token string">"VBoxInternal/Devices/smc/0/Config/DeviceKey"</span> <span class="token string">"ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"</span>
VBoxManage setextradata <span class="token string">"VM Name"</span> <span class="token string">"VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC"</span> 1
git filter-branch --env-filter 'export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"'
git push -f
pktmon filter remove
pktmon filter add -p 53
pktmon start --etw -m real-time
#!/usr/bin/env bash

# Update the list of packages
sudo apt-get update

# Install pre-requisite packages.
sudo apt-get install -y wget apt-transport-https software-properties-common

# Download the Microsoft repository GPG keys
wget -q

# Register the Microsoft repository GPG keys
sudo dpkg -i packages-microsoft-prod.deb

# Update the list of packages after we added
sudo apt-get update

# Install PowerShell
sudo apt-get install -y powershell

# Start PowerShell
© 2022 GitHub, Inc.
Start-Process powershell.exe -verb runAs -ArgumentList '-NoExit', '-Command', 'cd <PATH>'
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Windows Terminal.lnk")
$Shortcut.TargetPath = "$env:LOCALAPPDATA\Microsoft\WindowsApps\Microsoft.WindowsTerminal_8wekyb3d8bbwe\wt.exe"
$bytes = [System.IO.File]::ReadAllBytes("$Home\Desktop\Windows Terminal.lnk")
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON
[System.IO.File]::WriteAllBytes("$Home\Desktop\Windows Terminal.lnk", $bytes)
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
▶ My shell setup:
* Fish shell:
* Fisher:
* Shellder:
* Nerd fonts:
* z for fish:
* Exa:
* ghq:
* peco:
wsl --shutdown
# open window Diskpart
select vdisk file="C:\WSL-Distros\…\ext4.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
kubectl rollout restart deploy -n cnext-di-demo
    Format-TSQL will format tsql script supplied per options set
    This script will strip supplied code of comments format per options
    Author     : Mala Mahadevan (
-InputScript: text file containing T-SQL
    -OutputScript: name of text file to be generated as output
Strips code of comments

2021.08.08First version for
function Format-TSQL
    #Defining parameter for scriptname
    If ((Test-Path $InputScript -PathType Leaf) -eq $false)
        $errormessage = "File $InputScript not found!"
        throw $errormessage
    If ((Test-Path $OutputScript -IsValid) -eq $false)
        $errormessage = "Path for $Outputscript not found!"
        throw $errormessage
    #This may need to be modified to wherever the dll resides on your machine
    Add-Type -Path "C:\Program Files\Microsoft SQL Server\150\DAC\bin\Microsoft.SqlServer.TransactSql.ScriptDom.dll"
    $generator = [Microsoft.SqlServer.TransactSql.ScriptDom.Sql150ScriptGenerator]::New();
    #Include semi colons at end of every statement
    $generator.Options.IncludeSemicolons = $true
    #Aligns body inside of  blocks
    $generator.Options.AlignClauseBodies = $true
    #Aligns all column definitions for create view/table
    $generator.Options.AlignColumnDefinitionFields = $true
    #Aligns set statements
    $generator.Options.AlignSetClauseItem = $true
    #create or alter 'as' will be on its own line
    $generator.Options.AsKeywordOnOwnLine = $true
    #Define indentation - only spaces
    $generator.Options.IndentationSize = 10
    #Indent set clauses
    $generator.Options.IndentSetClause = $true
    #Indent body of view
    $generator.Options.IndentViewBody = $true
    #Set keyword casing
    $generator.Options.KeywordCasing =  1 #0 lower case 1 upper case 2 pascal case
    #Seperate each column on insert source statement to its own line
    $generator.Options.MultilineInsertSourcesList = $true
    #Seperate each column on insert target statement to its own line
    $generator.Options.MultilineInsertTargetsList = $true
    #Seperate each column on select statement to its own line
    $generator.Options.MultilineSelectElementsList = $true
    #Separate each item on set clause to its own line
    $generator.Options.MultilineSetClauseItems = $true
    #Separate each column on view to its own line
    $generator.Options.MultilineViewColumnsList = $true
    #Separate each line on where predicate to its own line
    $generator.Options.MultilineWherePredicatesList = $true
    #Insert a new line before ( on multi line list of columns
    $generator.Options.NewLineBeforeCloseParenthesisInMultilineList = $true
    #Insert a new line before from clause
    $generator.Options.NewLineBeforeFromClause = $true
    #Insert a new line before group by clause
    $generator.Options.NewLineBeforeGroupByClause = $true
    #Insert a new line before having clause
    $generator.Options.NewLineBeforeHavingClause = $true
    #Insert a new line before join
    $generator.Options.NewLineBeforeJoinClause = $true
    #Insert a new line before offset clause
    $generator.Options.NewLineBeforeOffsetClause = $true
    #Insert a new line before ) on multi line list of columns
    $generator.Options.NewLineBeforeOpenParenthesisInMultilineList = $true
    #Insert a new line before order by
    $generator.Options.NewLineBeforeOrderByClause = $true
    #Insert a new line before output clause
    $generator.Options.NewLineBeforeOutputClause = $true
    #Insert a new line before where clause
    $generator.Options.NewLineBeforeWhereClause = $true
    #Recognize syntax specific to engine type - to be safe use 0
    $generator.Options.SqlEngineType = 0 # 0 All 1 Engine 2 Azure
    #Version used 
    #80    1
    #90    0 (default)
    $generator.Options.SqlVersion = 7
    #Read the string passed in
    $stringreader = New-Object -TypeName System.IO.StreamReader -ArgumentList $InputScript
    #Create generate object
    $generate =     [Microsoft.SqlServer.TransactSql.ScriptDom.Sql150ScriptGenerator]($generator)
    #Parse the string for errors and create tsqlfragment for formatting
    $parser = [Microsoft.SqlServer.TransactSql.ScriptDom.TSql150Parser]($true)::New();
    if($parser -eq $null){
    throw 'ScriptDOM not installed or not accessible'
    $parseerrors = $null
    $fragment = $parser.Parse($stringreader,([ref]$parseerrors))
    # raise an exception if any parsing errors occur
    if($parseerrors.Count -gt 0) {
        throw "$($parseErrors.Count) parsing error(s): $(($parseErrors | ConvertTo-Json))"
    $formattedoutput = ''
    #Format the string
    write-host $formattedoutput -BackgroundColor blue
    $formattedoutput.ToString() | Out-File $OutputScript
Get-Service | Where-Object -FilterScript {$_.StartType -EQ 'Automatic'}
Get-Content "\\fs01\Align\Public\OLEGSQLSWITCH\Servers.txt" |
          if(Test-Connection $_ -Count 1 -quiet){
               "$_ Up"
               "$_ Down"
$RG = "di-platform-dev-rg-execution"
$NAME = "di-platform-dev-k8s-exe"

$SP_ID=$(az aks show --resource-group "$RG" --name "$NAME" \
    --query servicePrincipalProfile.clientId -o tsv)

az ad sp credential list --id "$SP_ID" --query "[].endDate" -o tsv

$SP_ID=$(az aks show --resource-group "$RG" --name "$NAME" \
    --query servicePrincipalProfile.clientId -o tsv)

$SP_SECRET=$(az ad sp credential reset --name "$SP_ID" --query password -o tsv)

az aks update-credentials \
    --resource-group "$RG" \
    --name $NAME" \
    --reset-service-principal \
    --service-principal "$SP_ID" \
    --client-secret "$SP_SECRET"
 [string] [Parameter(Mandatory=$true)] $PathToVSIX,
 [string] [Parameter(Mandatory=$true)] $Token,
 [string] $IsPublicInput = "false",
 [string] $Version = $null,
 [string] $Publisher = $null,
 [string] $RemoveBaseUriInput = "true",
 [string] $ShareWith= $null
Set-StrictMode -Version 3

[bool]$IsPublic = [bool]::Parse($IsPublicInput)
[bool]$RemoveBaseUri = [bool]::Parse($RemoveBaseUriInput)

$file = Get-ChildItem $PathToVSIX -Filter *.vsix -Recurse | % { $_.FullName } | Select -First 1
Write-Verbose "Found VSIX Package $file"

try { $null = [IO.Compression.ZipFile] }
catch { [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') }

try { $fileZip = [System.IO.Compression.ZipFile]::Open( $file, 'Update' ) }
catch { throw "Another process has locked the '$file' file." }

$desiredFile = [System.IO.StreamReader]($fileZip.Entries | Where-Object { $_.FullName -match 'extension.vsixmanifest' }).Open()
$text = $desiredFile.ReadToEnd()
[xml]$xml = $text

if ($Version)
 Write-Verbose "Updating Version to $Version"
 $xml.PackageManifest.MetaData.Identity.Version = $Version

if ($Publisher)
 Write-Verbose "Updating Publisher to $Publisher"
 $xml.PackageManifest.MetaData.Identity.Publisher = $Publisher

if($IsPublic -eq $true)
 Write-Verbose "Setting GalleryFlag to Public"
 $xml.PackageManifest.MetaData.GalleryFlags = "Public"
 Write-Verbose "Setting GalleryFlag to Private"
 $xml.PackageManifest.MetaData.GalleryFlags = ""

$desiredFile = [System.IO.StreamWriter]($fileZip.Entries | Where-Object { $_.FullName -match 'extension.vsixmanifest' }).Open()


$desiredFile = [System.IO.StreamReader]($fileZip.Entries | Where-Object { $_.FullName -match 'extension.vsomanifest' }).Open()
$text = $desiredFile.ReadToEnd()

if ($RemoveBaseUri -eq $true)
 $text = (($text -split "`n") | ? {$_ -notmatch 'baseUri'}) -join "`n"

$desiredFile = [System.IO.StreamWriter]($fileZip.Entries | Where-Object { $_.FullName -match 'extension.vsomanifest' }).Open()



if($ShareWith -ne $null)
 $ShareWith = "--share-with" + $ShareWith
 $ShareWith = ""

npm install -g tfx-cli
tfx extension publish --vsix "$File" --token $Token $ShareWith
set WEBAPIURL=http://...

powershell -Command "& {Invoke-RestMethod -UseDefaultCredential -Method Post -Uri %WEBAPIURL% }>> output.txt
# WSL2 network port forwarding script v1
#   for enable script, 'Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser' in Powershell,
#   for delete exist rules and ports use 'delete' as parameter, for show ports use 'list' as parameter.
#   written by Daehyuk Ahn, Aug-1-2020

# Display all portproxy information
If ($Args[0] -eq "list") {
    netsh interface portproxy show v4tov4;

# If elevation needed, start new process
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
  # Relaunch as an elevated process:
  Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path),"$Args runas" -Verb RunAs

# You should modify '$Ports' for your applications 
$Ports = (22,80,443,8080)

# Check WSL ip address
wsl hostname -I | Set-Variable -Name "WSL"
$found = $WSL -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if (-not $found) {
  echo "WSL2 cannot be found. Terminate script.";

# Remove and Create NetFireWallRule
Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock';
if ($Args[0] -ne "delete") {
  New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $Ports -Action Allow -Protocol TCP;
  New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $Ports -Action Allow -Protocol TCP;

# Add each port into portproxy
$Addr = ""
Foreach ($Port in $Ports) {
    iex "netsh interface portproxy delete v4tov4 listenaddress=$Addr listenport=$Port | Out-Null";
    if ($Args[0] -ne "delete") {
        iex "netsh interface portproxy add v4tov4 listenaddress=$Addr listenport=$Port connectaddress=$WSL connectport=$Port | Out-Null";

# Display all portproxy information
netsh interface portproxy show v4tov4;

# Give user to chance to see above list when relaunched start
If ($Args[0] -eq "runas" -Or $Args[1] -eq "runas") {
  Write-Host -NoNewLine 'Press any key to close! ';
  $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Powercfg -setacvalueindex scheme_current sub_processor PERFBOOSTMODE 0
Powercfg -setactive scheme_current
Get-ChildItem -Path bin -Recurse | Remove-Item -Recurse -Force -Verbose
Get-ChildItem -Path obj -Recurse | Remove-Item -Recurse -Force -Verbose
class TrustAll : System.Net.ICertificatePolicy 
  [bool]CheckValidationResult([System.Net.ServicePoint]$sp, [System.Security.Cryptography.X509Certificates.X509Certificate]$cert, [System.Net.WebRequest]$request, [int]$problem)
    return $true

[System.Net.ServicePointManager]::CertificatePolicy = [TrustAll]::new()
[PSCustomObject]$param = [PSCustomObject](Get-Content .\parameters.json | Out-String | ConvertFrom-Json)

Fri Jan 27 2023 06:37:08 GMT+0000 (UTC)

#powershell #activedirectory

Mon Jan 02 2023 21:53:55 GMT+0000 (UTC)


Sun Jan 01 2023 20:21:31 GMT+0000 (UTC)


Thu Dec 08 2022 19:46:48 GMT+0000 (UTC)


Thu Dec 01 2022 01:27:11 GMT+0000 (UTC)


Wed Nov 30 2022 04:19:22 GMT+0000 (UTC)


Fri Nov 25 2022 05:39:41 GMT+0000 (UTC)


Mon Nov 21 2022 22:58:53 GMT+0000 (UTC)


Mon Nov 21 2022 22:58:03 GMT+0000 (UTC)


Fri Nov 18 2022 20:07:55 GMT+0000 (UTC)

#powershell #security

Tue Nov 15 2022 21:54:03 GMT+0000 (UTC)


Mon Oct 31 2022 02:56:23 GMT+0000 (UTC)

#powershell #file #filesystem #measure

Wed Sep 21 2022 20:38:16 GMT+0000 (UTC) undefined

#powershell #windows #sql #pwsh

Fri Jul 08 2022 07:07:21 GMT+0000 (UTC)


Fri Jul 08 2022 07:05:25 GMT+0000 (UTC)


Tue Jul 05 2022 10:30:57 GMT+0000 (UTC)


Tue Jul 05 2022 10:28:31 GMT+0000 (UTC)


Tue Jul 05 2022 10:25:58 GMT+0000 (UTC)


Tue Jul 05 2022 10:22:06 GMT+0000 (UTC)


Tue Jul 05 2022 10:20:02 GMT+0000 (UTC)


Tue Jul 05 2022 10:19:07 GMT+0000 (UTC)


Tue Jul 05 2022 10:14:54 GMT+0000 (UTC)


Tue Jul 05 2022 10:07:12 GMT+0000 (UTC)


Tue Jun 21 2022 23:59:51 GMT+0000 (UTC)

#powershell #ping

Tue Jun 14 2022 20:24:44 GMT+0000 (UTC)


Tue May 24 2022 20:02:11 GMT+0000 (UTC)

#powershell #ping

Tue May 24 2022 19:33:27 GMT+0000 (UTC)


Tue Mar 01 2022 18:06:57 GMT+0000 (UTC)


Tue Mar 01 2022 12:57:10 GMT+0000 (UTC)


Mon Feb 28 2022 20:01:16 GMT+0000 (UTC)


Wed Feb 02 2022 22:15:45 GMT+0000 (UTC)

#installation #linux #bash #wsl #powershell

Wed Feb 02 2022 21:37:35 GMT+0000 (UTC)

#windows #powershell

Wed Feb 02 2022 21:32:02 GMT+0000 (UTC)

#powershell #windows #cmd

Sun Jan 23 2022 11:52:23 GMT+0000 (UTC)

#wsl #wsl2 #windows #powershell #terminal #commands

Thu Jan 20 2022 23:52:33 GMT+0000 (UTC)

#fisher #powershell #terminal

Mon Dec 27 2021 12:25:33 GMT+0000 (UTC)

#bash #powershell

Wed Dec 01 2021 08:41:07 GMT+0000 (UTC)

#powershell #docker #pods #restart

Wed Nov 17 2021 20:04:25 GMT+0000 (UTC)


Mon Nov 08 2021 14:20:28 GMT+0000 (UTC)

#powershell #filter

Mon Oct 25 2021 17:48:18 GMT+0000 (UTC)

#powershell #k8s #spn #reset #expired #expire

Thu Sep 30 2021 15:25:52 GMT+0000 (UTC)


Fri Sep 24 2021 17:49:04 GMT+0000 (UTC)


Sat Sep 04 2021 08:05:25 GMT+0000 (UTC)

#bash #powershell

Mon Aug 30 2021 00:44:14 GMT+0000 (UTC)


Thu Jul 01 2021 14:13:17 GMT+0000 (UTC)


Mon Aug 17 2020 21:56:14 GMT+0000 (UTC)


Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension