PowerShell

Collection of useful one-liners and simple scripts

Check Win11 Status

$computerName = $env:COMPUTERNAME
  $searcher = New-Object DirectoryServices.DirectorySearcher
  $searcher.Filter = "(&(objectCategory=computer)(name=$computerName))"
  $result = $searcher.FindOne()
  
  if ($result -ne $null) {
      $ou = $result.Path
  } else {
      Write-Output "Computer $computerName not found in AD."
  }
  
  
  $target = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate' | select ProductVersion ,TargetReleaseVersionInfo
  
  Write-Output "$OU"
  Write-Output "Target Release: $($target.ProductVersion) $($target.TargetReleaseVersionInfo)"

type clipboard as keypresses


  
  # countdown
  "Pasting in 5 seconds..."
  5; Start-Sleep -Seconds 1
  4; Start-Sleep -Seconds 1
  3; Start-Sleep -Seconds 1
  2; Start-Sleep -Seconds 1
  1; Start-Sleep -Seconds 1
  0; 'Pasting now...'
  
  
  
  
  $clip = (Get-Clipboard)
  $clip = $clip -replace '{', '__{__' -replace '}', '__}__'
  $clip = $clip -replace '__{__', '{{}' -replace '__}__', '{}}'
  $clip = $clip -join '{ENTER}' # replace newlines with ENTER keypress
  [System.Windows.Forms.SendKeys]::SendWait($clip)
  
  
  
  <#
  
  NOTES:
  SendKeys uses curly braces as a special character, 
  and you have to escape them withmore curly braces, 
  so I pad them first before escaping so you dont escape the escapes
  
  { --> {{}
  } --> {}}
  
  #>
  

PowerShell History File

(Get-PSReadLineOption).HistorySavePath
  
  # OR
  echo "C:\Users\$env:USERNAME\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt"

Get-TeamsOnlyOwnerReport

This will list the Teams that a user is the only owner of.

Connect-MicrosoftTeams
  $user = Read-Host "User"
  
  # get all teams that user is a member of
  $teams = Get-Team -User $user
  
  # get the owners of all teams that user is a member of
  $ownerReport = ForEach ($team in $teams) {
      Get-TeamUser -GroupId $team.GroupID -Role Owner | Add-Member -NotePropertyName "Team" -NotePropertyValue $team.DisplayName -PassThru | select Team,user,role
  }
  
  # get teams where that user is the ONLY owner
  $ownerReport | Group-Object -Property team | ? Count -EQ 1 | % {$_.group | ? User -EQ $user}

Fix-Csv

This isnt working yet…


  function Fix-Csv {
      param (
          [string[]]$Path
      )
  
      # try to import csv. dump error to $e
      Import-Csv $Path -ErrorVariable e
  
      # grab text in quotes
      $e.message -match '"([^"]+)"'
      $dupe = $matches[1]
  
      # get csv header. (first line of text)
      $header = gc $Path -First 1
  
      # replace the first occurence with "junk"
      [regex]$pattern = $dupe
      $header = $pattern.replace($header, "junk", 1)
      $header = $header -split ','   # turn comma separated list into multi-line string
      $header | % {$_-replace '"'}           # Strip Quotes
  
      # import again with new header
      $x = Import-Csv $Path -Header $header
      $x
  }

o365 sign-in asn lookup

This takes the ASN from the sign-in log and gets the associated name. I’m not sure if you can do anything with it, but its interesting data. Legit sign-ins are probably only from a few ASNs, but to my knowledge, you cant block access by ASN.

# NOTE: ($x is o365 sign-in logs csv)
  
  $asn = $x | ? status -Like "Success" | select -ExpandProperty 'Autonomous system  number'
  $dump = $asn | Group-Object |sort -Property count | select Count,Name
  
  # this might take a long time. There is probably a more efficient way to do the lookups
  $AsnTable = foreach ($item in $dump ) {
    @(
      $detail = $item | %{ gc .\Downloads\asn.txt | sls "^$($_.name) "} # <--- sls is probably the slow part
      @{Count=$item.Count;ASN=$item.Name;Detail=$detail}
    ) | % { New-Object object | Add-Member -NotePropertyMembers $_ -PassThru } | select Count,ASN,Detail
  }

get Process CommandLine

