【Python】オセロ(Othero)[リバーシ(riversi)]を作ってみた

リクエストがあったのでオセロを作ってみました
作成所要時間は座標系の嫌なバグが出たので15時間ほどかかりました
参考になれば幸いです


#プレイヤー値 順番により入れ替わる
player=1
notplayer=2

#ボードサイズ
bsize=8

#盤面
board=[[0 for i in range(bsize)] for j in range(bsize)]
#初期配置
board[3][4]=1#黒
board[4][3]=1
board[3][3]=2#白
board[4][4]=2

#入力チェック
def check(x,y):
    try:
        val=board[y][x]
    except:#範囲外
        return False
    if val==0:#無接続
        return False
    return True

#全て駒で埋まったかチェック
def full():
    cnt=0
    for i in range(bsize):
        for j in range(bsize):
            if board[i][j]>0:
                cnt+=1
    if cnt==bsize*bsize:
        return True
    else:
        return False

#盤面表示
def pboard():
    print(" 01234567")
    for i in range(bsize):
        print(su[i],end='')
        for j in range(bsize):
            print(dic[board[i][j]],end='')
        print('\n',end='')

#裏返す
def reversi(x,y):#PieceReturn
    #既に置かれた所はダメ
    if board[y][x]==player:
        return False
    if board[y][x]==notplayer:
        return False
    #CanInputEraser(入力可能表示を消す)
    board[y][x]=player
    for i in range(bsize):
        for j in range(bsize):
            if board[i][j]<0:
                board[i][j]=0

    result=[]
    for dy,dx in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]:
        depth,flg = 1,0
        tmp = []
        for _ in range(bsize):
            # 検索対象の座標を設定する
            ry,rx = y + (dy * depth) , x + (dx * depth) 
            # ボードの範囲を超えていたら抜ける
            if any([rx<0,ry<0,rx>=bsize,ry>=bsize]):
                break
            # 返せる駒がなくて0だったら抜ける
            if board[ry][rx]==0:
                break
            # 返せる駒がなくてplayerと同じ駒だったら抜ける
            elif flg==0 and board[ry][rx]==player:
                break
            # 返せる駒が初めて見つかったらflg=1にする
            elif flg==0 and board[ry][rx]==notplayer:
                flg = 1
                # 返せる座標を追加する
                tmp.append((ry,rx))
            # 返せる駒が初めて見つかったら返せる座標を追加する
            elif flg==1 and board[ry][rx]==notplayer:
                tmp.append((ry,rx))
            # flg=1の状態でplayerと同じ駒が見つかったらresultに追加する
            elif flg==1 and board[ry][rx]==player:
                result += tmp
                break
            depth += 1
        
    # 石をひっくり返す
    for y2,x2 in result:
        board[y2][x2]=player
    return True

#入力可能位置の検索
def CanInput():
    for x in range(bsize):
        for y in range(bsize):
            if board[y][x]<0:
                board[y][x]=0
    bingo=False
    for x in range(bsize):
        for y in range(bsize):
            if board[y][x]==player:
                for dy,dx in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]:
                    depth,flg = 1,0
                    for _ in range(bsize):
                        # 検索対象の座標を設定する
                        ry,rx = y + (dy * depth) , x + (dx * depth) 
                        # ボードの範囲を超えていたら抜ける
                        if any([rx<0,ry<0,rx>=bsize,ry>=bsize]):
                            break
                        # 返せる駒がなくてplayerと同じ駒だったら抜ける
                        if flg==0 and board[ry][rx]==player:
                            break
                        # 返せる駒が初めて見つかったらflg=1にする
                        elif flg==0 and board[ry][rx]==notplayer:
                            flg = 1
                        # flg=1の状態でplayerと同じ駒が見つかったら処理を抜ける
                        elif flg==1 and board[ry][rx]==player:
                            break
                        # flg=1の状態で駒を置ける場合はマークする
                        elif flg==1 and board[ry][rx]<=0:
                            board[ry][rx]=-player
                            bingo=True
                            break
                        if board[ry][ry]<=0:
                            break
                        depth += 1
    return bingo

#結果表示 勝敗と駒の数
def DispResult():
    black=0
    white=0
    for i in range(bsize):
        for j in range(bsize):
            if board[i][j]==1:
                black+=1
            elif board[i][j]==2:
                white+=1
    if black>white:
        print(f"Black Win! Black={black} White={white}")
    elif white>black:
        print(f"White Win! White={white} Black={black}")
    elif white==black:
        print("Drow!")

#ここからメイン===================================================

