Snippets Collections
$folder = (New-Object -ComObject Shell.Application).NameSpace("$pwd")
# Note: Assumes that no indices higher than 1000 exist.
0..1000 | % { 
  if ($n = $folder.GetDetailsOf($null, $_)) { 
    [pscustomobject] @{ Index = $_; Name = $n } 
  } 
}
Get-PSReadLineKeyHandler -Bound -Unbound

Key                   Function                Description
---                   --------                -----------
Enter                 AcceptLine              Accept the input or move to the next line if input is missing a closing token.
Shift+Enter           AddLine                 Move the cursor to the next line without attempting to execute the input
Escape                RevertLine              Equivalent to undo all edits (clears the line except lines imported from history)
LeftArrow             BackwardChar            Move the cursor back one character
RightArrow            ForwardChar             Move the cursor forward one character
Ctrl+LeftArrow        BackwardWord            Move the cursor to the beginning of the current or previous word
Ctrl+RightArrow       NextWord                Move the cursor forward to the start of the next word
Shift+LeftArrow       SelectBackwardChar      Adjust the current selection to include the previous character
Shift+RightArrow      SelectForwardChar       Adjust the current selection to include the next character
Ctrl+Shift+LeftArrow  SelectBackwardWord      Adjust the current selection to include the previous word
Ctrl+Shift+RightArrow SelectNextWord          Adjust the current selection to include the next word
UpArrow               PreviousHistory         Replace the input with the previous item in the history
DownArrow             NextHistory             Replace the input with the next item in the history
Home                  BeginningOfLine         Move the cursor to the beginning of the line
End                   EndOfLine               Move the cursor to the end of the line
Shift+Home            SelectBackwardsLine     Adjust the current selection to include from the cursor to the end of the line
Shift+End             SelectLine              Adjust the current selection to include from the cursor to the start of the line
Delete                DeleteChar              Delete the character under the cursor
Backspace             BackwardDeleteChar      Delete the character before the cursor
Ctrl+Spacebar         MenuComplete            Complete the input if there is a single completion, otherwise complete the input by selecting from a menu o...
Tab                   TabCompleteNext         Complete the input using the next completion
Shift+Tab             TabCompletePrevious     Complete the input using the previous completion
Ctrl+a                SelectAll               Select the entire line. Moves the cursor to the end of the line
Ctrl+c                CopyOrCancelLine        Either copy selected text to the clipboard, or if no text is selected, cancel editing the line with Cancel...
Ctrl+C                Copy                    Copy selected region to the system clipboard.  If no region is selected, copy the whole line
Ctrl+l                ClearScreen             Clear the screen and redraw the current line at the top of the screen
Ctrl+r                ReverseSearchHistory    Search history backwards interactively
...
> powershell -command "Get-ChildItem -Path C:\ -Recurse | Sort-Object Length -Descending | Select-Object FullName, Length -First 20 | Format-Table -AutoSize";
Get-ChildItem ".\FileStore" |
Select-Object Name, PSPath |
Add-Member -MemberType MemberSet `
           -Name PSStandardMembers `
           -Value ([System.Management.Automation.PSPropertySet]::new(
                      'DefaultDisplayPropertySet',
                      [string[]]('Name')
                  )) `
           -PassThru |
Out-GridView -PassThru -Title "Quick Notes" |
Get-Content | Set-Clipboard
   # Create the new ACE  
   $identity = 'domain\group'  
   $rights = 'FullControl'  
   $type = 'Allow'  
     
   # Folders and files inherit this permission, no need to propagate because it will be inherited  
   $inheritance = 'ContainerInherit, ObjectInherit'  
   $propagate = 'None'  
     
   $ace = New-Object System.Security.AccessControl.FileSystemAccessRule($identity, $rights, $inheritance, $propagate, $type)  
     
   # Apply to existing file system object  
   $acl = Get-Acl -Path 'YourPath'  
   $acl.AddAccessRule($ace)  
   Set-Acl -Path 'YourPath' -AclObject $acl  
<#
Run Get-ExecutionPolicy. If it returns Restricted, then run Set-ExecutionPolicy AllSigned or Set-ExecutionPolicy Bypass -Scope Process.
Now run the following command:
#>

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'))
$parent = "C:\Users\user\Desktop\derp"
$pl = $parent.Length
$dest = "C:\Users\user\Desktop\test"
$empty = get-childitem $parent -recurse | 
Where-Object { $_.PSIsContainer } |   
Where-Object { $_.GetFiles().Count -eq 0 } |   
Where-Object { $_.GetDirectories().Count -eq 0 } |    
ForEach-Object { $_.FullName }  

foreach ($item in $empty) {
Write-Host $item
$object= Get-Item $item
      if($object.parent.fullname.length -gt $pl){
                
                $OParentPath = $object.FullName
                $last = $OParentPath.Substring($pl)
                $newDest = $dest+$last
                mkdir -Path $newDest
                Remove-Item $item

                }
      Else{Move-Item $item -Destination $dest}

      }
    
  
Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue |
    Where-Object { $_.Length -gt 100MB } |
    Sort-Object Length -Descending |
    Select-Object @{Name='FullName'; Expression={$_.FullName}},
                  @{Name='Size'; Expression={
                      if ($_.Length -ge 1GB) {
                          [math]::Round($_.Length / 1GB, 2) + ' GB'
                      } elseif ($_.Length -ge 1MB) {
                          [math]::Round($_.Length / 1MB, 2) + ' MB'
                      } else {
                          [math]::Round($_.Length / 1KB, 2) + ' KB'
                      }
                  }} |
    Format-Table -AutoSize


FullName                                           Size 
--------                                           ----------
C:\some\path\to\largefile1.ext                      123.45 MB
C:\another\path\to\largefile2.ext                   110.98 MB
Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue |
    Where-Object { $_.Length -gt 100MB } |
    Sort-Object Length -Descending |
    Select-Object @{Name='FullName'; Expression={$_.FullName}},
                  @{Name='Size (MB)'; Expression={[math]::Round($_.Length / 1MB, 2)}} |
    Format-Table -AutoSize

FullName                                           Size (MB)
--------                                           ----------
C:\some\path\to\largefile1.ext                      123.45
C:\another\path\to\largefile2.ext                   110.98
Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.Length -gt 100MB } | Sort-Object Length -Descending | Select-Object FullName, Length | Format-Table -AutoSize
get-command -Module ISEScriptingGeek
Function ExcelToCsv ($File) {
    $Excel = New-Object -ComObject Excel.Application
    $wb = $Excel.Workbooks.Open($File)

    $x = $File | Select-Object Directory, BaseName
    $n = [System.IO.Path]::Combine($x.Directory, (($x.BaseName, 'csv') -join "."))

    foreach ($ws in $wb.Worksheets) {
        $ws.SaveAs($n, 6)
    }
    $Excel.Quit()
}

Get-ChildItem C:\Junk\*.xlsx |
    ForEach-Object{
        ExcelToCsv -File $_
    }
# need to try this:
# https://learn.microsoft.com/en-us/azure/batch/quick-run-python

# connect to Azure account:
Connect-AzAccount

# view resource groups 
Get-AzResourceGroup |Format-Table

# list batch accounts
Get-AzBatchAccount

# view batch account info, first create $context parameter:
# https://learn.microsoft.com/en-us/azure/batch/batch-powershell-cmdlets-get-started
$context = Get-AzBatchAccountKeys -AccountName osbatchaccount
# now run this command:
Get-AzBatchPool -Id "osbatchpool" -BatchContext $context

# delete batch account:
Remove-AzBatchAccount -AccountName <account_name>
  
# view batch node information
# https://learn.microsoft.com/en-us/powershell/module/az.batch/?view=azps-11.0.0
Get-AzBatchComputeNode -PoolId "osbatchpool" -Id "nodeid" -BatchContext $context

# view files and URL on a node in batch pool
Get-AzBatchComputeNode "osbatchpool" -Id "nodeid" -BatchContext $context | Get-AzBatchNodeFile -BatchContext $context
#--------------------------------------------------------------------------------
# check if python is installed using powershell:
if ($pythonPath) {
    # Python is installed, get the version
    $pythonVersion = & $pythonPath --version 2>&1
    Write-Output "Python is installed. Version: $pythonVersion"
} else {
    Write-Output "Python is not installed on this node."
}
#--------------------------------------------------------------------------------
# commant to execute PS script 
powershell.exe -ExecutionPolicy Unrestricted -File CheckPython.ps1

# display all system variables unsing Powershell:
dir env:

# remove a single task in azure batch job
Remove-AzBatchTask -JobId "myjob" -Id "mytask10" -BatchContext $context
#--------------------------------------------------------------------------------
# remove all tsks in a batch job:
# Get all tasks in the specified job
$jobId = "adfv2-osbatchpool"
$tasks = Get-AzBatchTask -JobId $jobId -BatchContext $context
# Remove each task in the job
foreach ($task in $tasks) {
     Remove-AzBatchTask -JobId $jobId -Id $task.Id -BatchContext $context
 }
Write-Host "All tasks in the job have been removed."
Invoke-Expression "& {$(Invoke-RestMethod get.scoop.sh)} -RunAsAdmin"
# Install
winget install JanDeDobbeleer.OhMyPosh -s winget

# Install a NERD Font
oh-my-posh font install

# Edit $PROFILE
notepad $PROFILE

# If $POROFILE doesn't exist:
# New-Item -Path $PROFILE -Type File -Force

// Inside $PROFILE
# Dark cool one
#oh-my-posh init pwsh --config 'https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/1_shell.omp.json' | Invoke-Expression

# Lighter
oh-my-posh init pwsh --config 'https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/catppuccin_latte.omp.json' | Invoke-Expression
type $env:USERPROFILE\.ssh\id_rsa.pub | 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 "$username@domain.com" -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
System.DateTime

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
2020

PS> (Get-Date).DayOfWeek
Sunday

PS> (Get-Date).Month
11

PS> (Get-Date).DayOfYear
327



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
True


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:

ToLongDateString()
ToShortDateString()
ToLongTimeString()
ToShortTimeString()
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
11/22/2020

#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

# https://stackoverflow.com/questions/11251034/find-guid-from-msi-file
function Get-MSIProperties {
  param (
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [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
    [System.GC]::Collect()
  }
}
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 )
}
$people
Compare-Object $(Get-Content .\TestDoc1.txt) $(Get-Content .\TestDoc2.txt) | Out-File .\TestDoc3.txt
$output = for ($i = 0; $i -le 10; $i++) {
  [pscustomobject]@{
      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 {    
    [ValidateNotNullOrEmpty()]
    [string]$Name    
    
    [ValidateRange(0,40)]
    [int]$Id
}

[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 {
    $name
    $location
    $age
}

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

$list.add($person)
### 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"
				EXIT
			}
			$iterations++
			$pwdBytes = @()
			$rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
			Do {
				[byte[]]$byte = [byte]1
				$rng.GetBytes($byte)
				If ($byte[0] -lt 33 -or $byte[0] -gt 126) {
					CONTINUE
				}
                $pwdBytes += $byte[0]
			}
			While ($pwdBytes.Count -lt $passwordNrChars)
				$pwd = ([char[]]$pwdBytes) -join ''
			} 
        Until (confirmPasswordIsComplex $pwd)
        Return $pwd
	}
}
<#
.SYNOPSIS

Send email with optional attachments

.DESCRIPTION

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.


.INPUTS

None

.OUTPUTS

None

.EXAMPLE

PS> .\Send-Email.ps1
Send-Email -EmailTo "user@yourdomain.co.uk" -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

.EXAMPLE

PS> .\Send-Email.ps1
$EmailRecipients = @("user@yourdomain.co.uk","user2@yourdomain.co.uk","admin@yourdomain.co.uk")
Send-Email -EmailTo $EmailRecipients -EmailSubject "Test message" -EmailBody "Hello"

These commands send an email to multiple recipients

.EXAMPLE

PS> .\Send-Email.ps1
Send-Email -EmailTo "user@yourdomain.co.uk" -EmailFrom "admin@yourdomain.co.uk" -EmailSMTPServer "mailserver.yourdomain.co.uk" -EmailSubject "Log file attached" -EmailBody "Please find attached the log file" -EmailAttachments "C:\logs\Logfile.txt"

This command shows all parameters

.LINK
https://www.techexplorer.co.uk/powershell-script-to-send-email-with-optional-attachments

#>



#--------------------------------------------------------------------------------
#        Script: Send-Email.ps1
#      Author: Dan Tonge, www.techexplorer.co.uk
#     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
{
    Param
        (
            [parameter(Mandatory=$true,HelpMessage="Email To Address")] $EmailTo,
            [parameter(HelpMessage="Email From Address")] $EmailFrom = [String]$env:computerName.ToLower() + '@yourdomain.co.uk',
            [parameter()] $EmailSMTPServer = 'mailserver.yourdomain.co.uk',
            [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
    # http://stackoverflow.com/questions/14560270/send-mailmessage-attachments-will-not-accept-null-for-any-variables
    $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

IsReadOnly
----------
     False
# Author cvucic (https://forums.malwarebytes.com/topic/135344-remote-or-unattended-uninstall/?do=findComment&comment=891527)

Function List-Programs {
    [cmdletbinding()]
    [cmdletbinding()]
    param(
    [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]$ComputerName = $env:computername
    )

    begin {
        $UninstallRegKey="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
    }

    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 {
    [cmdletbinding()]
    param (
    [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [string]$ComputerName = $env:computername,
    [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
    [string]$UninstallKey
    )
    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 {
    param($computername)
    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"
        Break
    }
}

Uninstall-MBAM -computername $env:computername

$TcpClient = New-Object System.Net.Sockets.TcpClient
[byte[]]$buffer = ,0 * 64
$TcpClient.Connect('time.nist.gov', 13)
$TcpStream = $TcpClient.GetStream()
$length = $TcpStream.Read($buffer, 0, $buffer.Length);
[void]$TcpClient.Close()
$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."
    $existing.SetPassword($Password)
}

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"
$printer
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 "olegserdia@gmail.com"


# if you see an error: WARNING: UNPROTECTED PRIVATE KEY FILE!
# then cd to a folder with files and run this in PS:
icacls * /reset /t /c /q   # https://superuser.com/questions/106181/equivalent-of-chmod-to-change-file-permissions-in-windows

# 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 git@github.com:Serdia/azure-resume.git

######################################################################
						### 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 git@github.com:Serdia/Flask_WeatherApp.git master


######################################################################
# Troubleshooting

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

#if error: Error loading key "C:/Users/oserdyuk/.ssh/id_rsa.pub": 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/id_rsa.pub   # click Enter to ignore password

git clone git@github.com:ACloudGuru-Resources/acg-project-azure-resume-starter.git

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

# service OpenSSH Authentification Agent. Make sure it's running.
C:\WINDOWS\System32\OpenSSH\ssh-agent.exe
# 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
then
   echo "ssh-agent is already running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
else
eval `ssh-agent -s`
fi


# 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/id_rsa.pub

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



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

ssh-add ~/.ssh my_id_rsa
Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
for ($num = 1 ; $num -le 10 ; $num++) { mkdir "your-prefix-$num"}
# make sure the module is installed:
Install-Module -Name ReportingServicesTools

# add computername to trusted hosts list to be able to connect remotely
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "POWERBI"

# view content of the folder
$reportServerUri = 'http://10.36.8.17/ReportServer/'
$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 = "http://10.36.8.17/Reports"
Get-RsRestItemDataSource -RsItem "/AFH/GrossBudget" -ReportPortalUri $ReportPortalUri

# Get connection string info for "Construction - AY Loss Ratios" report
$ReportPortalUri = "http://10.36.8.17/Reports"
Get-RsRestItemDataSource -RsItem "/AFH/Align General/Programs/Construction - AY Loss Ratios" -ReportPortalUri $ReportPortalUri

#----------------------------------------------------------------------------------------------
#----------Change connection string username and passwork in PowerBI reports-------------------
#----------------------------------------------------------------------------------------------

# connect remotely to POWERBI server
Enter-PSSession -ComputerName POWERBI -Credential ssrsserviceaccount
# specify parameters
$ReportPortalUri = "http://10.36.8.17/Reports"
$ReportName = '/AFH/Catalytic/Underwriter Reports/Underwriter Production'
$Username = 'catalyticSSRS'
$Password = 'RND1101!'
$ServerName = '10.36.8.18'
# grab parameters that are currently exists in a report
$parameters = Get-RsRestItemDataModelParameters $ReportName -ReportPortalUri $ReportPortalUri
$parameters
# Map to a dictionary to access the parameter values.
$parameterdictionary = @{}
foreach ($parameter in $parameters) { $parameterdictionary.Add($parameter.Name, $parameter); }
# change parameter value. "ServerName" or "datasource" whatever the name of the parameter in PowerBI
$parameterdictionary[“ServerName”].Value = $ServerName
# update parameters that are currentl in a report
Set-RsRestItemDataModelParameters -RsItem $ReportName -ReportPortalUri $ReportPortalUri -DataModelParameters $parameters
# print what changed
$parameterdictionary.Values
# 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 https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb

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

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

# Install PowerShell
sudo apt-get install -y powershell

# Start PowerShell
pwsh
© 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"
$Shortcut.Save()
 
$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: https://fishshell.com/
* Fisher: https://github.com/jorgebucaran/fisher
* Shellder: https://github.com/simnalamburt/shellder
* Nerd fonts: https://github.com/ryanoasis/nerd-fonts
* z for fish: https://github.com/jethrokuan/z
* Exa: https://the.exa.website/
* ghq: https://github.com/x-motemen/ghq
* peco: https://github.com/peco/peco
wsl --shutdown
diskpart
# open window Diskpart
select vdisk file="C:\WSL-Distros\…\ext4.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
exit
kubectl rollout restart deploy -n cnext-di-demo
<#  
.SYNOPSIS  
    Format-TSQL will format tsql script supplied per options set
.DESCRIPTION  
    This script will strip supplied code of comments format per options
.NOTES  
    Author     : Mala Mahadevan (malathi.mahadevan@gmail.com)
  
.PARAMETERS
-InputScript: text file containing T-SQL
    -OutputScript: name of text file to be generated as output
.LIMITATIONS
Strips code of comments
.LINK  
    

.HISTORY
2021.08.08First version for sqlservercentral.com
#>
function Format-TSQL
{
   
    #Defining parameter for scriptname
    [CmdletBinding()]
    param(
           [System.IO.FileInfo[]]$InputScript,
           [String]$OutputScript
    )
    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 
    #1002
    #1103
    #1204
    #1305
    #1406 
    #1507
    #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
    $generate.GenerateScript($fragment,([ref]$formattedoutput)) 
    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" |
     ForEach-Object{
          if(Test-Connection $_ -Count 1 -quiet){
               "$_ Up"
          }else{
               "$_ 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"
[cmdletbinding()]
param(
 [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
$desiredFile.Close()
$desiredFile.Dispose()

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"
}
else
{
 Write-Verbose "Setting GalleryFlag to Private"
 $xml.PackageManifest.MetaData.GalleryFlags = ""
}

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

$desiredFile.BaseStream.SetLength(0)
$desiredFile.Write($xml.InnerXml)
$desiredFile.Flush()
$desiredFile.Close()

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

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()

$desiredFile.BaseStream.SetLength(0)
$desiredFile.Write($text)
$desiredFile.Flush()
$desiredFile.Close()

$fileZip.Dispose()

if($ShareWith -ne $null)
{
 $ShareWith = "--share-with" + $ShareWith
}
else
{
 $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;
    exit;
} 

# 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
  exit
}

# 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.";
  exit;
}

# 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 = "0.0.0.0"
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)
star

Sat Oct 05 2024 17:35:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64597009/use-powershell-to-edit-a-files-metadata-details-tab-of-a-file-in-windows-file

#powershell #metadata #file #properties
star

Wed Sep 25 2024 08:49:19 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs

#win10 #win11 #powershell #openssh #ssh
star

Tue Aug 13 2024 15:51:47 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/powershell/module/psreadline/get-psreadlinekeyhandler?view

#powershell #psreadline
star

Tue Jul 30 2024 01:01:41 GMT+0000 (Coordinated Universal Time)

#powershell #windows11 #system #performance
star

Mon Jul 29 2024 02:25:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53323526/select-object-with-out-gridview

#powershell #out-gridview
star

Mon Jul 29 2024 00:35:27 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/answers/questions/1118931/powershell-on-modifying-permissions

#powershell
star

Tue Jul 23 2024 20:16:06 GMT+0000 (Coordinated Universal Time) https://docs.chocolatey.org/en-us/choco/setup/

#powershell
star

Thu Jun 20 2024 09:12:43 GMT+0000 (Coordinated Universal Time) https://community.spiceworks.com/t/powershell-move-folders-from-txt-file-to-another-drive-with-dir-structure/715354

#powershell
star

Sun Apr 07 2024 04:19:30 GMT+0000 (Coordinated Universal Time) https://docs.openinterpreter.com/getting-started/setup

#windows #powershell
star

Sun Dec 10 2023 01:23:36 GMT+0000 (Coordinated Universal Time) https://jdhitsolutions.com/blog/powershell/4169/friday-fun-updated-ise-scripting-geek-module/

#powershell
star

Sat Dec 09 2023 16:47:49 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/answers/questions/597931/convert-xlsx-to-csv-using-powershell

#powershell
star

Sat Nov 18 2023 22:30:16 GMT+0000 (Coordinated Universal Time)

#powershell #ping
star

Tue May 09 2023 08:44:14 GMT+0000 (Coordinated Universal Time) https://adamtheautomator.com/scoop-windows/

#powershell
star

Sat Feb 11 2023 11:28:28 GMT+0000 (Coordinated Universal Time)

#powershell
star

Sun Feb 05 2023 10:29:19 GMT+0000 (Coordinated Universal Time)

#powershell #ssh
star

Fri Jan 27 2023 06:37:08 GMT+0000 (Coordinated Universal Time) https://www.thefunkytechguy.co.za

#powershell #activedirectory
star

Fri Jan 27 2023 04:46:32 GMT+0000 (Coordinated Universal Time)

#powershell #activedirectory
star

Mon Jan 02 2023 21:53:55 GMT+0000 (Coordinated Universal Time) https://adamtheautomator.com/powershell-get-date/

#powershell
star

Sun Jan 01 2023 20:21:31 GMT+0000 (Coordinated Universal Time) https://reactnative.dev/docs/environment-setup

#powershell
star

Thu Dec 08 2022 19:46:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11251034/find-guid-from-msi-file

#powershell
star

Thu Dec 01 2022 01:27:11 GMT+0000 (Coordinated Universal Time) https://www.jonathanmedd.net/2015/01/how-to-make-use-of-functions-in-powershell.html

#powershell
star

Wed Nov 30 2022 04:19:22 GMT+0000 (Coordinated Universal Time)

#powershell
star

Fri Nov 25 2022 05:39:41 GMT+0000 (Coordinated Universal Time) https://www.delftstack.com/zh/howto/powershell/powershell-export-to-text/

#powershell
star

Mon Nov 21 2022 22:58:53 GMT+0000 (Coordinated Universal Time)

#powershell
star

Mon Nov 21 2022 22:58:03 GMT+0000 (Coordinated Universal Time)

#powershell
star

Fri Nov 18 2022 20:07:55 GMT+0000 (Coordinated Universal Time) https://github.com/zjorz/Public-AD-Scripts/blob/master/Reset-KrbTgt-Password-For-RWDCs-And-RODCs.ps1

#powershell #security
star

Tue Nov 15 2022 21:54:03 GMT+0000 (Coordinated Universal Time) https://www.techexplorer.co.uk/windows/powershell-script-to-send-email-with-optional-attachments/

#powershell
star

Mon Oct 31 2022 02:56:23 GMT+0000 (Coordinated Universal Time) https://shellgeek.com/powershell-get-file-size/

#powershell #file #filesystem #measure
star

Wed Sep 21 2022 20:38:16 GMT+0000 (Coordinated Universal Time) undefined

#powershell #windows #sql #pwsh
star

Fri Jul 08 2022 07:07:21 GMT+0000 (Coordinated Universal Time) https://4sysops.com/archives/set-and-remove-the-read-only-file-attribute-with-powershell/

#powershell
star

Fri Jul 08 2022 07:05:25 GMT+0000 (Coordinated Universal Time) https://4sysops.com/archives/set-and-remove-the-read-only-file-attribute-with-powershell/

#powershell
star

Tue Jul 05 2022 10:30:57 GMT+0000 (Coordinated Universal Time) https://forums.malwarebytes.com/topic/135344-remote-or-unattended-uninstall/?do=findComment&comment=891527

#powershell
star

Tue Jul 05 2022 10:28:31 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jul 05 2022 10:25:58 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jul 05 2022 10:24:20 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jul 05 2022 10:22:06 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jul 05 2022 10:20:02 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jul 05 2022 10:19:07 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jul 05 2022 10:14:54 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jul 05 2022 10:07:12 GMT+0000 (Coordinated Universal Time)

#powershell
star

Tue Jun 21 2022 23:59:51 GMT+0000 (Coordinated Universal Time)

#powershell #ping
star

Tue Jun 14 2022 20:24:44 GMT+0000 (Coordinated Universal Time) https://www.useweb.fr/blog/developpement/post/scoop-package-manager/

#powershell
star

Wed Jun 01 2022 12:50:48 GMT+0000 (Coordinated Universal Time)

#powershell #mkdir #windows
star

Wed Jun 01 2022 12:49:06 GMT+0000 (Coordinated Universal Time)

#powershell #mkdir #windows
star

Tue May 24 2022 20:02:11 GMT+0000 (Coordinated Universal Time)

#powershell #ping
star

Tue May 24 2022 19:33:27 GMT+0000 (Coordinated Universal Time) https://techsprobe.com/install-macos-big-sur-on-virtualbox-on-windows-pc/

#powershell
star

Tue Mar 01 2022 18:06:57 GMT+0000 (Coordinated Universal Time) https://github.community/t/commit-timestamps-in-github-dont-match-repo/127766

#powershell
star

Tue Mar 01 2022 12:57:10 GMT+0000 (Coordinated Universal Time) https://www.proservices-informatique.fr/activer-dns-over-https-windows/

#powershell
star

Mon Feb 28 2022 20:01:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/16460163/ps1-cannot-be-loaded-because-the-execution-of-scripts-is-disabled-on-this-syste/16461056

#powershell
star

Wed Feb 02 2022 22:15:45 GMT+0000 (Coordinated Universal Time) https://github.com/jimbrig/dotfiles-wsl/blob/main/scripts/dev/scripts/install-pwsh.sh

#installation #linux #bash #wsl #powershell
star

Wed Feb 02 2022 21:37:35 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/43494863/start-process-workingdirectory-as-administrator-does-not-set-location

#windows #powershell
star

Wed Feb 02 2022 21:32:02 GMT+0000 (Coordinated Universal Time) https://superuser.com/questions/1560049/open-windows-terminal-as-admin-with-winr/1560192

#powershell #windows #cmd
star

Sun Jan 23 2022 11:52:23 GMT+0000 (Coordinated Universal Time) https://ubuntu.com/tutorials/ubuntu-on-windows#1-overview

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

Thu Jan 20 2022 23:52:33 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v

#fisher #powershell #terminal
star

Mon Dec 27 2021 12:25:33 GMT+0000 (Coordinated Universal Time) https://github.com/microsoft/WSL/issues/4699#issuecomment-627133168

#bash #powershell
star

Wed Dec 01 2021 08:41:07 GMT+0000 (Coordinated Universal Time)

#powershell #docker #pods #restart
star

Wed Nov 17 2021 20:04:25 GMT+0000 (Coordinated Universal Time) https://www.sqlservercentral.com/articles/formatting-t-sql-scripts-using-scriptdom-and-powershell

#powershell
star

Mon Nov 08 2021 14:20:28 GMT+0000 (Coordinated Universal Time) https://adamtheautomator.com/powershell-where-object/

#powershell #filter
star

Wed Nov 03 2021 21:37:07 GMT+0000 (Coordinated Universal Time)

#powershell #ping
star

Mon Oct 25 2021 17:48:18 GMT+0000 (Coordinated Universal Time) https://docs.microsoft.com/en-us/azure/aks/update-credentials?WT.mc_id=Portal-Microsoft_Azure_Expert#update-aks-cluster-with-new-service-principal-credentials

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

Thu Sep 30 2021 15:25:52 GMT+0000 (Coordinated Universal Time) https://wouterdekort.com/2016/03/07/modifying-a-vsix-file-before-publishing/

#powershell
star

Fri Sep 24 2021 17:49:04 GMT+0000 (Coordinated Universal Time)

#powershell
star

Sat Sep 04 2021 08:05:25 GMT+0000 (Coordinated Universal Time)

#bash #powershell
star

Mon Aug 30 2021 00:44:14 GMT+0000 (Coordinated Universal Time)

#powershell
star

Thu Jul 01 2021 14:13:17 GMT+0000 (Coordinated Universal Time)

#powershell
star

Sat Mar 13 2021 11:38:25 GMT+0000 (Coordinated Universal Time)

#powershell #certificate
star

Mon Aug 17 2020 21:56:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/35863103/how-to-load-a-json-file-and-convert-it-to-an-object-of-a-specific-type

#powershell

Save snippets that work with our extensions

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