$process = "notepad.exe"
  Get-CimInstance Win32_Process -Filter "name = '$process'" | select CommandLine 
  
  
  
  get-process notepad.exe | select-object ProcessName, CommandLine

get list of installed software

Get-WmiObject -Class Win32_Product | ? Name -like "*SQL Server 2012*" 

Search-BitLockerRecoveryInfo.ps1

param
  (
      [Parameter(Mandatory)]$search
  )
  
  
  # Get user input if not specified in param
  if (!$search){
    $search = Read-Host "Computer Name or Recovery Key ID"
  }
  
  # Get all the recovery objects from AD
  $AllRecoveryInformation = Get-AdObject -Filter 'objectClass -eq "msFVE-RecoveryInformation"'
  # Search for matching key
  $FoundKeys = $AllRecoveryInformation |Where-Object DistinguishedName -like "*$search*" | Get-ADObject -Properties *
  # Display results
  $FoundKeys | select "msFVE-*","whenChanged","whenCreated","DistinguishedName"

Windows Sandbox

sandbox.wsb

<Configuration>
    <VGpu>Disable</VGpu>
    <Networking>Enable</Networking>
    <MappedFolders>
      <MappedFolder>
        <HostFolder>C:\Users\*******\Desktop\WindowsSandbox</HostFolder>
        <ReadOnly>true</ReadOnly>
      </MappedFolder>
    </MappedFolders>
    <LogonCommand>
      <Command>cmd.exe</Command>
    </LogonCommand>
  </Configuration>
& .\sandbox.wsb
error
The following settings are enforced by your IT administrator:

      - Clipboard redirection is disabled by policy.
      - Networking is disabled by policy.

  If you wish to avoid this message in the future, please update your configuration to respect these Group Policy settings or contact your local IT administrator.

  Would you like to continue with the new configuration?

fix:

$SandboxRegPath = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Sandbox\'
  Set-ItemProperty -Path $SandboxRegPath -Name 'AllowClipboardRedirection' -Value 1
  Set-ItemProperty -Path $SandboxRegPath -Name 'AllowNetworking' -Value 1

in the Windows Sandbox:

# Set DNS server
  Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddresses 1.1.1.1

Powershell

PowerShell

Collection of useful one-liners and simple scripts

Check Win11 Status

$computerName = $env:COMPUTERNAME
      $searcher = New-Object DirectoryServices.DirectorySearcher
      $searcher.Filter = "(&(objectCategory=computer)(name=$computerName))"
      $result = $searcher.FindOne()
      
      if ($result -ne $null) {
          $ou = $result.Path
      } else {
          Write-Output "Computer $computerName not found in AD."
      }
      
      
      $target = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate' | select ProductVersion ,TargetReleaseVersionInfo
      
      Write-Output "$OU"
      Write-Output "Target Release: $($target.ProductVersion) $($target.TargetReleaseVersionInfo)"

type clipboard as keypresses


      
      # countdown
      "Pasting in 5 seconds..."
      5; Start-Sleep -Seconds 1
      4; Start-Sleep -Seconds 1
      3; Start-Sleep -Seconds 1
      2; Start-Sleep -Seconds 1
      1; Start-Sleep -Seconds 1
      0; 'Pasting now...'
      
      
      
      
      $clip = (Get-Clipboard)
      $clip = $clip -replace '{', '__{__' -replace '}', '__}__'
      $clip = $clip -replace '__{__', '{{}' -replace '__}__', '{}}'
      $clip = $clip -join '{ENTER}' # replace newlines with ENTER keypress
      [System.Windows.Forms.SendKeys]::SendWait($clip)
      
      
      
      <#
      
      NOTES:
      SendKeys uses curly braces as a special character, 
      and you have to escape them withmore curly braces, 
      so I pad them first before escaping so you dont escape the escapes
      
      { --> {{}
      } --> {}}
      
      #>
      

PowerShell History File

(Get-PSReadLineOption).HistorySavePath
      
      # OR
      echo "C:\Users\$env:USERNAME\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt"

Get-TeamsOnlyOwnerReport

This will list the Teams that a user is the only owner of.

