3

我遇到了一个令人讨厌的问题,我想消除我在 Powershell 控制台和 ISE 中不需要的调试信息的位置。令人讨厌的是,它妨碍了我想要的调试信息。

我不清楚这是特定于我正在编写脚本的工具(WinSCP)还是更通用的 PowerShell 行为。

简而言之, WinSCP.Session.Open事件不会写出任何内容(好!),但是Close()andDispose()方法非常健谈,每次调用时都会在我的控制台中显示以下内容。

起初我认为这可能是在finally块中包含语句的结果,但是将它们移动到try块中会产生相同的令人讨厌的行为。

基于类似但不相同的问题,我检查了“偏好变量”。我的股票价值列在最后,我唯一尝试更改无济于事的是“警告偏好”到“默默地继续”,没有效果

运行示例:

PS F:\> getFirewallContents "AAA" 255.255.227.254
Attempting Session.Open  AAA  |  255.255.227.254
Completed  Session.Open  AAA  |  255.255.227.254
/var/db/commits exists, last write: 5/8/2015 11:33:22 AM
Closing Session  AAA

... two stanzas that follow are the undesired output ......    

MemberType          : Method
OverloadDefinitions : {System.Void Close()}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Void Close()
Name                : Close
IsInstance          : True

MemberType          : Method
OverloadDefinitions : {System.Void Dispose()}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Void Dispose()
Name                : Dispose
IsInstance          : True

Closed  Session  AAA

function getFirewallContents ([string] $fw_name, [string] $fw_ip) {
    $session = New-Object WinSCP.Session
    $sessionOptions = New-Object WinSCP.SessionOptions
    $xferOptions = New-Object WinSCP.TransferOptions

    $sessionOptions.HostName = $fw_ip
    $sessionOptions.UserName = "NOPE"
    $sessionOptions.Password = "NOT TELLING"
    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
    $sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = $TRUE

    $remotefile = "/var/db/commits"

    Try {
        Write-Host  "Attempting Session.Open " $fw_name " | " $sessionOptions.HostName 

        $session.Open($sessionOptions)

        Write-Host  "Completed  Session.Open " $fw_name " | " $sessionOptions.HostName      

        if ($session.FileExists($remotefile)) {
            Write-Host "$remotefile exists, last write:" $session.GetFileInfo($remotefile).LastWriteTime
        } else {
            Write-Host "$remotefile NOT FOUND"
        }
    } Catch {
        Write-Host "Something bad happened"
    } Finally {
        Write-Host "Closing Session  $fw_name "
        $session.Close
        $session.Dispose
        Write-Host "Closed  Session  $fw_name "
    }
}

Name                           Value
----                           -----
ConfirmPreference              High
DebugPreference                SilentlyContinue
ErrorActionPreference          Continue
ProgressPreference             Continue
VerbosePreference              SilentlyContinue
WarningPreference              Continue     (Tried Silently Continue, no effect)
WhatIfPreference               False
4

1 回答 1

3

您在调用.Close和时缺少括号.Dispose。所以你实际上根本没有调用方法,而是获取方法的地址而不使用它。作为最后的手段,PowerShell 在控制台上打印“表达式”结果。

正确的语法是:

$session.Close()
$session.Dispose()
于 2015-05-13T08:27:21.020 回答