Lazy Diary @ Hatena Blog

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

PowerShell

What curl can do and Invoke-WebRequest can't do

curl can show the raw request header and body with --trace option*1. There is no way to get the content of the request with Invoke-WebRequest. curl can show the body of 5xx response. Invoke-WebRequest returns null when a server responds wi…

Determine whether you are behind a proxy or not with .NET

You can get the default proxy setting for a specific url with System.Net.WebRequest.GetSystemWebProxy().GetProxy(). The result is System.Uri object, and its OriginalString property will be the same the parameter if you are not behind a pro…

Test-NetConnectionの不思議な挙動

最近はICMP Echoに応答しないサイトも多い(たとえばlogin.live.com)。そんなときは、TCPでポートを指定して接続確認が行えるTest-NetConnectionコマンドレットが便利に使える。 ただこのTest-NetConnectionコマンドレット、ネットワーク接続が確立していな…

タスク スケジューラからPowerShellを起動するとき-Commandオプションのパラメタをシングルクォートで囲んではいけない

前提 タスク スケジューラで作ったタスクで、操作に「プログラムの開始」でpowershell.exeを指定し、「引数の追加」で-Commandオプションと実行したいスクリプトを指定すれば、タスク スクリプトから任意のコマンドを実行できる。 参考: https://www.netspi.…

PowerShellはまり道

github.com この処理を書くときに久しぶりにいくつかはまったのでメモ。 .ps1ファイルの文字コードをBOMなしUTF-8にすると日本語コメントがあったときに誤動作する。たとえばAdd-Typeの後のヒアドキュメントが正しくヒアドキュメントと認識されずに単一行文…

PowerShellでHashSetのForEachメソッドを使う

$map = New-Object System.Collections.Generic.HashSet[string]; $map.Add("ABC") > $null $map | Get-Member とすると出てこないが、PowerShell ISEなどでオートコンプリートを使うとHashSetにForEach()というメソッドが生えていることが分かる。 このForE…

PowerShell上でgit diff中の日本語が文字化けするのを直す

前提条件 PowerShellから下のようにgit diffを実行する。 PS C:\git\checkstyle> Get-ChildItem -Recurse | Where-Object { $_.Name -like "messages_ja.properties" } | ForEach-Object { $_.FullName.substring(29) } | ForEach-Object { Write-Output "`n…

情報処理安全確保支援士の共通講習・実践講習の受講要否を取得する

情報処理安全確保支援士は、1年に1度の共通講習(オンライン講習)と、3年に1度の実践講習(実践講習または特定講習)を受講する義務があります*1。この講習を受講するには3年間で14万円かかります*2。企業や組織に所属する情報処理安全確保支援士の場合、こ…

How to write records into .xlsx with OLEDB

satob.hatenablog.com satob.hatenablog.com So, how should you write records into .xlsx files with OLEDB? Requirement and Implementation You want to record some data into a .xlsx file with relational database style. In other words, you want …

How to insert a new row with datatype constraints by using Microsoft.ACE.OLEDB

satob.hatenablog.com You can make an Excel file (.xlsx) without Excel by using Microsoft.ACE.OLEDB, but the behavior of INSERT is also a little bit weird. The behavior changes according to the CREATE TABLE is executed in the same connectio…

How to create a new sheet with the desired name by using Microsoft.ACE.OLEDB

You can make an Excel file (.xlsx) without Excel by using Microsoft.ACE.OLEDB, but the behavior of CREATE TABLE is a little bit weird. The behavior changes according to the name of the sheet, suffix of the sheet name ($) in the CREATE TABL…

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スレッド)です。 なお、処理に使うウィンドウはPowerSh…

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…