我有一个讨厌的问题我想消除我在Powershell控制台和ISE中没有要求调试信息的位置。它妨碍了我想要的调试信息。
我不清楚这是特定于我正在编写脚本的工具(WinSCP),还是更通用的PowerShell行为。
简而言之,WinSCP.Session.Open
事件不会写出任何内容(好!),但Close()
和Dispose()
方法非常繁琐,下面的内容出现在每次调用我的控制台。
起初我认为这可能是将语句包含在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
答案 0 :(得分:2)
您在调用.Close
和.Dispose
时缺少括号。所以你实际上根本没有调用方法,而是采用方法的地址而不是使用它。 PowerShell打印"表达式"作为最后的手段在控制台上的结果。
正确的语法是:
$session.Close()
$session.Dispose()