コンテンツへスキップ

$oldSystemPath = [System.Environment]::GetEnvironmentVariable("path","Machine")
$newSystemPath = $oldSystemPath + ";" + <追加したいパス>
[System.Environment]::SetenvironmentVariable("Path",$newSystemPath,"Machine")

パスの確認

[System.Environment]::GetEnvironmentVariable("path","Machine") -split ";"

# 1Mバイトのファイルを作成
@(1..10) | Foreach{
    $random_bin = new-object byte[] (1024*1024); (new-object Random).NextBytes($random_bin); [IO.File]::WriteAllBytes("c:\tmp\test$_.dat", $random_bin)
}
# 最終更新日が任意のファイルを作成
for($i=0;$i -le 90;$i++){
    $file = $i.tostring() + ".log"
    $filepath = (join-path D:\log $file)
    new-item $filepath |out-null
    $j = "-" + $i
    Set-ItemProperty $filepath -Name LastWriteTime -Value (get-date).addDays($j) 
}

 

$a=@(3,2,1,5,4,8)
$b=@(4,2,3,1,5,6)
Compare-Object ($a|sort-object) ($b|sort-object) -IncludeEqual | foreach-object {
    $direction = $_.SideIndicator
    $value = $_.InputObject
    if( $direction -eq "<="){
        write-host("aにだけあり[{0}]" -f $value)
    } elseif ( $direction -eq "=>"){
        write-host("bにだけあり[{0}]" -f $value)
    } else {
        write-host("aとbにあり[{0}]" -f $value)
    }
}

 

# download itextsharp.dll.
# Invoke-WebRequest -Uri 'https://github.com/itext/itextsharp/releases/download/5.5.10/itextsharp-all-5.5.10.zip'

param(
    [parameter(mandatory=$false)][string]$ITextLibraryPath = "E:\tmp\itextsharp.dll",
    [parameter(mandatory=$false)][string]$InputFilePath    = "E:\tmp\input.pdf",
    [parameter(mandatory=$false)][string]$OutputFilePath   = "E:\tmp\output.txt"
)

[System.Reflection.Assembly]::LoadFrom($ITextLibraryPath) | Out-Null
$reader = New-Object iTextSharp.text.pdf.PdfReader -ArgumentList $InputFilePath
$pages = $reader.numberofpages

for($i=1;$i -le $pages;$i++){
    write-output("=============== page=[{0}] ===============" -f $i) >>$OutputFilePath
    [iTextSharp.text.pdf.parser.PdfTextExtractor]::GetTextFromPage($reader,$i) >> $OutputFilePath
}

 

bookから全シートの全データを抽出する。

■使い方

. .\ExcelDataClass.ps1

$e = new-object ExcelDataClass("c:\test.xlsx")

$e.ShowAllData()

■ExcelDataClass.ps1のコード

class ExcelDataClass{
    [string]$BookFilePath
    [System.Collections.Hashtable]$AllDataHash

