Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

PowerShell

Record the mouse position and the top window title to Windows Event Log

Requirement Record the user activity to Windows Event Logs. The mouse position*1 and top window title *2 are used to indicate the activity. Solution Run the following PowerShell script every 5 minutes from the Task Scheduler. Add-Type -Ass…

Record a Windows Event Log with a custom application/source and appropriate message

Requirement You want to record an event on Windows Event Log. The log should be recorded with a custom application and source. The message of the event should be recorded appropriately. The message should not contain the warning like The d…

Windows Event Viewer Category Correspondence Table

I couldn't find the correspondence table between the value of the -Category argument (Int16) of Write-EventLog cmdlet and the category shown in Event Viewer from Microsoft. I have run this command and viewed the result in the Event Viewer …

ProcessBuilder freezes when you try to run a .bat containing PowerShell scripts

Background By using the .bat file from here, you can run a PowerShell script by just click the .bat file. reosablo.hatenablog.jp Problem When you are trying to run the .bat file from Java ProcessBuilder class like this, the .bat file will …

CPU goes 100% when you read .HAR file with ConvertFrom-JSON

Background In Chrome DevTools, you can export the contents in the Network tab into a JSON file (.HAR file). Chrome cannot export the contents of the spreadsheet in the Network tab into .csv or .xlsx format. If you want to get these content…

Overwriting existing file never change creation time in NTFS

Overwriting existing file like 1..10 > file.txt, 1..10 | Out-File file.txt, or 1..10 | Set-Content file.txt, never changes creation time in NTFS. You have to delete the file explicitly like rm file.txt; 1..10 > file.txt, or change creation…

Copy-Item doesn't have --no-clobber option

Context: cp(1) has -n or --no-clobber option. It makes cp not overwrite existing files. This option is useful when you copy only newly created files. Problem: In PowerShell, Copy-Item cmdlet doesn't have options equivalent to --no-clobber …

cmd.exeとPowerShellの起動速度

PowerShellの起動速度が遅い遅いというけれど、cmd.exeと比較してどの程度遅いのか確かめてみた。 OSはWindows 10 version 2004、CPUはIntel(R) Core(TM) i7-8750H CPU @ 2.20GHz(6コア12スレッド)です。 なお、処理に使うウィンドウはPowerShellのもので…

Read from .xlsx in PowerShell (x64) without using Excel

This article shows how to read .xlsx in PowerShell without Excel. In Windows 10 (x64), you will have to do additional work. You have to install Microsoft Access Database Engine 2010 Redistributable (AccessDatabaseEngine_X64.exe) when you u…

Launch PowerShell process in non-default culture (locale)

In PowerShell on Windows 10, you cannot change the current culture (locale) with chcp command. If you want to launch a new PowerShell process in another culture, once run cmd.exe from PowerShell, execute chcp, and launch powershell.exe fro…

You cannot set CPU affinity of PostgreSQL instance started through pg_ctl with Start-Process and Process.ProcessorAffinity

Background: In Windows, you can set the CPU affinity of an user process with Start-Process PowerShell cmdlet and System.Diagnostics.Process.ProcessorAffinity property like this: $app = Start-Process -FilePath C:\Windows\System32\mspaint.ex…

Use Enum defined in classes from PowerShell

If you have an enum like this: namespace Foo { public class Bar { public enum Baz { A = 0, B = 1, C = 2 } } } You can use this enum from PowerShell with [FQCN+Enum] notation like this: Add-Type @" namespace Foo { public class Bar { public …

Change culture (locale) of current PowerShell process

You can change culture (locale) into English with chcp 437 in Windows 7. In contrast, You cannot change culture with chcp in Windows 10. In Windows 10, if you want to execute single PowerShell script in another culture, you can execute the…

Import assemblies for C# embedded in PowerShell

You can import assemblies (.NET DLLs) in PowerShell like this: [void][reflection.assembly]::LoadWithPartialName("System.Drawing") New-Object System.Drawing.Drawing2D.GraphicsPath But you will get an error when you tring to use these assemb…

Difference of Invoke-Expression and '&' in PowerShell

# Command Result 1 Invoke-Expression 'Get-Process' OK 2 & 'Get-Process' OK 3 Invoke-Expression 'Get-Process explorer' OK 4 & 'Get-Process explorer' NG #4 causes the following error: & : 用語 'Get-Process explorer' は、コマンドレット、関数…