#表示用
dispplayer={1:"○",2:"●"}
dic={0:' ',1:'○',2:'●',-1:'□',-2:'■'}
su={0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',}
passcount=0

while(True):
    CanInput()  #入力可能位置の検索
    pboard()    #盤面表示
    #座標入力
    try:
        print(f"player={dispplayer[player]}")
        x=int(input("col="))
        y=int(input("row="))
    except:
        #入力不正時はゲーム終了
        break
    #駒をひっくり返す
    if check(x,y)==True:
        if full()==False:
            #ここで駒を返す処理
            if reversi(x,y)==False:
                print("NG") #まず無いハズ(既に駒があるところを指定)
                print("")
            else:
                passcount=0
                #プレイヤー交代
                player,notplayer=notplayer,player
        else:
            #全て駒で埋まった
            #結果表示
            pboard()
            DispResult()
            break   #ゲーム終了
    else:
        print("NG")
        print("")

    #駒が置ける位置の検索表示
    if CanInput()==False:
        passcount+=1
        #駒を置けない
        pboard()
        #すべて駒で埋まったか
        if full()==False or passcount<2:
            #駒が置けないのでパス
            print(f"player={dispplayer[player]} Pass!")
            print("")
            #プレイヤー交代
            player,notplayer=notplayer,player
            #黒白共に駒が置けない場合は終了
            if CanInput()==False:
                pboard()
                DispResult()
                break
        else:
            #全て駒で埋まった又は両プレイヤー共に駒が置けない
            #結果表示
            pboard()
            DispResult()
            break   #ゲーム終了

【Windows】端末(ターミナル)の種類と起動方法

現在Windows[10,11]で使える端末(terminal)は5種類あります
その簡単な説明と起動方法を紹介します

ターミナルの種類

コマンドプロンプト(Command Prompt)

起動方法

■スタートメニュー
スタートメニュー→Windows システムツール→コマンドプロンプト
■ファイル名を指定して実行
cmdまたはcmd.exe

コードページ(抜粋)

規定 id .NET Name 追加情報
932 shift_jis ANSI/OEM Japanese; Japanese (Shift-JIS)
20127 us-ascii US-ASCII (7-bit)
51932 euc-jp EUC Japanese
65001 utf-8 Unicode (UTF-8)

docs.microsoft.com

パワーシェル(Windows PowerShell)

起動方法

■スタートメニュー
スタートメニュー→Windows PowerShellWindows PowerShell
■ファイル名を指定して実行
powershellまたはpowershell.exe

パワーシェルISE(Windows PowerShell ISE)

起動方法

■スタートメニュー
スタートメニュー→Windows PowerShellWindows PowerShell ISE
■ファイル名を指定して実行
powershell_ISEまたはpowershell_ISE.exe

パワーシェル7(PowerShell 7)

インストール

docs.microsoft.com

起動方法

■スタートメニュー
スタートメニュー→PowerShellPowerShell 7
■ファイル名を指定して実行
pwshまたはpwsh.exe

ウィンドウズターミナル(Windows Terminal)

インストール

docs.microsoft.com

起動方法

■スタートメニュー
スタートメニュー→ターミナル
■ファイル名を指定して実行
wtまたはwt.exe

【PowerShell】ソースコードファイル種による文字化けと文字コード

成否の評価について
- はリテラル文字または変数・関数名に2バイト文字が含まれている時点で構文エラーになる
× はターミナル出力時に文字化けする


Write-Output(ehco,write)

ターミナル ソースコードファイル 成否
PowerShell Shift-Jis
PowerShell UTF-8 -
PowerShell UTF-8BOM
pwsh Shift-Jis ×
pwsh UTF-8
pwsh UTF-8BOM


変数(文字列)から出力

ターミナル ソースコードファイル 成否
PowerShell Shift-Jis
PowerShell UTF-8 -
PowerShell UTF-8BOM
pwsh Shift-Jis ×
pwsh UTF-8
pwsh UTF-8BOM


データファイルの文字化け

Get-Content(gc)

ターミナル ソースコードファイル データファイル 成否
PowerShell Shift-Jis Shift-JIs
PowerShell Shift-Jis UTF-8 ×
PowerShell Shift-Jis UTF-8BOM
PowerShell UTF-8 Shift-JIs -
PowerShell UTF-8 UTF-8 -
PowerShell UTF-8 UTF-8BOM -
PowerShell UTF-8BOM Shift-JIs
PowerShell UTF-8BOM UTF-8 ×
PowerShell UTF-8BOM UTF-8BOM
pwsh Shift-Jis Shift-Jis ×
pwsh Shift-Jis UTF-8
pwsh Shift-Jis UTF-8BOM
pwsh UTF-8 Shift-Jis ×
pwsh UTF-8 UTF-8
pwsh UTF-8 UTF-8BOM
pwsh UTF-8BOM Shift-Jis ×
pwsh UTF-8BOM UTF-8
pwsh UTF-8BOM UTF-8BOM


OutputEncoding.EncodingName

デフォルトの出力時のエンコード

ターミナル ソースコードファイル Encode
PowerShell Shift-Jis US-ASCII
PowerShell UTF-8 US-ASCII
PowerShell UTF-8BOM US-ASCII
pwsh Shift-Jis UTF-8
pwsh UTF-8 UTF-8
pwsh UTF-8BOM UTF-8


[console]::OutputEncoding

デフォルトのコンソール出力時のエンコード

ターミナル ソースコードファイル Encode
PowerShell Shift-Jis 日本語 (シフト JIS)
PowerShell UTF-8 日本語 (シフト JIS)
PowerShell UTF-8BOM 日本語 (シフト JIS)
pwsh Shift-Jis Japanese (Shift-JIS)
pwsh UTF-8 Japanese (Shift-JIS)
pwsh UTF-8BOM Japanese (Shift-JIS)


リダイレクト[>,>>]

リダイレクトでファイル出力時の出力文字エンコード

ターミナル ソースコードファイル Encode
PowerShell Shift-Jis UTF-16LE
PowerShell UTF-8 -
PowerShell UTF-8BOM UTF-16LE
pwsh Shift-Jis ×
pwsh UTF-8 UTF-8
pwsh UTF-8BOM UTF-8



Encodingパラメーターがあるコマンドレット

ソースモジュール コマンドレット
Microsoft.PowerShell.Management Add-Content
Microsoft.PowerShell.Management Get-Content
Microsoft.PowerShell.Management Set-Content
Microsoft.PowerShell.Utility Export-Clixml
Microsoft.PowerShell.Utility Export-Csv
Microsoft.PowerShell.Utility Export-PSSession
Microsoft.PowerShell.Utility Format-Hex
Microsoft.PowerShell.Utility Import-Csv
Microsoft.PowerShell.Utility Out-File
Microsoft.PowerShell.Utility Select-String
Microsoft.PowerShell.Utility Send-MailMessage


Encoding パラメーター

上記コマンドレットのEncodingパラメータに指定できる値です
UTF-8についてはPowerShellとpwshでは意味が異なります
PwoerShellではBOM付きUTF-8ですがpwshではBOM無しUTF-8であることに注意してください


Version パラメーター 説明
PowerShell Ascii Uses Ascii (7-bit) character set.
PowerShell BigEndianUnicode Uses UTF-16 with the big-endian byte order.
PowerShell BigEndianUTF32 Uses UTF-32 with the big-endian byte order.
PowerShell Byte Encodes a set of characters into a sequence of bytes.
PowerShell Default Uses the encoding that corresponds to the system's active code page (usually ANSI).
PowerShell Oem Uses the encoding that corresponds to the system's current OEM code page.
PowerShell String Same as Unicode.
PowerShell Unicode Uses UTF-16 with the little-endian byte order.
PowerShell Unknown Same as Unicode.
PowerShell UTF32 Uses UTF-32 with the little-endian byte order.
PowerShell UTF7 Uses UTF-7.
PowerShell UTF8 Uses UTF-8 (with BOM).
pwsh ascii Uses the encoding for the ASCII (7-bit) character set.
pwsh bigendianunicode Encodes in UTF-16 format using the big-endian byte order.
pwsh oem Uses the default encoding for MS-DOS and console programs.
pwsh unicode Encodes in UTF-16 format using the little-endian byte order.
pwsh utf7 Encodes in UTF-7 format.
pwsh utf8 Encodes in UTF-8 format (no BOM).
pwsh utf8BOM Encodes in UTF-8 format with Byte Order Mark (BOM)
pwsh utf8NoBOM Encodes in UTF-8 format without Byte Order Mark (BOM)
pwsh utf32 Encodes in UTF-32 format.


上記パラメーターの他にPowerShell6.2より.NET Coreまたは.NET Frameworkで規定されているコードページIDまたはコードページ名が使用できます


.NET Coreで規定されているもの

コードページID コードページ名 表示名
1200 utf-16 Unicode
1201 utf-16BE Unicode (Big-Endian)
12000 utf-32 Unicode (UTF-32)
12001 utf-32BE Unicode (UTF-32 Big-Endian)
20127 us-ascii US-ASCII
28591 iso-8859-1 Western European (ISO)
65000 utf-7 Unicode (UTF-7)
65001 utf-8 Unicode (UTF-8)


.NET Frameworkで規定されているもの

コードページID コードページ名 表示名
37 IBM037 IBM EBCDIC (US-Canada)
437 IBM437 OEM United States
500 IBM500 IBM EBCDIC (International)
708 ASMO-708 Arabic (ASMO 708)
720 DOS-720 Arabic (DOS)
737 ibm737 Greek (DOS)
775 ibm775 Baltic (DOS)
850 ibm850 Western European (DOS)
852 ibm852 Central European (DOS)
855 IBM855 OEM Cyrillic
857 ibm857 Turkish (DOS)
858 IBM00858 OEM Multilingual Latin I
860 IBM860 Portuguese (DOS)
861 ibm861 Icelandic (DOS)
862 DOS-862 Hebrew (DOS)
863 IBM863 French Canadian (DOS)
864 IBM864 Arabic (864)
865 IBM865 Nordic (DOS)
866 cp866 Cyrillic (DOS)
869 ibm869 Greek, Modern (DOS)
870 IBM870 IBM EBCDIC (Multilingual Latin-2)
874 windows-874 Thai (Windows)
875 cp875 IBM EBCDIC (Greek Modern)
932 shift_jis Japanese (Shift-JIS)
936 gb2312 Chinese Simplified (GB2312)
949 ks_c_5601-1987 Korean
950 big5 Chinese Traditional (Big5)
1026 IBM1026 IBM EBCDIC (Turkish Latin-5)
1047 IBM01047 IBM Latin-1
1140 IBM01140 IBM EBCDIC (US-Canada-Euro)
1141 IBM01141 IBM EBCDIC (Germany-Euro)
1142 IBM01142 IBM EBCDIC (Denmark-Norway-Euro)
1143 IBM01143 IBM EBCDIC (Finland-Sweden-Euro)
1144 IBM01144 IBM EBCDIC (Italy-Euro)
1145 IBM01145 IBM EBCDIC (Spain-Euro)
1146 IBM01146 IBM EBCDIC (UK-Euro)
1147 IBM01147 IBM EBCDIC (France-Euro)
1148 IBM01148 IBM EBCDIC (International-Euro)
1149 IBM01149 IBM EBCDIC (Icelandic-Euro)
1200 utf-16 Unicode
1201 utf-16BE Unicode (Big-Endian)
1250 windows-1250 Central European (Windows)
1251 windows-1251 Cyrillic (Windows)
1252 Windows-1252 Western European (Windows)
1253 windows-1253 Greek (Windows)
1254 windows-1254 Turkish (Windows)
1255 windows-1255 Hebrew (Windows)
1256 windows-1256 Arabic (Windows)
1257 windows-1257 Baltic (Windows)
1258 windows-1258 Vietnamese (Windows)
1361 Johab Korean (Johab)
10000 macintosh Western European (Mac)
10001 x-mac-japanese Japanese (Mac)
10002 x-mac-chinesetrad Chinese Traditional (Mac)
10003 x-mac-korean Korean (Mac)
10004 x-mac-arabic Arabic (Mac)
10005 x-mac-hebrew Hebrew (Mac)
10006 x-mac-greek Greek (Mac)
10007 x-mac-cyrillic Cyrillic (Mac)
10008 x-mac-chinesesimp Chinese Simplified (Mac)
10010 x-mac-romanian Romanian (Mac)
10017 x-mac-ukrainian Ukrainian (Mac)
10021 x-mac-thai Thai (Mac)
10029 x-mac-ce Central European (Mac)
10079 x-mac-icelandic Icelandic (Mac)
10081 x-mac-turkish Turkish (Mac)
10082 x-mac-croatian Croatian (Mac)
12000 utf-32 Unicode (UTF-32)
12001 utf-32BE Unicode (UTF-32 Big-Endian)
20000 x-Chinese-CNS Chinese Traditional (CNS)
20001 x-cp20001 TCA Taiwan
20002 x-Chinese-Eten Chinese Traditional (Eten)
20003 x-cp20003 IBM5550 Taiwan
20004 x-cp20004 TeleText Taiwan
20005 x-cp20005 Wang Taiwan
20105 x-IA5 Western European (IA5)
20106 x-IA5-German German (IA5)
20107 x-IA5-Swedish Swedish (IA5)
20108 x-IA5-Norwegian Norwegian (IA5)
20127 us-ascii US-ASCII
20261 x-cp20261 T.61
20269 x-cp20269 ISO-6937
20273 IBM273 IBM EBCDIC (Germany)
20277 IBM277 IBM EBCDIC (Denmark-Norway)
20278 IBM278 IBM EBCDIC (Finland-Sweden)
20280 IBM280 IBM EBCDIC (Italy)
20284 IBM284 IBM EBCDIC (Spain)
20285 IBM285 IBM EBCDIC (UK)
20290 IBM290 IBM EBCDIC (Japanese katakana)
20297 IBM297 IBM EBCDIC (France)
20420 IBM420 IBM EBCDIC (Arabic)
20423 IBM423 IBM EBCDIC (Greek)
20424 IBM424 IBM EBCDIC (Hebrew)
20833 x-EBCDIC-KoreanExtended IBM EBCDIC (Korean Extended)
20838 IBM-Thai IBM EBCDIC (Thai)
20866 koi8-r Cyrillic (KOI8-R)
20871 IBM871 IBM EBCDIC (Icelandic)
20880 IBM880 IBM EBCDIC (Cyrillic Russian)
20905 IBM905 IBM EBCDIC (Turkish)
20924 IBM00924 IBM Latin-1
20932 EUC-JP Japanese (JIS 0208-1990 and 0212-1990)
20936 x-cp20936 Chinese Simplified (GB2312-80)
20949 x-cp20949 Korean Wansung
21025 cp1025 IBM EBCDIC (Cyrillic Serbian-Bulgarian)
21866 koi8-u Cyrillic (KOI8-U)
28591 iso-8859-1 Western European (ISO)
28592 iso-8859-2 Central European (ISO)
28593 iso-8859-3 Latin 3 (ISO)
28594 iso-8859-4 Baltic (ISO)
28595 iso-8859-5 Cyrillic (ISO)
28596 iso-8859-6 Arabic (ISO)
28597 iso-8859-7 Greek (ISO)
28598 iso-8859-8 Hebrew (ISO-Visual)
28599 iso-8859-9 Turkish (ISO)
28603 iso-8859-13 Estonian (ISO)
28605 iso-8859-15 Latin 9 (ISO)
29001 x-Europa Europa
38598 iso-8859-8-i Hebrew (ISO-Logical)
50220 iso-2022-jp Japanese (JIS)
50221 csISO2022JP Japanese (JIS-Allow 1 byte Kana)
50222 iso-2022-jp Japanese (JIS-Allow 1 byte Kana - SO/SI)
50225 iso-2022-kr Korean (ISO)
50227 x-cp50227 Chinese Simplified (ISO-2022)
51932 euc-jp Japanese (EUC)
51936 EUC-CN Chinese Simplified (EUC)
51949 euc-kr Korean (EUC)
52936 hz-gb-2312 Chinese Simplified (HZ)
54936 GB18030 Chinese Simplified (GB18030)
57002 x-iscii-de ISCII Devanagari
57003 x-iscii-be ISCII Bengali
57004 x-iscii-ta ISCII Tamil
57005 x-iscii-te ISCII Telugu
57006 x-iscii-as ISCII Assamese
57007 x-iscii-or ISCII Oriya
57008 x-iscii-ka ISCII Kannada
57009 x-iscii-ma ISCII Malayalam
57010 x-iscii-gu ISCII Gujarati
57011 x-iscii-pa ISCII Punjabi
65000 utf-7 Unicode (UTF-7)
65001 utf-8 Unicode (UTF-8)

【PoweShell】Get-Comandでコマンドレットを絞り込む

結論から言うと2通りあります

ここではこれらを取得する方法とその構成を説明します
コマンドレットのContentに注目します

PowerShellでは特に指定しない限りコマンド中の大文字小文字は区別されません

もっとも簡単な方法

コマンド

>gcm -noun content
  • 短縮コマンドの説明
短縮名 コマンドレット 説明
gcm Get-Command コマンドレットの情報を取得する

結果

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Add-Content                                        7.0.0.0    Microsoft.PowerShell.Management
Cmdlet          Clear-Content                                      7.0.0.0    Microsoft.PowerShell.Management
Cmdlet          Get-Content                                        7.0.0.0    Microsoft.PowerShell.Management
Cmdlet          Set-Content                                        7.0.0.0    Microsoft.PowerShell.Management

表示をスマートに

コマンド

>gcm -noun contnt | select name,version

結果

Name          Version
----          -------
Add-Content   7.0.0.0
Clear-Content 7.0.0.0
Get-Content   7.0.0.0
Set-Content   7.0.0.0

他の方法

コマンド

>gcm | ?{$_.noun -eq "content"} | select name,version

結果

Name          Version
----          -------
Add-Content   7.0.0.0
Clear-Content 7.0.0.0
Get-Content   7.0.0.0
Set-Content   7.0.0.0

コマンド

>gcm | ?{$_.name -like "*content"} | select name,version
>gcm | ?{$_.commandtype -eq "cmdlet" -and $_.name -like "*content"} | select name,version

結果

Name                    Version
----                    -------
Add-Content             7.0.0.0
Clear-Content           7.0.0.0
Get-Content             7.0.0.0
Get-WindowsImageContent 3.0
Set-Content             7.0.0.0
  • 短縮コマンドの説明
短縮名 コマンドレット 説明
? Where-Object オブジェクトを列挙する
select Select-Object オブジェクトプロパティを選択する

正式なコマンドレット名に展開すると上の2つのコマンドは次のようになります

>Get-Command | Where-Object{$PSItem.Noun -eq "Content"} | Select-Object Name,Version
>Get-Command | Where-Object{$PSItem.Name -like "*Content"} | Select-Object name,version

フィルタに使えるメンバー名(表タイトル)

  • 短縮コマンドの説明
短縮名 コマンドレット 説明
gm Get-Member メンバーの情報を取得する

コマンド

>gcm | gm

結果

   TypeName: System.Management.Automation.AliasInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
Definition          Property       string Definition {get;}
Description         Property       string Description {get;set;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PSTy…
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.Parameter…
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.Comm…
ReferencedCommand   Property       System.Management.Automation.CommandInfo ReferencedCommand {get;}
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
ResolvedCommand     Property       System.Management.Automation.CommandInfo ResolvedCommand {get;}
Source              Property       string Source {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
DisplayName         ScriptProperty System.Object DisplayName {get=if ($this.Name.IndexOf('-') -lt 0)…
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference…
ResolvedCommandName ScriptProperty System.Object ResolvedCommandName {get=$this.ResolvedCommand.Name;}

   TypeName: System.Management.Automation.FunctionInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CmdletBinding       Property       bool CmdletBinding {get;}
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
DefaultParameterSet Property       string DefaultParameterSet {get;}
Definition          Property       string Definition {get;}
Description         Property       string Description {get;set;}
HelpFile            Property       string HelpFile {get;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Noun                Property       string Noun {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PSTy…
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.Parameter…
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.Comm…
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
ScriptBlock         Property       scriptblock ScriptBlock {get;}
Source              Property       string Source {get;}
Verb                Property       string Verb {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference…

   TypeName: System.Management.Automation.CmdletInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
DefaultParameterSet Property       string DefaultParameterSet {get;}
Definition          Property       string Definition {get;}
HelpFile            Property       string HelpFile {get;}
ImplementingType    Property       type ImplementingType {get;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Noun                Property       string Noun {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PSTy…
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.Parameter…
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.Comm…
PSSnapIn            Property       System.Management.Automation.PSSnapInInfo PSSnapIn {get;}
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
Source              Property       string Source {get;}
Verb                Property       string Verb {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
DLL                 ScriptProperty System.Object DLL {get=$this.ImplementingType.Assembly.Location;}
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference…

上の方法では余分な情報があるのでCmdletInfoに絞り込みます
コマンド

>gcm|gm|?{$_.typename -eq "system.management.automation.cmdletinfo"}
>gcm|gm|?{$_.typename -like "*cmdletinfo"}

結果

   TypeName: System.Management.Automation.CmdletInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
DefaultParameterSet Property       string DefaultParameterSet {get;}
Definition          Property       string Definition {get;}
HelpFile            Property       string HelpFile {get;}
ImplementingType    Property       type ImplementingType {get;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Noun                Property       string Noun {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PSTy…
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.Parameter…
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.Comm…
PSSnapIn            Property       System.Management.Automation.PSSnapInInfo PSSnapIn {get;}
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
Source              Property       string Source {get;}
Verb                Property       string Verb {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
DLL                 ScriptProperty System.Object DLL {get=$this.ImplementingType.Assembly.Location;}
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference…

先のコマンドではDifinitionの一部が省略されて表示されてます
これらを折り返して表示するには次のようにします
コマンド

>gcm|gm|?{$_.typename -eq "system.management.automation.cmdletinfo"} | ft -wrap
  • 短縮コマンドの説明
短縮名 コマンドレット 説明
ft Format-Table 出力の列内の表示変更

結果

   TypeName: System.Management.Automation.CmdletInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
DefaultParameterSet Property       string DefaultParameterSet {get;}
Definition          Property       string Definition {get;}
HelpFile            Property       string HelpFile {get;}
ImplementingType    Property       type ImplementingType {get;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Noun                Property       string Noun {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PSTyp
                                   eName] OutputType {get;}
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.ParameterM
                                   etadata] Parameters {get;}
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.Comma
                                   ndParameterSetInfo] ParameterSets {get;}
PSSnapIn            Property       System.Management.Automation.PSSnapInInfo PSSnapIn {get;}
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
Source              Property       string Source {get;}
Verb                Property       string Verb {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
DLL                 ScriptProperty System.Object DLL {get=$this.ImplementingType.Assembly.Location;}
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference
                                             $ProgressPreference = 'SilentlyContinue'
                                             try
                                             {
                                             [Microsoft.PowerShell.Commands.GetHelpCodeMethods]::GetHelpUri($this)
                                             }
                                             catch {}
                                             finally
                                             {
                                             $ProgressPreference = $oldProgressPreference
                                             };}

もっと詳しく

次のコマンドではGet-Contentのメンバー(タイトル)とその中身を表示します
コマンド

>gcm | ?{$_.name -eq "get-content"} | select *

結果

HelpUri             : https://go.microsoft.com/fwlink/?LinkID=2096490
DLL                 : C:\Program Files\PowerShell\7\Microsoft.PowerShell.Commands.Management.dll
Verb                : Get
Noun                : Content
HelpFile            : Microsoft.PowerShell.Commands.Management.dll-Help.xml
PSSnapIn            :
Version             : 7.0.0.0
ImplementingType    : Microsoft.PowerShell.Commands.GetContentCommand
Definition          :
                      Get-Content [-Path] <string[]> [-ReadCount <long>] [-TotalCount <long>] [-Tail <int>] [-Filter <s
                      tring>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-Delim
                      iter <string>] [-Wait] [-Raw] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<CommonP
                      arameters>]

                      Get-Content -LiteralPath <string[]> [-ReadCount <long>] [-TotalCount <long>] [-Tail <int>] [-Filt
                      er <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-
                      Delimiter <string>] [-Wait] [-Raw] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<Co
                      mmonParameters>]

DefaultParameterSet : Path
OutputType          : {System.Byte, System.String}
Options             : ReadOnly
Name                : Get-Content
CommandType         : Cmdlet
Source              : Microsoft.PowerShell.Management
Visibility          : Public
ModuleName          : Microsoft.PowerShell.Management
Module              : Microsoft.PowerShell.Management
RemotingCapability  : PowerShell
Parameters          : {[ReadCount, System.Management.Automation.ParameterMetadata], [TotalCount, System.Management.Auto
                      mation.ParameterMetadata], [Tail, System.Management.Automation.ParameterMetadata], [Path, System.
                      Management.Automation.ParameterMetadata]…}
ParameterSets       : {[-Path] <string[]> [-ReadCount <long>] [-TotalCount <long>] [-Tail <int>] [-Filter <string>] [-I
                      nclude <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-Delimiter <strin
                      g>] [-Wait] [-Raw] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<CommonParameters>]
                      , -LiteralPath <string[]> [-ReadCount <long>] [-TotalCount <long>] [-Tail <int>] [-Filter <string
                      >] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-Delimiter
                      <string>] [-Wait] [-Raw] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<CommonParame
                      ters>]}

これらの情報を見るとコマンドレット名[Name]はメンバー[Verb(動詞)]とメンバー[Noun(名詞)]の組み合わせであることが判ります
従ってメンバー[Noun]でフィルタすると使用可能な動詞[Verb]の一覧が得られます
これで最初のフィルタするコマンドが理解できたと思います
このフィルタリング手法はGet-Commandの他にGet-ChildItem、Get-Service、Get-Processなどまたファンクションですがよく使うGet-NetIPAddressなどでも応用可能です

Contentについて

  • 短縮コマンドの説明
短縮名 コマンドレット 説明
catGet-Content指定された場所にあるアイテムのコンテンツを取得します
基本的にファイルの内容を取得します
gc
type
ac Add-Content ファイルに追記します
clc Clear-Content ファイルの内容をクリアします
sc Set-Content ファイルに新たに内容を書き込みます
※PowerShell7以降ではこの短縮名は使えません

他にもいくつか注意点があります
次のサイトを参照してください
tech.guitarrapc.com
ファイル書き込み時にはOut-Fileを使うことも考慮してください
またファイル書き込みにはリダイレクト「>や>>」もあるので必要に応じて使い分けるのが良いでしょう
www.itlab51.com

重要追記

紹介した上記サイトに書かれている「デフォルトエンコーディングの違い」についてですがPowerShell7[pwsh]では仕様が変わったようです
結論から言うとpwshではOut-File,Set-Content,リダイレクト(>,>>)で全てASCIIとして出力されるようになったようです
PowerShell[powershell]でも確認しましたが、この場合はエンコーディングが違うことを確認しました
Set-ContentのみASCII
これらに注意してください

【ImageMagic】一括処理でJpeg画像から丸窓化(Ping画像)するBatchプログラム【Windows】

環境

OS:Windows
ImageMagic7以降

注意

ファイル名に半角スペースが含まれている場合エラーになります
作成したバッチファイルは画像のあるフォルダに入れて実行してください
トリミングした画像はPNG画像になります

変数preにはファイル前置詞を指定できます

CircleConv.bat

@echo off
setlocal enabledelayedexpansion
set pre=_
type nul > list.txt
for %%i in (*.jpg) do (
    magick identify "%%i" >> list.txt
)
for /f "tokens=1,3" %%a in (list.txt) do (
    for /f "tokens=1,2 delims=x" %%x in ("%%b") do (
        set /a cx=%%x/2
        set /a cy=%%y/2
        if /i %%x gtr %%y (
            set top=0
            set left=!cx!
            set harfx=0
            set /a harfy=%%y/2
            set size=%%y
            set /a cutleft=%%x-!size!
            set /a cutleft=!cutleft!/2
            set cuttop=0
        ) else (
            set top=!cy!
            set left=0
            set /a harfx=%%x/2
            set harfy=0
            set size=%%x
            set cutleft=0
            set /a cuttop=%%y-!size!
            set /a cuttop=!cuttop!/2
        )
        set /a harf=!size!/2
        magick -size !size!x!size! xc:none -draw "circle !harf!,!harf! !harfx!,!harfy!" _mask_%%a.png
        magick %%a -crop "!size!x!size!+!cutleft!+!cuttop!"  _ex_%%a.png
        magick _ex_%%a.png _mask_%%a.png -compose CopyOpacity -composite %pre%%%%a.png
        del _ex_%%a.png
        del _mask_%%a.png
    )
)
del list.txt

SQLServerのインストールと郵便番号データのインポート

ファイヤーウォールのポート開放

コントロールパネルでファイアーウォールを検索
WindowsDefenderファイアウォールの詳細設定を表示
新しい規則で次のポートを開放
TCP 1433
UDP 1434
規則の名前はMSSqlserverとでもしておく

■SQLServer2017のインストール

コンピューターの管理のサービスとアプリケーションで
SQL構成マネージャーのネットワーク構成でプロトコルの名前付きパイプを有効にする
(ネットワーク越しに使用する場合はTCP/IPも有効にする)

■郵便局のページ

http://www.post.japanpost.jp/zipcode/download.html
から必要な郵便番号データをダウンロードする
(読み仮名データの促音・拗音を小書きで表記するものの全国一括)
ken_all.zipを解凍し別名KEN_ALL(更新日付とか).CSVにする

■MSSMSでデータベースを作成

ここではKEN_ALL

■MSSMSでテーブルを作成(テーブル名もKEN_ALL)

USE [KEN_ALL]
GO
/****** Object:  Table [dbo].[KEN_ALL]    Script Date: 2018/03/18 13:31:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KEN_ALL](
 [cord] [varchar](100) NULL,
 [zip5] [varchar](100) NULL,
 [zip] [varchar](100) NULL,
 [todofukenkana] [varchar](100) NULL,
 [sikuchosonkana] [varchar](100) NULL,
 [choikikana] [varchar](100) NULL,
 [todofuken] [varchar](100) NULL,
 [sikuchoson] [varchar](100) NULL,
 [choiki] [varchar](100) NULL,
 [a] [varchar](1) NULL,
 [b] [varchar](1) NULL,
 [c] [varchar](1) NULL,
 [d] [varchar](1) NULL,
 [e] [varchar](1) NULL,
 [f] [varchar](1) NULL
) ON [PRIMARY]
GO

■管理者権限のコマンドプロンプトBCPでKEN_ALL(更新日付とか).CSVインポートする

>bcp KEN_ALL in c:\フォルダーパス\KEN_ALL().CSV -S <Server Name> -d KEN_ALL -U <Username> -P <password> -q -c -t,

コマンドオプションの説明

  • S サーバー名を指定します。省略した場合、既定のサーバーになります。
  • T 統合認証を使ってログインします。この場合ユーザー名、パスワードは必要ありません。
  • q 空白や単一引用符を含むデータベース名を指定するには、-q オプションを使用する必要があります。
  • c 文字データ型を使用して操作を実行します。 このオプションを使用すると、フィールドごとにプロンプトが表示されません。 char をプレフィックスなしのストレージ型として、また \t (タブ) をフィールド区切り文字、 \r\n (改行文字) を行ターミネータとして使用します。 -c は -w と互換性がありません。
  • t フィールド ターミネータを指定します。 既定値は \t (タブ文字) です。 既定のフィールド ターミネータを無効にする場合、このパラメーターを使用します。 詳細については、「フィールド ターミネータと行ターミネータの指定 (SQL Server)」をご覧ください。

bcp.exe コマンドでは、フィールド ターミネータを 16 進数表記で指定すると、値が 0x00 で切り捨てられます。 たとえば、0x410041 を指定した場合、使用されるのは 0x41 になります。
field_term がハイフン (-) またはスラッシュ (/) で始まる場合は、 -t と field_term 値の間に空白を入れないでください。

■sqlcmdで確認する

>sqlcmd -S <Server Name> -d KEN_ALL -U <Username> -P <Password> -Q "select + from KEN_ALL;"

SQLServer2017に PubsとNorthWindデータベースのインストール

■解凍してinstnwnd.sqlとinstpubs.sqlの一部を書き換える

(C:\SQL Server 2000 Sample Databasesに解凍)

○instnwnd.sql

/*
exec sp_dboption 'Northwind','trunc. log on chkpt.','true'
exec sp_dboption 'Northwind','select into/bulkcopy','true'
*/
alter database Northwind set recovery simple

○instpubs.sql

/*
execute sp_dboption 'pubs' ,'trunc. log on chkpt.' ,'true'
*/
alter database pubs  set recovery simple

■sqlcmdでデータベースをインストールする

BATファイルを作って実行する

Windows認証の場合

@echo off
cd C:\SQL Server 2000 Sample Databases
sqlcmd -S (コンピューター名)\(インスタンス名) -i instpubs.sql
sqlcmd -S (コンピューター名)\(インスタンス名) -i instnwnd.sql

SQL Server認証の場合

@echo off
cd C:\SQL Server 2000 Sample Databases
sqlcmd -S (コンピューター名)\(インスタンス名) -U (ユーザ名) -P (パスワード) -i instpubs.sql
sqlcmd -S (コンピューター名)\(インスタンス名) -U (ユーザ名) -P (パスワード) -i instnwnd.sql

コンピューター名は標準ならHOME、そのあと\を挟んでインスタンス名を入れます
(ここではSQLExpressになってます)

■作ったBATファイルをコマンドプロンプトで実行する

■データベースができたか確認する

コマンドプロンプトに次のコマンドを実行する

sqlcmd -S (コンピューター名)\(インスタンス名) -U (ユーザ名) -P (パスワード) -Q "select name,create_date from sys.databases;"

一覧の中にpubsとNorthwindがあれば成功です