#
#
#

$Host.PrivateData.ErrorForegroundColor = "cyan"

#rm alias:ll -force
rm alias:cd -force
rm alias:dir -force

set-alias ll custom_ll
set-alias dir custom_ll
set-alias cd custom_cd

$LS_COLORS = @()
@('exe', 'bat', 'ps1', 'asde', 'cmd', 'com') | ForEach-Object {
$w='\.'+$_+'$'; $LS_COLORS += ,@( $w, 'yellow', '') }
@('\.tar$', '\.tgz$', '\.arj$', '\.taz$', '\.lzh$', '\.zip$', '\.z$')|ForEach-Object {
$LS_COLORS += ,@( $_, 'magenta ', '') }
@('\.jpg$', '\.gif$', '\.bmp$', '\.xbm$', '\.xpm$', '\.png$', '\.tif$')| ForEach-Object {
$LS_COLORS += ,@( $_, 'Cyan', 'black')}
@('\.wmv$', '\.doc$', '\.txt$', '\.pdf$', '\.log$') | ForEach-Object {
$LS_COLORS += ,@( $_, 'Cyan', '')}
@('\.mp4$', '\.docx$') | ForEach-Object {
$LS_COLORS += ,@( $_, 'Cyan', '')}
@('\.clean$', '\.bak$','\.org$') | ForEach-Object {
$LS_COLORS += ,@( $_, 'gray', '')}
@('^.{28}d') | ForEach-Object { $LS_COLORS += ,@( $_, 'green', '')}

function prompt {
# $bakup = New-Object management.Automation.Host.Coordinates(0, 0)
# $coordinate = New-Object management.Automation.Host.Coordinates(0, 10)
$bakup = (Get-Host).UI.RawUI.CursorPosition
$head = (Get-Host).UI.RawUI.WindowPosition
$head.x = (Get-Host).UI.RawUI.WindowSize.Width - 20

$Host.UI.RawUI.CursorPosition = $head
# Write-Host $(get-date -format f)
color-Write -Green $(get-date -format f)
$Host.UI.RawUI.CursorPosition = $bakup
# "" + $(short_path $(get-location)) + "`r`n" + $(get-date -format f) + "> "
# "" + $(short_path $(get-location)) + " " + $(Get-Date -format "hh:mm:ss") + "> "
"" + $(path_compact $(get-location)) + "> "
# "" + $(get-date -format f) + "> "
}

# Win32PathCompactPathEx 呼出
$Signature =@"
[DllImport("Shlwapi.dll")]
public static extern uint PathCompactPathEx( StringBuilder pszOut, string pszSrc, uint cchMax, ulong dwFlags );
"@
$Getprivate = add-type -memberDefinition $Signature -name "Win32PathCompactPathEx" -namespace Win32Utils -Using System.Text -passthru

function path_compact {
$out = New-Object System.Text.StringBuilder 512
$null = $Getprivate::PathCompactPathEx($out, $args[0], 30, 0)
return $out.ToString()
}

function custom_cd {
$c = "Set-Location " + '"' + $args + '"'
Invoke-Expression $c
custom_ll
}

