¿La mejor manera de comprobar si existe un objeto de PowerShell?


Estoy buscando la mejor manera de comprobar si existe un objeto Com.

Aquí está el código que tengo, me gustaría mejorar la última línea:

$ie = New-Object -ComObject InternetExplorer.Application
$ie.Navigate("http://www.stackoverflow.com")
$ie.Visible = $true

$ie -ne $null #Are there better options?
Author: CJBS, 2010-12-13

7 answers

Me quedaría con la verificación $null ya que cualquier valor que no sea '' (cadena vacía), 0, $false y $null pasará la comprobación: if ($ie) {...}.

 89
Author: Keith Hill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 15:45:26

También puedes hacer

if ($ie) {
    # Do Something if $ie is not null
}
 48
Author: ravikanth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-23 19:03:52

En su ejemplo particular quizás usted no tiene que realizar ninguna comprobación en absoluto. ¿Es posible que New-Object devuelva null? Nunca he visto eso. El comando debe fallar en caso de un problema y el resto del código en el ejemplo no se ejecutará. Entonces, ¿por qué deberíamos hacer esos controles?

Solo en el código como a continuación necesitamos algunas comprobaciones (la comparación explícita con $null es la mejor):

# we just try to get a new object
$ie = $null
try {
    $ie = New-Object -ComObject InternetExplorer.Application
}
catch {
    Write-Warning $_
}

# check and continuation
if ($ie -ne $null) {
    ...
}
 12
Author: Roman Kuzmin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 17:35:01

Type-check con el operador-is devuelve false para cualquier valor null. En la mayoría de los casos, si no todos, value value-es [System.Object] será true para cualquier posible valor no nulo. (En todos los casos, será false para cualquier valor null.)

Mi valor no es nada si no es un objeto.

 1
Author: Aron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-12 11:30:03

Lo que todas estas respuestas no resaltan es que al comparar un valor con $null, debe poner $null en el lado izquierdo, de lo contrario puede tener problemas al comparar con un valor de tipo colección. Véase: https://github.com/nightroman/PowerShellTraps/blob/master/Basic/Comparison-operators-with-collections/looks-like-object-is-null.ps1

$value = @(1, $null, 2, $null)
if ($value -eq $null) {
    Write-Host "$value is $null"
}

El bloque anterior está (desafortunadamente) ejecutado. Lo que es aún más interesante es que en Powershell a value valor puede ser tanto {null y no null null:

$value = @(1, $null, 2, $null)
if (($value -eq $null) -and ($value -ne $null)) {
    Write-Host "$value is both $null and not $null"
}

Por lo tanto, es importante poner $null en el lado izquierdo para hacer que estas comparaciones funcionen con colecciones:

$value = @(1, $null, 2, $null)
if (($null -eq $value) -and ($null -ne $value)) {
    Write-Host "$value is both $null and not $null"
}

¡Supongo que esto muestra una vez más el poder de Powershell !

 1
Author: Dag Wieers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 16:31:51

Yo tenía el mismo problema. Esta solución funciona para mí.

$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
    $Word = new-object -ComObject word.application
}

Https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.marshal.getactiveobject(v=vs. 110).aspx

 0
Author: McHalley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-10 10:29:40

En caso de que usted es como yo y aterrizó aquí tratando de encontrar una manera de saber si su variable de PowerShell es este sabor particular de inexistente:

El objeto COM que ha sido separado de su RCW subyacente no puede ser utilizar.

Entonces aquí hay un código que funcionó para mí:

function Count-RCW([__ComObject]$ComObj){
   try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
   catch{return 0}
   return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}

Ejemplo de uso:

if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}

Mezclado de las mejores respuestas de otros pueblos:

Y algunas otras cosas interesantes para saber:

 0
Author: Gregor y,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-12 21:50:28