Powershell Hints & Tricks
Convert hex to bytes, bytes to hex
function ConvertTo-Hex ([byte []]$bytes )
{
return ($bytes | % { $_.ToString (" X2" ) }) -join " "
}
function ConvertTo-Bytes ([string ]$hex )
{
return $hex -split " (?<=\G\w{2})(?=\w{2})" | % { [Convert ]::ToByte( $_ , 16 ) }
}
How to owerride default output
$LOGFILE = " c:\my.log"
function global :Out-Default
{
process
{
" $ ( get-date - Format s) [$PID ] $_ " | out-file - FilePath $LOGFILE - Append - Force; $_ | out-host ;
}
}
Get (or search across) list of registered COM objects
function Search-COM ( $filter = " *" )
{
return Get-ChildItem HKLM:\Software\Classes - ErrorAction SilentlyContinue |
? { $_.PSChildName -match ' ^\w+\.\w+$' `
-and (Test-Path - Path " $ ( $_.PSPath ) \CLSID" ) `
-and $_.PSChildName -like $search_filter } | Select-Object - ExpandProperty PSChildName
}
New-Object - Com (Search-COM (" wscript.network" )) | Get-Member
function retry ( $times , $sleep , $script )
{
0 .. ($times - 1 ) |
% { & {
write-host - nonewline (get-date ).tolongtimestring()" "
try { & $script }
catch { $_.Exception }
finally { sleep - s $sleep }
}
}
}
# usage: check google.com every 1 m in 24h:
retry (60 * 24 ) 60 { (Invoke-WebRequest " https://google.com" ).statusCode }
Allow connect to untrusted SSL
Add-Type - TypeDefinition "
using System.Net;using System.Security.Cryptography.X509Certificates;
public class AllowConnectToUntrustedSSL : ICertificatePolicy {
public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; }
}"
[System.Net.ServicePointManager ]::CertificatePolicy = New-Object AllowConnectToUntrustedSSL
$dir = " C:\path\"
Get-ChildItem - Path $dir - Recurse - Filter " *.cs" |
% {
Write-Host " $ ( $_.Name ) - $ ( (Get-Content $_.FullName ).Length) "
}
$stroke = " After this stroke will protected, only current user could unprotect this stroke back."
$output = " C:\Temp\data.ecrypted"
$salt = " s a l t"
$DP = [System.Security.Cryptography.ProtectedData ]
$scope = [System.Security.Cryptography.DataProtectionScope ]::CurrentUser
$ENC = [System.Text.Encoding ]::UTF8
sc $output - Value $DP ::Protect($ENC.GetBytes ($stroke ), $ENC.GetBytes ($salt ), $scope ) - Force
$unprotected = $ENC.GetString ( $DP ::Unprotect( (gc $output ), $ENC.GetBytes ($salt ), $scope ) )
if ( $unprotected -ne $stroke ){
throw " Unprotect check failed: protected data cannot be restored" }
$env: Path = [System.Environment ]::GetEnvironmentVariable(" Path" , " Machine" ) + " ;" + [System.Environment ]::GetEnvironmentVariable(" Path" , " User" )
get-date - uformat % s
# 1465571078,24586
((get-date - uformat % s) -split ' ,' )[0 ]
# 1465571078
$date = [DateTime ]::Now.AddYears(1 )
get-date ($date ) - uformat % s
Create Hashtable Dynamicaly
$Field1 = " 1"
$Field2 = " 2"
$Field3 = " 3"
$Field4 = " 4"
$Field5 = " 5"
$Field6 = " 6"
$Field7 = " 7"
$data = @ {}
" a,b,c,d,e,f" -split " ," | % {$n = 0 } {
$n ++
$data.Add ($_ , ((Get-Variable - Name " Field$n " ).Value) )
}
$data
Generate self-signed Certificate
$certName = " my-self-signed-certificate"
$certPass = " SuperPassword"
$outputFolder = (Split-Path $PSCommandPath - Parent)
$cert = New-SelfSignedCertificate - DnsName " Windows Azure Tools" - CertStoreLocation " cert:\LocalMachine\My"
$password = ConvertTo-SecureString - String $certPass - Force - AsPlainText
Export-PfxCertificate - Cert $cert - FilePath " $outputFolder \$certName .pfx" - Password $password
Export-Certificate - Cert $cert - Type CERT - FilePath " $outputFolder \$certName .cer"