我有一个现有的Powershell脚本,它在PowerShell 5.1中没有问题。 安装 PowerShell 7 后,脚本不再工作,并且在尝试建立 WinSCP 会话时失败。
首先,会话选项是通过New-WinSCPSessionOption创建的,这些选项被存储到$sessionOption,没有问题。
$sessionOption = New-WinSCPSessionOption -HostName $hostName -Credential $credentials -Protocol Ftp
会话安装程序运行时,Powershell 7 中会引发异常:
$session = New-WinSCPSession -SessionOption $sessionOption
引发以下异常:
Line |
| $session = New-WinSCPSession -SessionOption $sessionOption
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling "Open" with "1" argument(s): "Method not found: 'Void
| System.Threading.EventWaitHandle..ctor(Boolean, System.Threading.EventResetMode, System.String,
| Boolean ByRef, System.Security.AccessControl.EventWaitHandleSecurity)'."
假设您仍然有可用的 PowerShell 5,并且您确实希望将 WinSCP(或其他不再起作用的 cmdlet(与 PowerShell 7 一起使用,那么只要您可以,或者准备以管理员身份运行代码,这是可能的。
在管理员提升的 shell 中,需要使用WinPSCompatSession
然后通过该会话发送命令。
$hostname = 'yourHostName'
$username = 'yourUsername'
$password = 'yourPassword'
$fingerprint = 'yourFingerprint'
$session = New-PSSession -Name WinPSCompatSession
Invoke-Command -Session $session -ScriptBlock {
Add-Type -Path "C:Program Files (x86)WinSCPWinSCPnet.dll"
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $using:hostname
UserName = $using:username
SecurePassword = $using:password
SshHostKeyFingerprint = $using:fingerprint
}
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)
}
# and so on...
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_windows_powershell_compatibility?view=powershell-7.3
如上所述,任何你想在脚本块中使用的存在于外部的变量都需要像$using:yourVariableName
一样调用,因为它们在不同的范围内。
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.3&viewFallbackFrom=powershell-7#scope-modifiers