qshinoの日記

Powershell関係と徒然なこと

.gitignore

.girignore

適用範囲

サブディレクトリにも適用される。 但し、より深いディレクトリが優先される。

よって、最上階ディレクトリの .gitignoreに基本ルールを記載すると便利。

“/” の意味

否定

  • 先頭に"!“ -> 無視されない=git管理

気になる

.gitignore対象ファイルがgit pull で取得できるか?

  • できない -> まあまあ
  • できる -> なるほど

どちらだろう。

確かめた

commit済みのファイルを.gitignoreで指定してもgit管理のまま。

  1. .gitignoreにコミット済みファイルを指定
  2. commit
  3. ディレクトリでclone
  4. ignore指定ファイルも取り出された。

なるほど

git rm で削除しないといけないのね

参考

http://qiita.com/anqooqie/items/110957797b3d5280c44f

wpf例外処理

Wpf例外処理

UIスレッドで発生した例外処理。

  1. 例外発生時、Try-catchより先に受け取るAppDomain.CurrentDomain.FirstChanceException
  2. UIスレッド DispatcherUnhandledException e.Handled = $true により例外処理済みにできる。
  3. バックグラウンドジョブ UnobservedTaskException UnobservedTaskExceptionEventArgsオブジェクト(System.Threading.Tasks名前空間)のSetObservedメソッドにより処理済みにできる。
  4. 最後の最後に AppDomainクラスのUnhandledExceptionイベント

DispatcherUnhandledException

public partial class App : Application
{
  public App()
  {
    // UIスレッドで実行されているコードで処理されなかったら発生する(.NET 3.0より)
    this.DispatcherUnhandledException += App_DispatcherUnhandledException;
  }

  private void App_DispatcherUnhandledException(
                  object sender, 
                  System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
  {
    string errorMember = e.Exception.TargetSite.Name;
    string errorMessage = e.Exception.Message;
    string message = string.Format(
@"例外が{0}で発生。プログラムを継続しますか?
エラーメッセージ:{1}",
                              errorMember, errorMessage);
    MessageBoxResult result
      = MessageBox.Show(message, "DispatcherUnhandledException",
                        MessageBoxButton.YesNo, MessageBoxImage.Warning);
    if(result == MessageBoxResult.Yes)
      e.Handled = true;
  }
}
Class Application
  Public Sub New()
    ' UIスレッドで実行されているコードで処理されなかったら発生する(.NET 3.0より)
    AddHandler Me.DispatcherUnhandledException,
      AddressOf App_DispatcherUnhandledException
  End Sub

  Private Sub App_DispatcherUnhandledException(
              sender As Object,
              e As System.Windows.Threading.DispatcherUnhandledExceptionEventArgs)

    Dim errorMember As String = e.Exception.TargetSite.Name
    Dim errorMessage As String = e.Exception.Message
    Dim message As String = String.Format(
"例外が{0}で発生。プログラムを継続しますか?" + vbCrLf _
+ "エラーメッセージ:{1}",
                              errorMember, errorMessage)
    Dim result As MessageBoxResult _
      = MessageBox.Show(message, "DispatcherUnhandledException",
                          MessageBoxButton.YesNo, MessageBoxImage.Warning)
    If (result = MessageBoxResult.Yes) Then
      e.Handled = True
    End If
  End Sub
End Class

UnobservedTaskException

public partial class App : Application
{
  public App()
  {
    // バックグラウンドタスク内で処理されなかったら発生する(.NET 4.0より)
    TaskScheduler.UnobservedTaskException
      += TaskScheduler_UnobservedTaskException;
  }