function custom_ll {
$gm = get-childitem $args
if (!$gm)
{
return $gm
}
if( ($myinvocation.PipelineLength -ne $myinvocation.PipelinePosition) `
-or ($myinvocation.Line -match '>') ){
return $gm
}

switch( $gm[0].gettype().basetype.name ){
default {
return $gm
}
'FileSystemInfo' {
$c1 = @{Label="LastWriteTime"; Expression={datetime_jpn($_.LastWriteTime)} }
$c2 = @{Label="Size”; Expression={ if($_.Mode[0] -ne 'd') {file_size($_.Length)}else{" "*10}}; Alignment="right"}

# $c3 = @{Label="Mode"; Expression={$_.Mode -Replace "-"," " -Replace "^.{2}.","" } }
$c3 = @{Label="Mode"; Expression={$_.Mode -Replace "-"," " } }
# $c4 = @{Label="Name"; Expression={$_.Name}; Alignment="right"}

# Write-host "`nディレクトリ: " $(Get-Location) "`n"
$gm | format-table $c1, $c2, $c3, Name -auto -wrap | Format-Line-Color $LS_COLORS $myinvocation
# -width (((Get-Host).UI.RawUI.WindowSize.Width) - 41)
}
}
}

function color-Write
{
# DO NOT SPECIFY param(...)
# we parse colors ourselves.

$allColors = ("-Black", "-DarkBlue","-DarkGreen","-DarkCyan","-DarkRed","-DarkMagenta","-DarkYellow","-Gray",
"-Darkgray","-Blue", "-Green", "-Cyan", "-Red", "-Magenta", "-Yellow", "-White")
$foreground = (Get-Host).UI.RawUI.ForegroundColor # current foreground
$color = $foreground
[bool]$nonewline = $false
$sofar = ""
$total = ""

foreach($arg in $args)
{
if ($arg -eq "-nonewline") { $nonewline = $true }
elseif ($arg -eq "-foreground")
{
if ($sofar) { Write-Host $sofar -foreground $color -nonewline }
$color = $foregrnd
$sofar = ""
}
elseif ($allColors -contains $arg)
{
if ($sofar) { Write-Host $sofar -foreground $color -nonewline }
$color = $arg.substring(1)
$sofar = ""
}
else
{
$sofar += "$arg "
$total += "$arg "
}
}
# last bit done special
if (!$nonewline)
{
Write-Host $sofar -foregroundcolor $color
}
elseif($sofar)
{
Write-Host $sofar -foregroundcolor $color -nonewline
}
}

function file_size {
if( $args[0] -ge 1TB ){
return "{0,7:#,###.00}" -F ($args[0] / 1TB) + " TB"
}
if( $args[0] -ge 1GB ){
return "{0,7:#,###}" -F ($args[0] / 1GB) + " GB"
}
if( $args[0] -ge 1MB ){
return "{0,7:#,###}" -F ($args[0] / 1MB) + " MB"
}
if( $args[0] -ge 1KB ){
return "{0,7:#,###}" -F ($args[0] / 1KB) + " KB"
}
return "{0,7:#,##0}" -F $args[0] + " B "

}

function datetime_jpn {
return $args[0].ToString( "yyyy/MM/dd HH:mm" )
}
function df {
$disks = get-wmiobject Win32_LogicalDisk | ?{$_.DriveType -eq 3}
foreach ($disk in $disks)
{
write-host "ドライブレター : " $disk.DeviceID
write-host "容量 : " $(file_size($disk.Size))
write-host "空き容量 : " $(file_size($disk.FreeSpace))
write-host "使用量 : " $(file_size($disk.Size - $disk.FreeSpace))
}
}

function getcpu {
$WmiObject = Get-WmiObject Win32_Processor
Write-Host "Name :" $WmiObject.Name
Write-Host "Caption :" $WmiObject.Caption
# Write-Host "Manufacturer :" $WmiObject.Manufacturer
# Write-Host "SocketDesignation :" $WmiObject.SocketDesignation
# Write-Host "CurrentClockSpeed :" $WmiObject.CurrentClockSpeed
Write-Host "L2 CacheSize :" $WmiObject.L2CacheSize
}

function getbios {
$WmiObject = Get-WmiObject Win32_BIOS
Write-Host "Manufacturer :" $WmiObject.Manufacturer
Write-Host "Version :" $WmiObject.Version
Write-Host "BIOS Version :" $WmiObject.SMBIOSBIOSVersion
}

function getmemory {
$WmiObjects = Get-WmiObject Win32_physicalMemory
Write-Host "Number Manufacturer Capacity Speed"
Write-Host "----------------- --------------------------- -------- -----"
foreach( $WmiObject in $WmiObjects )
{
Write-Host $WmiObject.tag $WmiObject.Manufacturer ($WmiObject.Capacity / 1MB) "MB " $WmiObject.Speed
# Write-Host "tag :" $WmiObject.tag
# Write-Host $WmiObject.tag
# Write-Host "Manufacturer :" $WmiObject.Manufacturer
# Write-Host "Capacity :" ($WmiObject.Capacity / 1MB) "MB"
# Write-Host "Speed :" $WmiObject.Speed
# Write-Host
}
}

# administrator時にメッセージ
If($True -eq ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Output ""
Write-Output "CAUTION: PowerShell is running with administrator credentials!"
Write-Output ""
Write-Output ""
}

function ver()
{
$PSVersionTable
}

function event()
{
@('ERROR') | ForEach-Object { $f += ,@( $_, 'Black', 'RED') }

get-eventlog -list | ForEach-Object {
try {
$evt = get-eventlog -logname $_.log -EntryType Error -after (get-date).AddDays(-7) -errorAction:silentlyContinue
if ($evt) {
$_.log
$evt | ft -auto -wrap | Format-Word-Color $f $myinvocation
}
}
catch {}
}
}

function Format-Line-Color() {
param (
[System.Array] $Colors = @(),
[object] $miv = $myinvocation,
[switch] $isPipe
)
if( ($miv.PipelineLength -ne $miv.PipelinePosition) `
-or ($isPipe) `
-or ($miv.Line -match '>') ){
return $input
# return $input -replace "`r", "" -split "`n" | Out-String -stream
}
# $width = ((Get-Host).UI.RawUI.WindowSize.Width) - 35
# $lines = ( $input | out-string -width $width ) -replace "`r", "" -split "`n"
$lines = ( $input | out-string ) -replace "`r", "" -split "`n"

# fixed配列で最後に空の項目が out-stringにより追加される
# なので、配列の0添字開始と最終行カットで-2とする。
# $lines | ForEach-Object {
foreach($data in $lines[0..($lines.Count-2)]) {
$data = $data.TrimEnd()
$color = @{}
foreach($pattern in $Colors) {
if($data -match $pattern[0] ) {
if ($pattern[1]){
$color.Add("foreground", $pattern[1])
}
if ($pattern[2]){
$color.Add("background", $pattern[2])
}
break
}
}
Write-Host $data @color
}
}

function Format-Word-Color {
param (
[System.Array] $Colors = @(),
[object] $miv = $myinvocation,
[switch] $isPipe
)
if( ($miv.PipelineLength -ne $miv.PipelinePosition) `
-or ($isPipe) `
-or ($miv.Line -match '>') ){
return $input
}
# $width = ((Get-Host).UI.RawUI.WindowSize.Width) - 35
# $lines = ( $input | out-string -width $width ) -replace "`r", "" -split "`n"
$lines = ( $input | out-string) -replace "`r", "" -split "`n"

# fixed配列で最後に空の項目が out-stringにより追加される
# なので、配列の0添字開始と最終行カットで-2とする。
foreach($data in $lines[0..($lines.Count-2)]) {
$data = $data.TrimEnd()
while($data) {
foreach($pattern in $Colors) {
$wk = ($data -match "(?.*?)(?$($pattern[0]))(?.*)" )
if ($wk) {
break
}
}
if ($wk) {
$data = $matches.bottom
if($matches.front) {
Write-Host $matches.front -NoNewline
}
$color = @{}
if ($pattern[1]){
$color.Add("foreground", $pattern[1])
}
if ($pattern[2]){
$color.Add("background", $pattern[2])
}
Write-Host $matches.word @color -NoNewline
}
else {
Write-Host $data -NoNewline
break
}
}
Write-Host
}
}

Function ExcelToCSV ($excelFileName, $csvLoc)
{
$files = Resolve-Path $excelFileName
$csvLocFull = Convert-Path ($csvLoc)
Foreach ($file in $files)
{
$excelLeaf = Split-Path $file -Leaf
$excelLeaf = [Regex]::Replace($excelLeaf, "\.xls$","")
$excelLeaf = [Regex]::Replace($excelLeaf, "\.xls4","")
$excelLeaf = [Regex]::Replace($excelLeaf, "\.xlsx$","")
$excelLeaf = [Regex]::Replace($excelLeaf, "\.xlsm$","")
$excelLeaf = [Regex]::Replace($excelLeaf, "\.xlsb$","")

$excelFile = Convert-Path($file)
$E = New-Object -ComObject Excel.Application
$E.Visible = $false
$E.DisplayAlerts = $false
$wb = $E.Workbooks.Open($excelFile)
foreach ($ws in $wb.Worksheets)
{
$n = $excelLeaf + "_" + $ws.Name

# $a = $csvLocFull + '\' + $n + ".csv"
# Write-Host $a

$ws.SaveAs($csvLocFull + '\' + $n + ".csv", 6)
}
$E.Quit()
[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($E)
}
}

# administrator時にメッセージ
If($True -eq ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Output ""
Write-Output "CAUTION: PowerShell is running with administrator credentials!"
Write-Output ""
Write-Output ""
}

function vim() {
$x = (Get-Host).UI.RawUI.WindowSize.Width
$y = (Get-Host).UI.RawUI.WindowSize.Height
$p = '""C:\Program Files (x86)\Vim\vim80\vim.exe" -c "set columns=' + $x + '" -c "set lines=' + $y + '" ' + $args + '"'
# Write-Output $p
cmd /s /c $p
}

Get-Culture
Write-Output ""
getcpu
Write-Output ""
getbios
Write-Output ""
getmemory