0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PowerShellの-notlikeで角括弧が壊れる:索引ファイルを失った原因と安全な代替

0
Posted at

はじめに

PowerShellの -like / -notlike は、正規表現ではなくワイルドカードです。[ と ] は文字クラスとして解釈されるため、[[Sessions/...]] のような角括弧を含む文字列を照合すると、パターンが不正になったり、意図しない結果になります。

この記事では、実際に例外を再現し、安全な代替(StartsWith / Contains / 完全一致)を確認します。

環境

  • Windows 11(ビルド 10.0.26200)
  • Windows PowerShell 5.1.26100(PowerShell 7系でも同様のワイルドカード構文)

やったこと

1. 角括弧を含むパターンで例外を出す

'[[Sessions/a]]' -like '[[Sessions/*'

結果:

The specified wildcard character pattern is not valid: [[Sessions/*

[ が文字クラスの開始と解釈され、閉じていないためパターンエラーになります。

2. -notlike でフィルターすると空になる

次のような索引行を想定します。

$lines = @(
  '# index'
  '[[Sessions/a]]'
  '[[Sessions/b]]'
  'other'
)
$filtered = $lines | Where-Object { $_ -notlike '[[Sessions/*' }

パターンが不正なため、Where-Object の結果が期待通りになりません。その結果をそのまま Set-Content すると、索引が1行だけになる事故につながります。

3. StartsWithで安全に判定する

$filtered = $lines | Where-Object { -not $_.StartsWith('[[Sessions/') }
$filtered

結果:

# index
other

角括弧はただの文字として扱われます。

4. Containsや完全一致も使える

'[[Sessions/a]]'.Contains('[[Sessions/')   # True
'[[Sessions/a]]' -eq '[[Sessions/a]]'      # True

5. 正規表現でエスケープする

どうしても -match を使いたい場合は、[regex]::Escape() でエスケープします。

[regex]::Escape('[[Sessions/')

結果:

\[\[Sessions/

6. 索引を書き換えるときの安全手順

$path = 'C:\work\index.md'
$backup = "$path.bak"
Copy-Item $path $backup -Force

$lines = Get-Content $path
$new = $lines | Where-Object { -not $_.StartsWith('[[Sessions/') }
$tmp = "$path.tmp"
$new | Set-Content -Encoding UTF8 $tmp

# 件数と先頭・末尾を確認してから置換
if ((Get-Content $tmp).Count -ne $new.Count) { throw '件数が一致しません' }
Move-Item $tmp $path -Force

ハマった点

例外が出ても書き込みは実行される

Where-Object のフィルターが失敗しても、パイプラインの後続の Set-Content は実行されます。フィルター結果が空だと、ファイルが空または1行になります。書き込み前に件数を検証してください。

-like は正規表現ではない

.* や \d は使えません。ワイルドカードは *、?、[abc] です。角括弧を含む文字列には向きません。

バックアップを先に取る

索引・設定・リストなど、再生成に手間がかかるファイルは、書き換え前に同一フォルダへバックアップします。可能なら一時ファイルに書いてから Move-Item で置換します。

まとめ

  • -like / -notlike はワイルドカードで、[ は文字クラスとして解釈される。
  • 角括弧を含む文字列には StartsWith / Contains / 完全一致を使う。
  • 正規表現なら [regex]::Escape() でエスケープする。
  • 書き込み前に件数を検証し、バックアップと一時ファイルを経由する。
  • フィルターの例外を無視して Set-Content しない。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?