  private void TaskScheduler_UnobservedTaskException(
                  object sender,
                  UnobservedTaskExceptionEventArgs e)
  {
    string errorMember = e.Exception.InnerException.TargetSite.Name;
    string errorMessage = e.Exception.InnerException.Message;
    string message = string.Format(
@"例外がバックグラウンドタスクの{0}で発生。プログラムを継続しますか?
エラーメッセージ:{1}",
                        errorMember, errorMessage);
    MessageBoxResult result
      = MessageBox.Show(message, "UnobservedTaskException",
                        MessageBoxButton.YesNo, MessageBoxImage.Warning);
    if (result == MessageBoxResult.Yes)
      e.SetObserved();
  }
}

因みに

PowerShellイベントハンドラでは、$_に何かが入っている。

参考

C#, VB http://www.atmarkit.co.jp/ait/spv/1512/16/news026.html

C# http://blog.jhashimoto.net/entry/20101212/1292138123

Technet

https://technet.microsoft.com/de-de/subscriptions/system.windows.application.dispatcherunhandledexception(v=vs.85)

sample

http://thinkami.hatenablog.com/entry/2014/09/04/061854

Code Project

http://www.codeproject.com/Articles/90866/Unhandled-Exception-Handler-For-WPF-Applications

Powershell 例外処理

PowerShell 例外処理

例外処理には二種類。

  1. Trap [例外] {}
  2. Try{}Catch[例外]{}Finally{}

Trap

書式: Trap [例外] {例外処理}

Trap例外処理中の break,continue

  • break: 処理を終了する。
  • continue: 処理を継続する。

Try Catch

書式: Try{}Catch[例外]{}Finally{}

Throw

書式: Throw 文字列

どの例外をThrowするのか?

$Error

$Error[0]に最新のErrorそれ以降に過去のErrorが入っている。

$ErrorActionPreference

  • Stop
  • Continue
  • SilentlyContinue

Trapのスコープ?

