programing

PowerShell 객체가 존재하는지 확인하는 가장 좋은 방법은 무엇입니까?

cafebook 2023. 4. 8. 09:14
반응형

PowerShell 객체가 존재하는지 확인하는 가장 좋은 방법은 무엇입니까?

Com Object가 존재하는지 확인하는 가장 좋은 방법을 찾고 있습니다.

가지고 있는 코드는 다음과 같습니다.마지막 행을 개선하고 싶습니다.

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

$ie -ne $null #Are there better options?

난 계속 할 거야$null'' 문자열 (빈 문자열),0,$false ★★★★★★★★★★★★★★★★★」$null will will the will will will will will will will will will will will 。if ($ie) {...}.

할 수도 있습니다.

if ($ie) {
    # Do Something if $ie is not null
}

이 모든 답변에서 강조되지 않는 것은 값을 $null과 비교할 때 왼쪽에 $null을 입력해야 한다는 것입니다. 그렇지 않으면 수집 유형 값과 비교할 때 문제가 발생할 수 있습니다.참조: 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"
}

위의 블록은 (불행하게도) 실행됩니다.더욱 흥미로운 점은 Powershell에서 $값은 $null이 아니라 $null이 될 수 있다는 것입니다.

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

따라서 컬렉션과 비교하려면 왼쪽에 항상 $null을 넣는 것이 중요합니다.

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

나는 이것이 파워셸의 힘을 다시 한번 보여주는 것 같아!

예에서는, 체크를 전혀 실시할 필요가 없는 경우가 있습니다.그게 가능합니까?New-Objectreturn null?나는 그것을 본 적이 없다.이 명령어는 문제가 발생했을 때 실패하며 예제의 나머지 코드는 실행되지 않습니다.그럼 왜왜 리리 사? ???

아래 코드만 체크가 필요합니다($null과의 명시적인 비교가 가장 좋습니다).

# 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) {
    ...
}

-is 연산자를 사용하여 type-check를 실행하면 null 값에 대해 false가 반환됩니다.전부는 아니지만 대부분의 경우 $value는 [시스템]입니다.Object]는 null이 아닌 임의의 값에 대해 true가 됩니다.(모든 경우 null 값에 대해 false가 됩니다).

나의 가치는 물건이 아니면 아무것도 아니다.

나도 같은 문제가 있었다.이 솔루션은 나에게 효과가 있다.

$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

예를 들어, 저와 같은 고객이 PowerShell 변수가 존재하지 않는 특정 맛인지 여부를 판단하기 위해 이곳에 도착한 경우:

기본 RCW에서 분리된 COM 개체는 사용할 수 없습니다.

그럼 여기 몇 가지 코드가 있습니다.

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

사용 예:

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

다른 사람들의 더 나은 대답으로부터 함께 뭉쳐진 것:

그 밖에 알아두면 좋을 것 같습니다.

