2012-09-13 159 views
1

我使用PS Remoting,Powershell 2.0。函數在PowerShell中返回布爾值

我需要調用返回布爾值($ true或$ false)的函數。

我的功能:

Function TryDisableClientForCredSSP() 
{ 
    try 
    { 
     WriteTrace "[TryDisableClientForCredSSP]. Disable-WSManCredSSP -Role Client " 
     $script=Convert-StringToScriptBlock("Disable-WSManCredSSP -Role Client ") 
     Caller($script) 

     WriteTrace "[TryDisableClientForCredSSP]. winrm get winrm/config/client/auth [($env:COMPUTERNAME)]" 
     $script=Convert-StringToScriptBlock("winrm get winrm/config/client/auth") 
     Caller($script); 

     return $true; 
    } 
    catch 
    { 
     Write-Verbose "[TryDisableClientForCredSSP] Error " 
     Write-Verbose $_ 
     Write-Host $_.Exception.Message`r`n 
     return $false; 
    } 
} 

注:WRITETRACE功能僅僅只能做寫主機。

我使用它:

$ok = TryDisableClientForCredSSP; 
    WriteTrace "[TryDisableClientForCredSSP]. $ok" 
    if ($ok -eq $true) 
    { 
     WriteTrace "[TryDisableClientForCredSSP]. OK true" 
    } 
    else 
    { 
     WriteTrace "[TryDisableClientForCredSSP]. KO false" 
    } 

我得到這樣的輸出:

[TryDisableClientForCredSSP]. Auth  Basic = true  Digest = true  Kerberos = true  Negotiate = true  Certificate = true  CredSSP = false True 
[TryDisableClientForCredSSP]. OK true 

我想這條線輸出 「[TryDisableClientForCredSSP]真。」

WriteTrace "[TryDisableClientForCredSSP]. $ok" 

有什麼建議?

回答

6

函數返回無論每個命令吐出到輸出流。嘗試刪除像這樣的輸出:

[void]WriteTrace "[TryDisableClientForCredSSP]. Disable-WSManCredSSP -Role Client " 
    $script=Convert-StringToScriptBlock("Disable-WSManCredSSP -Role Client ") 
    [void]Caller($script) 

    [void]WriteTrace "[TryDisableClientForCredSSP]. winrm get winrm/config/client/auth [($env:COMPUTERNAME)]" 
    $script=Convert-StringToScriptBlock("winrm get winrm/config/client/auth") 
    [void]Caller($script); 

    return $true; 
+0

如果您不喜歡使用[void],則可以添加'| out-null「來代替這些行。 –

+0

是不是有一個更簡單的方法來停止輸出,比如在命令後面使用分號? – Neolisk

+2

有三種方式:[void] ...,... | Out-Null和...> $ null。而已。 –