Emacs: Format PowerShell Code 📜

By Xah Lee. Date: . Last updated: .

put this in your Emacs Init File:

(defun xah-pwsh-format-buffer ()
  "Format PowerShell code of current buffer.
Buffer must be a file buffer. It is saved first.

Requires
 Install-Module -Name PSScriptAnalyzer -Force

Requires the cross-platform pwsh.

URL `http://xahlee.info/emacs/emacs/emacs_format_powershell_code.html'
Created: 2021-09-13
Version: 2025-07-02"
  (interactive)
  (when (not buffer-file-name) (user-error "%s: current buffer %s must be a file" real-this-command (buffer-name)))
  (when (buffer-modified-p) (save-buffer))
  (let ((xbackupName (concat buffer-file-name "." (format-time-string "%Y%m%d%H%M%S") "~")))
    (copy-file buffer-file-name xbackupName t)
    (message (concat "\nBackup saved at: " xbackupName)))
  (let ((xoutbuf (get-buffer-create "*xah-pwsh-format output*")))
    (with-current-buffer xoutbuf (erase-buffer))

    ;; use call-process-region
    ;; pass the command as a region, to stdin
    ;; this way, avoid escaping string problem
    ;; the command will do format the file

    ;; 2025-07-02 no way to know if Invoke-Formatter is successful
    (call-process-region
     (format
      "Set-Content \"%s\" (Invoke-Formatter -ScriptDefinition ([IO.File]::ReadAllText(\"%s\"))) -NoNewline;"
      buffer-file-name
      buffer-file-name)
     nil
     "pwsh"
     nil xoutbuf nil
     "-Command" "-")
    (revert-buffer t t t)
    (if (eq 1 (with-current-buffer xoutbuf (point-max)))
        (progn
          (kill-buffer xoutbuf))
      (progn
        (display-buffer xoutbuf)
        (error "Error xah-pwsh-format-buffer %s failed" buffer-file-name)))))

need PowerShell: Pretty Format PowerShell Code 📜

part of Emacs: Xah PowerShell Mode 📦

Emacs, Format Code