2006/07/14

元記事はhttp://winscript.s41.xrea.com/mt/archives/2005/09/com.htmlです。

PowerShellでは.NETのオブジェクトのほかに、COMのオブジェクトも呼び出すことができます。呼び出し方は$Fs = new-object -com Scripting.FileSystemObjectのようにします。

このサンプルは、深い階層に新しいフォルダを再帰的に作成していくスクリプトです。

function CreateFolderEx ($Path){
 $sParent=$Fs.GetParentFolderName($Path)
 if ($Fs.FolderExists($sParent) -And !$Fs.FolderExists($Path)) {
  [void]$Fs.CreateFolder($Path)
 } elseif ($Fs.FolderExists($Path)) {
 } else {
  CreateFolderEx($sParent)
  [void]$Fs.CreateFolder($Path)
 }
}
$Fs = new-object -com Scripting.FileSystemObject
CreateFolderEx "C:\test\test\aaaa\wwww\aaa" 

FolderExistsと($Path)の間にスペースを入れるとエラーになるのに注意です。(beta 2ではならなかったのに…)

function CreateFolderEx ($Path){

は、

function CreateFolderEx {
Param($Path)

と書くこともできますが、個人的にこちらの書き方は冗長じゃないかなあという気がします。betaとの互換性のために残されているだけかもしれません。

ちなみに、.NET FrameworkのSystem.IO.DirectoryInfoクラスを使うならこんな面倒なことは必要ありません。

$di = new-object System.IO.DirectoryInfo("C:\test\test\aaaa\wwww\aaa")
$di.Create()
元記事:http://blogs.wankuma.com/mutaguchi/archive/2006/07/14/32456.aspx

古い記事へ | 新しい記事へ


プライバシーポリシー

Twitter

Books