Главная

Monday, 11 January 2016

PowerShell and MS Excel 2010.

Hi all.

Do you imagine - PowerShell 2.0 is not working with MS Excel 2010 if your OS has interface language location another than English (en-US) ? Although PS is working well with MS Word 2010 by any language.

So, and what we have decision?

The good guys made Function for change Host.CurrentCulture to "en-US" on the fly.

Here is her code:

Function Using-Culture (
[System.Globalization.CultureInfo]$culture = (throw "USAGE: Using-Culture -Culture culture -Script {scriptblock}"),
[ScriptBlock]$script= (throw "USAGE: Using-Culture -Culture culture -Script {scriptblock}"))
{
    $OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
    trap
    {
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
    }
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
    Invoke-Command $script
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}

The string for using of this function:
using-culture en-US {get-date}

And below my simple PS-example of function application:

#get process
$a = Get-Process -name powershell*
$a

#function Using-Culture
Function Using-Culture (
[System.Globalization.CultureInfo]$culture = (throw "USAGE: Using-Culture -Culture culture -Script {scriptblock}"),
[ScriptBlock]$script= (throw "USAGE: Using-Culture -Culture culture -Script {scriptblock}"))
{
    $OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
    trap
    {
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
    }
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
    Invoke-Command $script
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}

Using-Culture en-US -Script {
$b = New-object -ComObject Excel.Application
$b.Visible= $true
$c = $b.WorkBooks.Add()
$d = $c.Sheets.Add()

#insert data to Excel
$d.Cells.Item(1,1) ="Process Name"
$d.Cells.Item(2,1) =$a.Name
$d.Cells.Item(1,2) ="ID"
$d.Cells.Item(2,2) =$a.ID
}

Good luck.

No comments:

Post a Comment

А что вы думаете по этому поводу?