나는 이 질문이 (비록 오래되긴 하지만) 정말 쓸모없는 가치를 확인하는 질문이라고 믿는다.PowerShell에서 null(또는 null이 아님) 값을 확인하는 것은 어렵습니다.($null - eq $value) 또는 ($null -ne $value)를 사용하는 것이 항상 작동하는 것은 아닙니다.if($value)도 마찬가지입니다.그것들을 사용하는 것은 나중에 문제를 일으킬 수도 있다.
Powershell에서 null이 얼마나 까다로운지를 이해하려면 다음 마이크로소프트 기사(IT's 전체)를 읽어보십시오.

[https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1] [1]

PowerShell에서 null(또는 null이 아닌) 값을 확인하기 위해 아래 두 가지 함수를 작성했습니다.모든 가치와 데이터 유형에 대해 기능해야 한다고 생각합니다.

누가 도움이 됐으면 좋겠어요.MS가 PowerShell에서 Null을 쉽게 처리할 수 있도록 PowerShell에 기본적으로 이와 같은 기능을 탑재하지 않은 이유를 잘 모르겠습니다.

이게 도움이 됐으면 좋겠어요.

이 방법의 눈에 띄지 않는 「함정」이나 문제를 알고 있는 사람이 있으면, 여기에 코멘트를 달아 주세요.감사합니다!

<#
*********************  
FUNCTION: ValueIsNull
*********************  
Use this function ValueIsNull below for checking for null values
rather using -eq $null or if($value) methods.  Those may not work as expected.     
See reference below for more details on $null values in PowerShell. 
[https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1][1]

An if statement with a call to ValueIsNull can be written like this:
if (ValueIsNull($TheValue))    
#>

function ValueIsNull {
  param($valueToCheck)
  # In Powershell when a parameter of a function does not have a data type defined,
  # it will create the parameter as a PSObject. It will do this for 
  # an object, an array, and a base date type (int, string, DateTime, etc.)
  # However if the value passed in is $null, then it will still be $null.
  # So, using a function to check null gives us the ability to determine if the parameter
  # is null or not by checking if the parameter is a PSObject or not.
  # This function could be written more efficiently, but intentionally 
  # putting it in a more readable format.
  # Special Note: This cannot tell the difference between a parameter
  # that is a true $null and an undeclared variable passed in as the parameter.
  # ie - If you type the variable name wrong and pass that in to this function it will see it as a null.
  
  [bool]$returnValue = $True
  [bool]$isItAnObject=$True
  [string]$ObjectToString = ""
  
  try { $ObjectToString =  $valueToCheck.PSObject.ToString() } catch { $isItAnObject = $false }

  if ($isItAnObject)
  {
    $returnValue=$False
  }

  return $returnValue
}
<# 
************************
FUNCTION: ValueIsNotNull 
************************
Use this function ValueIsNotNull below for checking values for 
being "not-null"  rather than using -ne $null or if($value) methods.
Both may not work as expected.

See notes on ValueIsNull function above for more info.

ValueIsNotNull just calls the ValueIsNull function  and then reverses
the boolean result. However, having ValueIsNotNull available allows
you to avoid having  to use -eq and\or -ne against ValueIsNull results.
You can disregard this function and just use !ValueIsNull($value). 
But, it is my preference to have both for easier readability of code.

An if statement with a call to ValueIsNotNull can be written like this:
if (ValueIsNotNull($TheValue))    
#>

function ValueIsNotNull {
  param($valueToCheck)
  [bool]$returnValue = !(ValueIsNull($valueToCheck))
  return $returnValue
}

Value Is Null에 대한 다음 콜목록을 사용하여 테스트할 수 있습니다.

  $psObject = New-Object PSObject
  Add-Member -InputObject $psObject -MemberType NoteProperty -Name customproperty -Value "TestObject"
  $valIsNull = ValueIsNull($psObject)

  $props = @{
    Property1 = 'one'
    Property2 = 'two'
    Property3 = 'three'
    }
  $otherPSobject = new-object psobject -Property $props
  $valIsNull = ValueIsNull($otherPSobject)
  # Now null the object
  $otherPSobject = $null
  $valIsNull = ValueIsNull($otherPSobject)
  # Now an explicit null
  $testNullValue = $null
  $valIsNull = ValueIsNull($testNullValue)
  # Now a variable that is not defined (maybe a type error in variable name)
  # This will return a true because the function can't tell the difference
  # between a null and an undeclared variable.
  $valIsNull = ValueIsNull($valueNotDefine)

  [int32]$intValueTyped = 25
  $valIsNull = ValueIsNull($intValueTyped)
  $intValueLoose = 67
  $valIsNull = ValueIsNull($intValueLoose)
  $arrayOfIntLooseType = 4,2,6,9,1
  $valIsNull = ValueIsNull($arrayOfIntLooseType)
  [int32[]]$arrayOfIntStrongType = 1500,2230,3350,4000
  $valIsNull = ValueIsNull($arrayOfIntStrongType)
  #Now take the same int array variable and null it.
  $arrayOfIntStrongType = $null
  $valIsNull = ValueIsNull($arrayOfIntStrongType)
  $stringValueLoose = "String Loose Type"
  $valIsNull = ValueIsNull($stringValueLoose)
  [string]$stringValueStrong = "String Strong Type"
  $valIsNull = ValueIsNull($stringValueStrong)
  $dateTimeArrayLooseValue = @("1/1/2017", "2/1/2017", "3/1/2017").ForEach([datetime])
  $valIsNull = ValueIsNull($dateTimeArrayLooseValue)
  # Note that this has a $null in the array values.  Still returns false correctly.
  $stringArrayLooseWithNull = @("String1", "String2", $null, "String3")
  $valIsNull = ValueIsNull($stringArrayLooseWithNull)

다음과 같이 인스턴스화된 PsObject에서 if 문을 사용하여 테스트하려면 다음을 사용합니다.다른 유형의 개체를 사용하는 경우 다음 값보다 큰 값 옆의 값을 조정해야 합니다.

$tempObject = New-Object -TypeName PsObject;

if (($tempObject | Get-Member).Count -gt 4)

$tempObject | Get-Member

유형 이름:시스템.관리.자동화PS Custom Object(PSCustom 객체)

멤버 이름유형 정의
--------------------------------- Method Bool Equals(시스템)와 동일합니다.오브젝트 obj) GetHashCode 메서드 int GetHashCode() GetType 메서드타입 GetType()
ToString 메서드 문자열 ToString()

언급URL : https://stackoverflow.com/questions/4430067/best-way-to-check-if-an-powershell-object-exist

반응형