  1. 現スコープから外に向かってTrapが探索される
  2. break break文のスコープから抜け、外側のスコープのTrap処理を実行。
  3. continue そのスコープ内で次の処理を実行。

説明用の例

trap { continue } continue0
Func1 {
  trap { break } # break1
  Func2 {
    trap { continue } # continue2
    Func3 {
       trap { break } # break3
       1/0 # exception3
        $a = 3 # sentence3
    }
    Func3
    $a=2 # sentence2
  }
   Func2
   2/0 # exception1
   $a=4 # sentence1
}
Func1
$a=5 # sentence0

上記exception3により、break3 が処理され、sentence3を実行せずにFunc3を抜ける。その後、continue2が処理され、Func3の次のsentence2を実行する。

その後、exception1によりbreak1 -> (sentence1 skip) -> continue0 -> sentence0が実行される。

参考

http://capm-network.com/?tag=PowerShell例外処理

スコープ http://mtgpowershell.blogspot.jp/2011/04/trap.html?m=1

Powershell 圧縮とshellオブジェクト

Powershell 圧縮

Comでshell にzipファイルを渡してCopyHere($filename)

注意点は、非同期処理対応。 重複試験はhashかなぁ。

なお、圧縮パスワードは設定できない。 解凍パスワードは、引数指定不可、ダイアログが表示される。

下記では、全ファイルをCopyHereに渡した後に圧縮待ちを入れた。

圧縮

$zip = "C:\a.zip"
$src = "C:\tmp"

# zip削除
if(Test-Path -Path $zip){
    Remove-Item -Path $zip
}
# zip作成
"PK"+ [char]5 + [char]6  + ("$([char]0)"*18) | `
New-Item -Path $zip -Type File

# shell作成
$shell = New-Object -comObject Shell.Application
$folder = $shell.NameSpace($zip)
# hash
$hash = @{}
$num=0
foreach($el in ($src | %{Get-Item $_})){
    if ( $hash.ContainsKey($el) ){continue}
    $hash[$el] = $true
    $num++
    $folder.CopyHere($el.FullName)
}
# wait untill zip complete
while($true){
  if( $num -le $folder.Items().Count ){break}
  Start-Sleep -milliseconds 500
}
return $hash.Keys

解凍1

comのshellを使う。comリリースも忘れずに。

$file = "D:\Desktop\test.zip"
$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace($file)
$dest =  $shell.NameSpace((Split-Path $file -Parent))

$dest.CopyHere($zip.Items())

$zip = $null ; $dest=$null

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)

Remove-Variable shell

解凍2

解凍は少し簡単

function psunzip {
   #エクスプローラーのオブジェクトを作成する
   $Expcom = New-Object -ComObject Shell.Application

   #第一引数のzipファイルパスを登録
   $zipFile = $Expcom.NameSpace($args[0])

   #第二引数の出力先ディレクトリパスを登録
   $tgtDir = $Expcom.NameSpace($args[1])

   #zipファイル内のオブジェクト(ファイル)一覧を取得してForEach-Objectに渡す
   $zipFile.Items() | ForEach-Object {

      #ファイルを一つずつ出力先ディレクトリにコピー
      $tgtDir.CopyHere($_.path)
   }
}

参考

COM http://memo-space.blogspot.jp/2010/01/powershellzip.html?m=1

少しスマート http://www.casleyconsulting.co.jp/blog-engineer/windows-powershell/windows-powershellを使ってデータファイルを圧縮するバッチを/

解凍1

http://mtgpowershell.blogspot.jp/2011/02/zip.html?m=1

解凍2

http://qiita.com/kmr_hryk/items/5dfe87c0035887cbd8e4

7zip

https://sevenzip.osdn.jp/howto/dos-command-password.html

PSから7zip使用

http://qiita.com/arachan@github/items/1147915cd0bcc011872f

wsh

http://bitdatasci.blogspot.jp/2015/10/windowsoszipwsh.html?m=1

shellオブジェクト

http://www.roy.hi-ho.ne.jp/mutaguchi/wsh/object/shell.htm

shell.namespace($folder)が使える。

folderオブジェクト

http://www.roy.hi-ho.ne.jp/mutaguchi/wsh/object/shellfol.htm

使えるメソッド

  • CopyHere(path|FolderItem|FolderItems, vOptions)
  • MoveHere(同上)
  • Items()
  • ParseName(string)

Property

  • ParentFolder
  • Title

FolderItems

  • Item(#)
  • Count

vOptions

定数名と値 意味

Const FOF_ALLOWUNDO = &H40   エクスプローラで「編集」→「元に戻す」コマンドで操作を取り消せるようになる。
Const FOF_CONFIRMMOUSE = &H2    (未使用)
Const FOF_FILESONLY = &H80  ワイルドカードを指定したとき(*.*)、フォルダを対象外にする。
Const FOF_MULTIDESTFILES = &H1  ?
Const FOF_NOCONFIRMATION = &H10 上書き確認などのダイアログが表示されなくなる。
Const FOF_NOCONFIRMMKDIR = &H200    フォルダを作成する確認ダイアログが表示されなくなる。
Const FOF_RENAMEONCOLLISION = &H8   コピーや移動先に同名のファイルが存在する場合、"コピー ~ filename.ext"のように、リネームする。
Const FOF_SILENT = &H4  経過ダイアログが表示されなくなる。
Const FOF_SIMPLEPROGRESS = &H100    ファイル名の表示されない、シンプルな経過ダイアログが表示される。
Const FOF_WANTMAPPINGHANDLE = &H20  ?

参考

vb

http://bitdatasci.blogspot.jp/2015/10/windowsoszipwsh.html?m=1

Create Shortcut

ショートカットファイル作成

Powershell でショートカットファイル作成。

com のwshで作成する。

$wsh = New-Object -comObject WScript.Shell
$link = $wsh.CreateShortcut("D:\desktop\notepad.lnk")
$link.TargetPath = "notepad.exe"
$link.Description = "メモ帳"
$link.WorkingDirectory = $home
$link.IconLocation = "notepad.exe"
$link.Save()

# 廃棄

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wsh)
remove-valiable link

参考

デスクトップにメモ帳のショートカット作成

http://www.atmarkit.co.jp/ait/spv/0409/17/news086_3.html

http://mtgpowershell.blogspot.jp/2010/11/blog-post_27.html?m=1

パッケージ

パッケージ内の記述例

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\ショートカット スクリプト..lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "ショートカット スクリプト."
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\マイクロソフトの Web サイト.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\ショートカット スクリプト.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "ショートカット スクリプト";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\マイクロソフト Web サイト.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

https://msdn.microsoft.com/ja-jp/library/cc364400.aspx