2
1

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とVSCodeのパイプライン連携で作業効率UP (?)

Posted at

PowerShellでの作業中に「この出力をVSCodeで編集・確認したい」と思ったことはありませんか?実は、PowerShellとVSCodeを連携させることで、コマンドライン作業の効率を向上させることができます。

この記事では、PowerShellの出力を直接VSCodeで開く方法から、実践的な活用例を備忘録します。

powershell_vscode_diagram.png

この記事で学べること

  • PowerShellからVSCodeへの直接パイプライン連携
  • 作業フォルダへの効率的なファイル出力
  • ファイル管理と一時ファイルの使い分け
  • 関数化による再利用可能なワークフロー作成
  • 実際の開発現場で使える具体例

前提条件

筆者の動作確認環境。

  • PowerShell 5.1
  • Visual Studio Code 1.19.1以上
  • VSCodeのPATHが通っていること

基本的なパイプライン連携

1. コマンド出力を直接VSCodeで開く

最もシンプルで強力な方法は、code -を使用することです:

Get-Process | Out-String | code -

image.png

解説:

  • Get-Process: 実行中のプロセス一覧を取得
  • Out-String: オブジェクトを文字列に変換
  • code -: 標準入力からVSCodeで新しいタブを開く

2. より実践的な例

# システム情報をVSCodeで確認
$tempFile = [System.IO.Path]::GetTempFileName() + ".txt"
Get-ComputerInfo | Out-File $tempFile -Encoding UTF8; code $tempFile

# エラーログの確認
$tempFile = [System.IO.Path]::GetTempFileName() + ".txt"
Get-EventLog -LogName System -EntryType Error -Newest 50 | Out-File $tempFile -Encoding UTF8; code $tempFile

# ファイル検索結果をVSCodeで表示
$tempFile = [System.IO.Path]::GetTempFileName() + ".txt"
Get-ChildItem -Recurse -Filter "*.cs" | Out-File $tempFile -Encoding UTF8; code $tempFile

image.png

ファイル出力を活用した連携方法

作業フォルダへの直接出力

# 現在のフォルダにプロセス情報を出力してVSCodeで開く
Get-Process | Out-File "process-report.txt" -Encoding UTF8; code "process-report.txt"

# 複数の情報を1つのファイルにまとめて出力
@"
=== システム情報レポート ===
生成日時: $(Get-Date)

=== 実行中のプロセス(上位20件)===
$(Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 | Format-Table -AutoSize | Out-String)

=== 実行中のサービス ===
$(Get-Service | Where-Object {$_.Status -eq "Running"} | Format-Table -AutoSize | Out-String)
"@ | Out-File "system-report.txt" -Encoding UTF8; code "system-report.txt"

image.png

日付付きファイル名での管理

# 日付付きのファイル名で管理
$date = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$filename = "log-analysis_$date.txt"

Get-EventLog -LogName Application -Newest 100 | 
    Where-Object {$_.EntryType -eq "Error"} | 
    Format-List TimeGenerated, Source, Message | 
    Out-File $filename -Encoding UTF8

code $filename

一時ファイルを使った管理

# 一意の一時ファイル名を生成
$tempFile = [System.IO.Path]::GetTempFileName() + ".txt"

# データを一時ファイルに出力
Get-Service | Where-Object {$_.Status -eq "Running"} | 
    Format-Table -AutoSize | Out-File $tempFile -Encoding UTF8

# VSCodeで開く
code $tempFile

# 作業後のクリーンアップ(オプション)
# Remove-Item $tempFile

実践的な活用例

1. ログ解析ワークフロー

# アプリケーションログの最新エラーを抽出してVSCodeで分析
$tempFile = [System.IO.Path]::GetTempFileName() + ".txt"
Get-WinEvent -LogName Application -MaxEvents 100 | 
    Where-Object {$_.LevelDisplayName -eq "Error"} | 
    Format-List TimeCreated, Id, LevelDisplayName, Message | 
    Out-File $tempFile -Encoding UTF8
code $tempFile

2. 開発環境チェック

# 開発環境の構成情報を一覧化
$envInfo = @"
=== 開発環境情報 ===
PowerShell Version: $($PSVersionTable.PSVersion)
.NET Version: $([System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription)
OS: $([System.Environment]::OSVersion.VersionString)

=== インストール済みモジュール ===
$(Get-Module -ListAvailable | Format-Table Name, Version -AutoSize | Out-String)

=== 環境変数 ===
$(Get-ChildItem Env: | Format-Table Name, Value -AutoSize | Out-String)
"@

$envInfo | Out-File "env-info.txt" -Encoding UTF8; code "env-info.txt"

3. 定期レポートの自動生成

# 毎日のシステムチェックレポートを作業フォルダに保存
$reportDate = Get-Date -Format "yyyy-MM-dd"
$reportFile = "daily-system-check_$reportDate.txt"

$report = @"
========================================
日次システムチェックレポート
生成日: $(Get-Date -Format "yyyy年MM月dd日 HH:mm:ss")
========================================

【ディスク使用量】
$(Get-WmiObject -Class Win32_LogicalDisk | Select-Object DeviceID, @{Name="Size(GB)";Expression={[math]::Round($_.Size/1GB,2)}}, @{Name="FreeSpace(GB)";Expression={[math]::Round($_.FreeSpace/1GB,2)}}, @{Name="Used%";Expression={[math]::Round(($_.Size-$_.FreeSpace)/$_.Size*100,2)}} | Format-Table -AutoSize | Out-String)

【メモリ使用状況】
$(Get-WmiObject -Class Win32_OperatingSystem | Select-Object @{Name="TotalMemory(GB)";Expression={[math]::Round($_.TotalVisibleMemorySize/1MB,2)}}, @{Name="FreeMemory(GB)";Expression={[math]::Round($_.FreePhysicalMemory/1MB,2)}} | Format-Table -AutoSize | Out-String)

【高CPU使用プロセス(上位10件)】
$(Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 | Format-Table Name, CPU, WorkingSet -AutoSize | Out-String)
"@

$report | Out-File $reportFile -Encoding UTF8
code $reportFile

関数化して再利用可能にする

# プロファイルに追加して常時利用可能にする関数例
function Show-InVSCode {
    param(
        [Parameter(ValueFromPipeline=$true)]
        $InputObject
    )
    
    process {
        $tempFile = [System.IO.Path]::GetTempFileName() + ".txt"
        $InputObject | Out-File -FilePath $tempFile -Encoding UTF8
        code $tempFile
    }
}

# 使用例
Get-Process | Show-InVSCode
Get-Service | Show-InVSCode

注意点とトラブルシューティング

よくある問題と解決方法

  1. codeコマンドが認識されない

    • VSCodeのPATHが通っていることを確認
    • コマンドパレット(Ctrl+Shift+P)から「Shell Command: Install 'code' command in PATH」を実行
  2. 日本語文字化け

    # エンコーディングを指定
    Get-Content .\log.txt -Encoding UTF8 | Out-File temp.txt -Encoding UTF8
    code temp.txt
    
  3. データ量を制限

    # データ量を制限
    Get-Process | Select-Object -First 50 | Out-String | code -
    

まとめ

PowerShellとVSCodeを連携させることで、エディタで出力結果を確認する作業がスムーズになります。関数やタスク機能を活用することで再利用性も高まり、生産性の向上が期待できます。

参考リンク

VSCode コマンド IFの説明みると、他にも使いたいオプションがあるかもしれません・・・。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?