powershell 不能对空值表达式调用方法

4nkexdtk  于 2023-05-22  发布在  Shell
关注(0)|答案(1)|浏览(208)

我只是想创建一个powershell脚本,它计算一个可执行文件(一个文件)的md5总和。
我的.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

是什么原因导致此错误?
我的空值表达式到底是什么?

参考文献:
How to get an MD5 checksum in PowerShell

ddrv8njm

ddrv8njm1#

这个问题的简单答案是你有一个未声明的(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, ...

$md5.ComputeHash().ComputeHash()是空值表达式。输入乱码也会产生同样的效果。

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-StrictMode关闭时,未初始化的变量(版本1)被假定为具有0(零)或$Null的值,具体取决于类型。对不存在的属性的引用将返回$Null,并且无效的函数语法的结果会因错误而异。不允许使用未命名的变量。

相关问题