PowerShell Excel SaveAs method incorrect finished

Hello! I'm executing the code:

function Get-ActivationStatus {
[CmdletBinding()]
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] 
        [string]$DNSHostName = $Env:COMPUTERNAME 
    )
    process {
        try {
            $wpa = Get-WmiObject SoftwareLicensingProduct -ComputerName $DNSHostName `
            -Filter "ApplicationID = '55c92734-d682-4d71-983e-d6ec3f16059f'" `
            -Property LicenseStatus,Description -ErrorAction Stop
        }
        catch {
            $status = New-Object ComponentModel.Win32Exception ($_.Exception.ErrorCode) #  
            $wpa = $null
        } 
        $out = New-Object psobject -Property @{ 
            ComputerName = $DNSHostName
            Status = [string]::Empty
			Type = [string]::Empty
        }
        if ($wpa) {
            :outer foreach($item in $wpa) { 
                switch ($item.LicenseStatus) { 
                    0 {$out.Status = "Unlicensed"} 
                    1 {$out.Status = "Licensed"; break outer}
                    default {$out.Status = "Unknown value"}
                }
            }
			$out.Type = ($item.Description.Split(",")[1] -replace " channel").Trim() 
        } else {$out.Status = $status.Message} 
        $out
    }
}

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
}

$code={
$x= $y= $z = 2
$filter = "(&(objectclass=computer)(dnshostname=*)(!operatingsystem=Windows XP Professional)(name=w*)(!userAccountControl:1.2.840.113556.1.4.803:=2))"
$sr = [adsisearcher]$filter
$sr.SearchRoot = [ADSI]"LDAP://dc=domain,dc=com"
$pcs = ([adsisearcher]$filter).FindAll() | Foreach {
	$o = $_.Properties.Item("operatingsystem")
	$_.Properties.Item("dnshostname") | Get-ActivationStatus  | Select ComputerName,Status,Type,@{n="OperatingSystem";e={$o}} 
}
$xl = new-object -comobject excel.application
$xl.visible = $true 
$b = $xl.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Name = "Undefined 2015" 
$c.columns.item(1).columnWidth = 75 
$c.columns.item(2).columnWidth = 75 

$c.cells.item(1,1) = "Name"
$c.cells.item(1,2) = "Status"

$d = $b.Worksheets.Add() 
$d.Name = "No licenses 2015"
$d.columns.item(1).columnWidth = 75 
$d.columns.item(2).columnWidth = 75

$d.cells.item(1,1) = "Name"
$d.cells.item(1,2) = "OS" 

$e = $b.Worksheets.Add(1) 
$e.Name = "Licenses 2015" 
$e.columns.item(1).columnWidth = 75 
$e.columns.item(2).columnWidth = 75 
$e.columns.item(3).columnWidth = 75 

$e.cells.item(1,1) = "Name" 
$e.cells.item(1,2) = "License type" 
$e.cells.item(1,3) = "OS" 


foreach($pc in $pcs) 
{
	
	switch($pc.Status)
	{
		"Licensed" 		{ 
			$e.cells.item($x,1) = $pc.ComputerName 
			$e.cells.item($x,2) = $pc.Type
			$e.cells.item($x,3) = $pc.OperatingSystem
			$x++
		}
		"Unlicensed" 	{ 
			$d.cells.item($y,1) = $pc.ComputerName 
			$d.cells.item($y,2) = $pc.OperatingSystem 
			$y++
		}
		default { 
			$c.cells.item($z,1) = $pc.ComputerName 
			$c.cells.item($z,2) = $pc.Status 
			$z++
		}
	}
}

$b.saveas("c:\License.xls") 
}
Using-Culture en-us $code
[gc]::collect()
[gc]::WaitForPendingFinalizers()

This is script is workable. However, I'm getting this error at the end of script execution:

Invoke-Command : Exception at calling "SaveAs" with "1" arguments: "Access error to the document 'License.xls', allowed read-only access."

What can I do to avoid that?

It don't critical, but I really want to know why so.

June 22nd, 2015 1:59am

that usually means the file is already open or that you do not have access to the file.

Running Excel under an Invoke is not allowed by Microsoft as it constitutes running as a service which is not supports.  It is not necessary to use Invoke here so you should remove it.

Free Windows Admin Tool Kit Click here and download it now
June 22nd, 2015 7:41am

Do you mean Invoke-Command $script? If I remove that (and [ScriptBlock]$script= (throw "USAGE:...), then script didn't work (it's execetud, but no output)). 
June 23rd, 2015 1:27am

Just run the scrip without making it a script block.  There is no point in doing that. 

I suspect you copied this from somewhere.  Have the original author fix it for you.

Free Windows Admin Tool Kit Click here and download it now
June 23rd, 2015 1:33am

Here.  This will likely work better and still open in Excel.

function Get-ActivationStatus {
    [CmdletBinding()]
    [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
    [string]$DNSHostName = $Env:COMPUTERNAME
    )
    process {
        try {
            $wpa = Get-WmiObject SoftwareLicensingProduct -ComputerName $DNSHostName `
                                 -Filter "ApplicationID = '55c92734-d682-4d71-983e-d6ec3f16059f'" `
                                 -Property LicenseStatus, Description -ErrorAction Stop
        } catch {
            $status = New-Object ComponentModel.Win32Exception ($_.Exception.ErrorCode) #  
            $wpa = $null
        }
        $out = New-Object psobject -Property @{
            ComputerName = $DNSHostName
            Status = [string]::Empty
            Type = [string]::Empty
        }
        if ($wpa) {
            :outer foreach($item in $wpa) {
                switch ($item.LicenseStatus) {
                    0 { $out.Status = "Unlicensed" }
                    1 { $out.Status = "Licensed"; break outer }
                    default { $out.Status = "Unknown value" }
                }
            }
            $out.Type = ($item.Description.Split(",")[1] -replace " channel").Trim()
        } else { $out.Status = $status.Message }
        $out
    }
}

$filter='(&(objectclass=computer)(!operatingsystem=Windows XP Professional)(name=w*)(!userAccountControl:1.2.840.113556.1.4.803:=2))'
$sr = [adsisearcher]$filter
([adsisearcher]$filter).FindAll() |
    Foreach {
        $o = $_.Properties.Item('operatingsystem')
        $_.Properties.Item("dnshostname") |
        Get-ActivationStatus | Select ComputerName, Status, Type, @{ n = "OperatingSystem"; e = { $o } }
    } |
  Export-Csv c:\temp\License.Csv -Notype
. c:\temp\License.Csv

You should not attempt to write to the root of C as it is protected on mall new systems.

June 23rd, 2015 1:41am

Thanks for answer. Simply changing location of saving file, the error is dissaper.
  • Marked as answer by Net Ranger 17 hours 17 minutes ago
Free Windows Admin Tool Kit Click here and download it now
June 23rd, 2015 9:53am

Thanks for answer. Simply changing location of saving file, the error is dissaper.
  • Marked as answer by Net Ranger Tuesday, June 23, 2015 1:51 PM
June 23rd, 2015 1:51pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics