PowerShell 개체가 있는지 확인하는 가장 좋은 방법은 무엇입니까?
Com 개체가 있는지 확인하는 가장 좋은 방법을 찾고 있습니다.
내가 가지고있는 코드는 다음과 같습니다. 마지막 줄을 개선하고 싶습니다.
$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
검사를 통과합니다 if ($ie) {...}
.
당신은 또한 할 수 있습니다
if ($ie) {
# Do Something if $ie is not null
}
특정 예에서는 확인을 전혀 수행하지 않아도됩니다 . New-Object
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) {
...
}
이 모든 답변이 강조하지 않는 것은 값을 $ 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에서 $ value가 $ 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"
}
나는 이것이 다시 Powershell의 힘을 보여주는 것 같아요!
Type-check with the -is operator returns false for any null value. In most cases, if not all, $value -is [System.Object] will be true for any possible non-null value. (In all cases, it will be false for any null-value.)
My value is nothing if not an object.
I had the same Problem. This solution works for me.
$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
$Word = new-object -ComObject word.application
}
Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:
COM object that has been separated from its underlying RCW cannot be used.
Then here's some code that worked for me:
function Count-RCW([__ComObject]$ComObj){
try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
catch{return 0}
return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}
example usage:
if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}
mashed together from other peoples' better answers:
- RCW & reference counting when using COM interop in C#
- RCW Reference Counting Rules != COM Reference Counting Rules
- “COM object that has been separated from its underlying RCW cannot be used” with .NET 4.0
and some other cool things to know:
- COM object that has been separated from its underlying RCW cannot be used
- Custom Marshaling
- Advanced COM Interoperability
참고URL : https://stackoverflow.com/questions/4430067/best-way-to-check-if-an-powershell-object-exist
'program tip' 카테고리의 다른 글
왼쪽 조인이있는 상위 1 (0) | 2020.09.24 |
---|---|
오류 : 매개 변수 1에 제공된 기본 인수 (0) | 2020.09.24 |
Python / postgres / psycopg2 : 방금 삽입 된 행의 ID 가져 오기 (0) | 2020.09.24 |
ASP.NET MVC 4 베타를 설치 한 후 InvalidCastException이 throw됩니다. (0) | 2020.09.24 |
Unix-한 디렉토리의 내용을 다른 디렉토리로 복사 (0) | 2020.09.24 |