2
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から新規wordファイルを作成する関数

Posted at

環境

  • Windows11
  • Powershell 7.4.0

使い方

ファイル名の拡張子はつけなくてもいい。
visible : Wordアプリを表示するかどうか(デフォルトは$True)

PS C:\Users\user> word file_name [visible]

コード

function getSavePath($fn, $ex) {
    $cd = (Get-Location).Path
    $fnc = $fn + $ex
    $sp = Join-Path $cd $fnc
    for ($i = 1; Test-Path $sp; $i++) {
        $fnc = $fn + $i.ToString("00") + $ex
        $sp = Join-Path $cd $fnc
    }
    return $sp
}

function word(
    $file_name = "new-doc-" + (Get-Date -Format "yyyyMMdd") + ".docx",
    [bool]$visible = $True
) {
    $wd = New-Object -ComObject Word.Application
    $wd.Visible = $visible
    $doc = $wd.Documents.Add()

    if ($file_name -match "^\.\\") {
        $file_name.Replace(".\", "")
    }
    if ($file_name -match "\.docx$") {
        $file_name.Replace("\.docx", "")
    }
    $save_path = getSavePath $file_name ".docx"

    $doc.SaveAs($save_path) 
}

不満とか

ファイル名が重複しないようにするコード(拡張子を消したり追加したり)をもっと改善できそう。

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