Connect-MicrosoftTeams
      $user = Read-Host "User"
      
      # get all teams that user is a member of
      $teams = Get-Team -User $user
      
      # get the owners of all teams that user is a member of
      $ownerReport = ForEach ($team in $teams) {
          Get-TeamUser -GroupId $team.GroupID -Role Owner | Add-Member -NotePropertyName "Team" -NotePropertyValue $team.DisplayName -PassThru | select Team,user,role
      }
      
      # get teams where that user is the ONLY owner
      $ownerReport | Group-Object -Property team | ? Count -EQ 1 | % {$_.group | ? User -EQ $user}

Fix-Csv

This isnt working yet…


      function Fix-Csv {
          param (
              [string[]]$Path
          )
      
          # try to import csv. dump error to $e
          Import-Csv $Path -ErrorVariable e
      
          # grab text in quotes
          $e.message -match '"([^"]+)"'
          $dupe = $matches[1]
      
          # get csv header. (first line of text)
          $header = gc $Path -First 1
      
          # replace the first occurence with "junk"
          [regex]$pattern = $dupe
          $header = $pattern.replace($header, "junk", 1)
          $header = $header -split ','   # turn comma separated list into multi-line string
          $header | % {$_-replace '"'}           # Strip Quotes
      
          # import again with new header
          $x = Import-Csv $Path -Header $header
          $x
      }

o365 sign-in asn lookup

This takes the ASN from the sign-in log and gets the associated name. I’m not sure if you can do anything with it, but its interesting data. Legit sign-ins are probably only from a few ASNs, but to my knowledge, you cant block access by ASN.

# NOTE: ($x is o365 sign-in logs csv)
      
      $asn = $x | ? status -Like "Success" | select -ExpandProperty 'Autonomous system  number'
      $dump = $asn | Group-Object |sort -Property count | select Count,Name
      
      # this might take a long time. There is probably a more efficient way to do the lookups
      $AsnTable = foreach ($item in $dump ) {
        @(
          $detail = $item | %{ gc .\Downloads\asn.txt | sls "^$($_.name) "} # <--- sls is probably the slow part
          @{Count=$item.Count;ASN=$item.Name;Detail=$detail}
        ) | % { New-Object object | Add-Member -NotePropertyMembers $_ -PassThru } | select Count,ASN,Detail
      }

get Process CommandLine

$process = "notepad.exe"
      Get-CimInstance Win32_Process -Filter "name = '$process'" | select CommandLine 
      
      
      
      get-process notepad.exe | select-object ProcessName, CommandLine

get list of installed software

Get-WmiObject -Class Win32_Product | ? Name -like "*SQL Server 2012*" 

Search-BitLockerRecoveryInfo.ps1

param
      (
          [Parameter(Mandatory)]$search
      )
      
      
      # Get user input if not specified in param
      if (!$search){
        $search = Read-Host "Computer Name or Recovery Key ID"
      }
      
      # Get all the recovery objects from AD
      $AllRecoveryInformation = Get-AdObject -Filter 'objectClass -eq "msFVE-RecoveryInformation"'
      # Search for matching key
      $FoundKeys = $AllRecoveryInformation |Where-Object DistinguishedName -like "*$search*" | Get-ADObject -Properties *
      # Display results
      $FoundKeys | select "msFVE-*","whenChanged","whenCreated","DistinguishedName"

Windows Sandbox

sandbox.wsb

<Configuration>
        <VGpu>Disable</VGpu>
        <Networking>Enable</Networking>
        <MappedFolders>
          <MappedFolder>
            <HostFolder>C:\Users\*******\Desktop\WindowsSandbox</HostFolder>
            <ReadOnly>true</ReadOnly>
          </MappedFolder>
        </MappedFolders>
        <LogonCommand>
          <Command>cmd.exe</Command>
        </LogonCommand>
      </Configuration>
& .\sandbox.wsb
error
The following settings are enforced by your IT administrator:

          - Clipboard redirection is disabled by policy.
          - Networking is disabled by policy.

      If you wish to avoid this message in the future, please update your configuration to respect these Group Policy settings or contact your local IT administrator.

      Would you like to continue with the new configuration?

fix:

$SandboxRegPath = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Sandbox\'
      Set-ItemProperty -Path $SandboxRegPath -Name 'AllowClipboardRedirection' -Value 1
      Set-ItemProperty -Path $SandboxRegPath -Name 'AllowNetworking' -Value 1

in the Windows Sandbox:

# Set DNS server
      Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddresses 1.1.1.1