    ExcelDataClass([string]$filepath){
        $this.BookFilePath = $filepath
        $excel = New-Object -ComObject Excel.Application
        $workbook = $excel.workbooks.open($filepath)
        $SheetList = new-object System.collections.arrayList
        $workbook.Sheets | foreach-object {
            $SheetName = $_.name
            $SheetList.add($SheetName)
        }
        $this.AllDataHash = new-object System.Collections.Hashtable
        foreach($SheetName in $SheetList){
            $ColHash = new-object System.Collections.Hashtable
            $sheet = $workbook.worksheets.Item($SheetName)
            $lastRow = $sheet.UseDrange.Rows.Count
            $lastCol = $sheet.UsedRange.Columns.Count
            for($col=1;$col -le $lastCol;$col++){
                $RowHash = new-object System.Collections.Hashtable
                for($row=1;$row -le $lastRow;$row++){
                    $val = $sheet.Cells.Item($row,$col).text.trim()
                    if($val -eq ""){
                        $val = "-"
                    }
                    $RowNum = ([string]$row).PadLeft(3,"0")
                    $RowHash.$RowNum = $val
                }
                $ColNum = ([string]$col).PadLeft(4,"0")
                $ColHash.$ColNum = $RowHash             
            }
            [void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($sheet)
            $this.AllDataHash.$SheetName = $ColHash
        }
        $workbook.close()
        $excel.Quit()
        [void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel)
    }

    [void]ShowAllData(){
        $this.AllDataHash.keys.getEnumerator() | sort-object value | foreach-object {
            $SheetName = $_
            $this.AllDataHash.$SheetName.keys.getEnumerator() | sort-object |foreach-object {
                $Col = $_
                $this.AllDataHash.$SheetName.$Col.keys.getEnumerator() | sort-object |foreach-object {
                    $Row = $_
                    $this.AllDataHash.$SheetName.$Col.$Row | foreach-object {
                        $v = $_
                        write-host("Sheet name:[{0}],Col:[{1}],Row:[{2}],Value:[{3}]" -f $SheetName,$Col,$Row,$v)
                    }
                }
            }
        }
    }

    [int]GetSheetLastCol([string]$sheetName){
        return $this.AllDataHash.$sheetName."0001".count
    }

    [int]GetSheetLastRow([string]$sheetName){
        return $this.AllDataHash.$sheetName.count
    }

    [system.collections.ArrayList]GetSheetList(){
        $a = new-object system.collections.ArrayList
        foreach($sheetName in $this.AllDataHash.keys){
            $a.add($sheetName)
        }
        return $a
    }
}

 

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $true


# 既存のブックを開く場合
$book = $excel.Workbooks.Open($bookfile)
# 新規の場合
$book = $excel.workbooks.add()

# シート追加
$excel.Worksheets.Add()

# シートの名前を変更
$book.Sheets(1).Name = "その1"
$book.Sheets(2).Name = "その2"
$book.Sheets(3).Name = "その3"


# セルに入力
$sheet = $book.Sheets("その1")
# $sheet.Cells.Item(行,列)
$sheet.Cells.Item(1, 2) = "テスト"
$sheet.Cells.Item(1, 3) = "テスト2"
$sheet.Cells.Item(1, 4) = "テスト3"
$sheet.Cells.Item(2, 2) = "テスト3--------------------------"

# 罫線を引く
$sheet.Range("A1:C3").Borders.LineStyle = 1

# 列の幅を自動調整
$sheet.Columns.AutoFit()

# セルの色を変更する。
$sheet.Cells.Item( 2, 2).Interior.ColorIndex = 3

# 終了
$book.SaveAs("${HOME}\Desktop\test.xlsx")
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet)

 

param(
    [parameter(mandatory=$true)][string]$filename
)

#$filename = "E:\my-document\powershell+word\テスト.docx"

$objWord = New-Object -Com Word.Application
$objWord.Visible = $false
$objDocument = $objWord.Documents.Open($filename)
$paras = $objDocument.Paragraphs

$pattern = "\[.*\]:.*\[.*\]"

foreach ($para in $paras) 
{ 
    #Write-Output $para.Range.Text
    $line = $para.Range.Text
    $line = $line.trim()
    if ($line -match $pattern) {
        write-output "Patternを含む=[" + $line + "]"
    } else {
        write-output "Pattern含まない=[" + $line + "]"
    }
}

 

ファイルの読み込み

# -*- coding:utf-8 -*-
import codecs

FILE="テキストファイル"
f=codecs.open(FILE,'rb','utf-8','')
contents=f.read()
f.close()
for line in contents.split('\n'):
    print(line)

ファイルへ出力

# -*- coding:utf-8 -*-
import codecs

FILE="test.txt"
f=codecs.open(FILE,'wb','utf-8')
f.write("書き込みテスト")
f.close()