programing

null 값 식에서 메서드를 호출할 수 없습니다.

starjava 2023. 8. 20. 10:10
반응형

null 값 식에서 메서드를 호출할 수 없습니다.

실행 파일(파일)의 md5 합계를 계산하는 powershell 스크립트를 만들려고 합니다.

나의.ps1스크립트:

$answer = Read-Host "File name and extension (ie; file.exe)"
$someFilePath = "C:\Users\xxx\Downloads\$answer"

If (Test-Path $someFilePath){
    $stream = [System.IO.File]::Open("$someFilePath",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
    $hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
    $hash
    $stream.Close()
} Else {
    Write-Host "Sorry, file $answer doesn't seem to exist."
}

스크립트를 실행할 때 다음 오류가 표시됩니다.

You cannot call a method on a null-valued expression.
At C:\Users\xxx\Downloads\md5sum.ps1:6 char:29
+                             $hash = [System.BitConverter]::ToString($md5.Compute ...
+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

제가 알기로는 이 오류는 스크립트가 어떤 작업을 시도하고 있지만 스크립트의 다른 부분에는 스크립트의 첫 번째 부분이 제대로 작동할 수 있는 정보가 없습니다.이 경우에는,$hash.

Get-ExecutionPolicy산출물Unrestricted.

이 오류의 원인은 무엇입니까?
저의 null 값 표현식은 정확히 무엇입니까?


참조:

PowerShell에서 MD5 체크섬을 가져오는 방법

이에 대한 간단한 대답은 선언되지 않은(null) 변수가 있다는 것입니다.이 경우에는 그렇습니다.$md5당신이 말한 코멘트에서 이것은 당신의 코드의 다른 곳에서 선언되어야 했습니다.

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

존재하지 않는 메서드를 실행하려고 하기 때문에 오류가 발생했습니다.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

.ComputeHash()$md5.ComputeHash()null 값 식이었습니다.횡설수설로 타이핑해도 동일한 효과가 발생합니다.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

기본적으로 PowerShell은 StrictMode에 정의된 대로 이 작업을 수행할 수 있습니다.

Set-Strict Mode가 해제된 경우 초기화되지 않은 변수(버전 1)의 값은 유형에 따라 0 또는 $Null로 가정됩니다.존재하지 않는 속성에 대한 참조는 $Null을 반환하며, 유효하지 않은 함수 구문의 결과는 오류에 따라 달라집니다.명명되지 않은 변수는 허용되지 않습니다.

언급URL : https://stackoverflow.com/questions/27525170/you-cannot-call-a-method-on-a-null-valued-expression

반응형