康煕字典体から常用漢字へ変換するコマンドレット

変換対照の文字は、文化庁 常用漢字表*1で康煕字典体が示されているものを対照とした。常用漢字表のPDFの内容をテキストファイルへダンプし、以下のスクリプトで常用漢字とカッコ書きの康煕字典体とのペアを抽出した*2。 > Get-Content .\常用漢字表.txt | W…

How to separate a string into codepoint-wise characters with PowerShell

Context: You have a Unicode string that contain non-ASCII characters as well as ASCII characters. You want to separate that string into characters. Problem: If you split the string with the code below: $TemporaryArray = $InputString -split…

Difference of behavior of String#split() in Java and -split operator in PowerShell

Both of String#split() in Java and -split operator in PowerShell take regex as argument, and split string into a list or an array, but there is some difference in behavior when you pass an empty string as argument. In Java: System.out.prin…

How to extract non-MS932 (Shift_JIS) compliant characters from string

function Get-NonMS932CompliantCharacter { Param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [string] $TargetString ) process { $TargetStringBytes = [Text.Encoding]::UTF32.GetBytes($TargetString); for ($i=0; $i -lt $TargetStringBy…

tr equivalent in PowerShell (Unicode surrogate pair-aware)

There is no straightforward tr equivalent in Windows, so I made an cmdlet that you can use like tr command. This tr cmdlet is aware of Unicode characters including surrogate pairs. function tr { Param( [Parameter(ValueFromPipeline=$true,Ma…

How to capture network packet without additional software in Windows

(A) Use "netsh trace" command pros: You can use it in isolated network. cons: You should convert the captured file with Microsoft Message Analyzer if you want to see packets with Wireshark. (You can also view the packets with Microsoft Mes…

How to change locale of error messages of PowerShell interpreter

Problem You can set locale of the current thread in PowerShell like below: [System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]("en-US") But error messages of PowerShell interpreter shows in current …

How to use additional character encodings in PowerShell Core (Linux) and Desktop (Windows)

Problem You have to call [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance) when you want to use additional character encodings in PowerShell Core (Linux). On the other hand, calling [System.Text.En…

Memory Consumption to Read XMLs in PowerShell

Background PowerShell has an useful function to read and parse XML files: [XML]. But reading XML files and (especially) building DOMs are memory consuming function. Question How much memory do you need to read XML files with [XML]? Methods…

How to escape special characters in PowerShell

Ways to escape special characters in PowerShell are different between its context, and so complecated... # Context Escaped char " ' \ ` `` 1 String with " " ✓ ✘ ✘ ✓ ✘ 2 String with " $ ✘ ✘ ✘ ✓ ✘ 3 String with " ' - - - - - 4 String wi…

Invoke-RestMethod to GitLab API causes mojibake

Context In PowerShell, You can call REST API with Invoke-RestMethod like: Invoke-RestMethod -Headers $headers -Method Get -Timeout 10 -Uri "https://api.github.com/users/octocat/orgs" Problem The result of Invoke-RestMethod causes mojibake …

Format operator with string contains "{" and "}"

Context In PowerShell, you can format a string with -F operator like: Get-Content foo.csv | ConvertFrom-Csv -Header Name,Code,Address | ` ForEach-Object { "{0} `n {1} {2}" -F $_.Name,$_.Code,$_.Address } Problem -F operator returns error l…

Get CodePoint-Property Pair from Scripts.txt on Unicode.org

Context You want to make a list of pair of unicode codepoint and its character property, like below: 00009,Cc 00020,Zs 00021,Po 00024,Sc ... Solution with PowerShell You can make the list from ftp://ftp.unicode.org/Public/UNIDATA/PropList.…

Convert deeply nested hash or array to JSON with ConvertTo-Json

Context You can read a JSON file like below with ConvertFrom-Json, and write with ConvertTo-Json properly. PS > Get-Content ./foo.json { "outerHash": { "innerHash": { "key": "value" } } } PS > Get-Content ./foo.json | ConvertFrom-Json | Co…

Convert an array to CSV with PowerShell

Problem You cannot convert an array with just pipeline the array to ConvertTo-Csv. PS > $array = ("a", "b", "c", "a", "d") PS > $array | ConvertTo-Csv "Length" "1" "1" "1" "1" "1" ... or just passing the array to ConvertTo-Csv. PS > Conver…