2017-12-27 3 views
1

프로그래밍 방식으로 수동으로 실행될 때 동일한 명령에서 두 개의 다른 출력이 발생하며 그 이유를 이해할 수 없습니다. powershell -Command "Get-Module -ListAvailable" 명령 프롬프트에서 수동으로 실행수동 및 프로그램 실행간에 PowerShell 출력이 달라집니다.

(자바를 통해) 프로그램 실행하면

질문 ::의 명령, 나는이 출력 ::

U:\>powershell -Command "Get-Module -ListAvailable" 

Directory: C:\Program Files\WindowsPowerShell\Modules 

ModuleType Version Name        ExportedCommands 
---------- ------- ----        ---------------- 
Binary  1.0.0.1 PackageManagement     {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource...} 
Script  1.0.0.1 PowerShellGet      {Install-Module, Find-Module, Save-Module, Update-Module...} 
Binary  6.5.1.6... VMware.DeployAutomation    {Add-DeployRule, Add-ProxyServer, Add-ScriptBundle, Copy-DeployRule...} 
Binary  6.5.1.6... VMware.ImageBuilder     {Add-EsxSoftwareDepot, Add-EsxSoftwarePackage, Compare-EsxImageProfile, Export-EsxImageProfile...} 
Manifest 6.5.4.7... VMware.PowerCLI 
Binary  6.5.4.6... VMware.VimAutomation.Cis.Core  {Connect-CisServer, Disconnect-CisServer, Get-CisService} 
Binary  6.5.1.5... VMware.VimAutomation.Cloud   {Add-CIDatastore, Connect-CIServer, Disconnect-CIServer, Get-Catalog...} 
Manifest 6.5.4.6... VMware.VimAutomation.Common 
Binary  6.5.2.6... VMware.VimAutomation.Core   {Add-PassthroughDevice, Add-VirtualSwitchPhysicalNetworkAdapter, Add-VMHost, Add-VMHostNtpServer...} 
Binary  6.5.4.7... VMware.VimAutomation.HA    Get-DrmInfo 
Binary  7.1.0.5... VMware.VimAutomation.HorizonView {Connect-HVServer, Disconnect-HVServer} 
Binary  6.5.1.5... VMware.VimAutomation.License  Get-LicenseDataManager 
Binary  2.0.0.6... VMware.VimAutomation.Nsxt   {Connect-NsxtServer, Disconnect-NsxtServer, Get-NsxtService} 
Binary  6.5.1.5... VMware.VimAutomation.PCloud   {Connect-PIServer, Disconnect-PIServer, Get-PIComputeInstance, Get-PIDatacenter} 
Manifest 1.0.0.5... VMware.VimAutomation.Sdk   {Get-PSVersion, Get-InstallPath} 
Binary  6.5.1.5... VMware.VimAutomation.Srm   {Connect-SrmServer, Disconnect-SrmServer} 
Binary  6.5.4.7... VMware.VimAutomation.Storage  {Add-KeyManagementServer, Copy-VDisk, Export-SpbmStoragePolicy, Get-KeyManagementServer...} 
Script  1.1  VMware.VimAutomation.StorageUtility Update-VmfsDatastore 
Binary  6.5.1.5... VMware.VimAutomation.Vds   {Add-VDSwitchPhysicalNetworkAdapter, Add-VDSwitchVMHost, Export-VDPortGroup, Export-VDSwitch...} 
Binary  6.5.4.7... VMware.VimAutomation.Vmc   {Connect-Vmc, Disconnect-Vmc, Get-VmcService, Connect-VmcServer...} 
Binary  6.5.1.5... VMware.VimAutomation.vROps   {Connect-OMServer, Disconnect-OMServer, Get-OMAlert, Get-OMAlertDefinition...} 
Binary  6.5.1.5... VMware.VumAutomation    {Add-EntityBaseline, Copy-Patch, Get-Baseline, Get-Compliance...} 

Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules 

ModuleType Version Name        ExportedCommands 
---------- ------- ----        ---------------- 
Manifest 1.0.0.0 AppLocker       {Set-AppLockerPolicy, Get-AppLockerPolicy, Test-AppLockerPolicy, Get-AppLockerFileInformation...} 
Manifest 1.0.0.0 BitsTransfer      {Add-BitsFile, Remove-BitsTransfer, Complete-BitsTransfer, Get-BitsTransfer...} 
Manifest 1.0.0.0 CimCmdlets       {Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance, Get-CimSession...} 
Script  1.0.0.0 ISE         {New-IseSnippet, Import-IseSnippet, Get-IseSnippet} 
Manifest 1.0.0.0 Microsoft.PowerShell.Archive  {Compress-Archive, Expand-Archive} 
Manifest 3.0.0.0 Microsoft.PowerShell.Diagnostics {Get-WinEvent, Get-Counter, Import-Counter, Export-Counter...} 
Manifest 3.0.0.0 Microsoft.PowerShell.Host   {Start-Transcript, Stop-Transcript} 
Manifest 3.1.0.0 Microsoft.PowerShell.Management  {Add-Content, Clear-Content, Clear-ItemProperty, Join-Path...} 
Script  1.0  Microsoft.PowerShell.ODataUtils  Export-ODataEndpointProxy 
Manifest 3.0.0.0 Microsoft.PowerShell.Security  {Get-Acl, Set-Acl, Get-PfxCertificate, Get-Credential...} 
Manifest 3.1.0.0 Microsoft.PowerShell.Utility  {Format-List, Format-Custom, Format-Table, Format-Wide...} 
Manifest 3.0.0.0 Microsoft.WSMan.Management   {Disable-WSManCredSSP, Enable-WSManCredSSP, Get-WSManCredSSP, Set-WSManQuickConfig...} 
Manifest 1.0.0.0 NetworkSwitchManager    {Disable-NetworkSwitchEthernetPort, Enable-NetworkSwitchEthernetPort, Get-NetworkSwitchEthernetPort, Remove-NetworkSwitchEthernetPortIPAddress...} 
Manifest 1.1  PSDesiredStateConfiguration   {Set-DscLocalConfigurationManager, Start-DscConfiguration, Test-DscConfiguration, Publish-DscConfiguration...} 
Script  1.0.0.0 PSDiagnostics      {Disable-PSTrace, Disable-PSWSManCombinedTrace, Disable-WSManTrace, Enable-PSTrace...} 
Binary  1.1.0.0 PSScheduledJob      {New-JobTrigger, Add-JobTrigger, Remove-JobTrigger, Get-JobTrigger...} 
Manifest 2.0.0.0 PSWorkflow       {New-PSWorkflowExecutionOption, New-PSWorkflowSession, nwsn} 
Manifest 1.0.0.0 PSWorkflowUtility     Invoke-AsWorkflow 
Manifest 1.0.0.0 TroubleshootingPack     {Get-TroubleshootingPack, Invoke-TroubleshootingPack} 

Directory: C:\opscode\chefdk\modules 

ModuleType Version Name        ExportedCommands 
---------- ------- ----        ---------------- 
Script  0.0  chef        {chef-apply, chef-client, chef-service-manager, chef-shell...} 

를 얻을,이 출력을 얻을 ::

ModuleType Name      ExportedCommands               
---------- ----      ----------------               
Binary  PackageManagement   {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource...}  
Script  PowerShellGet    {Install-Module, Find-Module, Save-Module, Update-Module...} 
Manifest BitsTransfer    {Add-BitsFile, Remove-BitsTransfer, Complete-BitsTransfer, Get-BitsTrans... 
Manifest CimCmdlets    {Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance, Get-CimSessio... 
Script  ISE      {New-IseSnippet, Import-IseSnippet, Get-IseSnippet}       
Manifest Microsoft.PowerShell.A... {Compress-Archive, Expand-Archive}           
Manifest Microsoft.PowerShell.D... {Get-WinEvent, Get-Counter, Import-Counter, Export-Counter...}    
Manifest Microsoft.PowerShell.Host {Start-Transcript, Stop-Transcript}           
Manifest Microsoft.PowerShell.M... {Add-Content, Clear-Content, Clear-ItemProperty, Join-Path...}    
Script  Microsoft.PowerShell.O... Export-ODataEndpointProxy             
Manifest Microsoft.PowerShell.S... {Get-Acl, Set-Acl, Get-PfxCertificate, Get-Credential...}     
Manifest Microsoft.PowerShell.U... {Format-List, Format-Custom, Format-Table, Format-Wide...}     
Manifest Microsoft.WSMan.Manage... {Disable-WSManCredSSP, Enable-WSManCredSSP, Get-WSManCredSSP, Set-WSManQ... 
Manifest PSDesiredStateConfigur... {Set-DscLocalConfigurationManager, Start-DscConfiguration, Test-DscConfi... 
Manifest PSDiagnostics    {Start-Trace, Stop-Trace, Enable-WSManTrace, Disable-WSManTrace...}   
Binary  PSScheduledJob   {New-JobTrigger, Add-JobTrigger, Remove-JobTrigger, Get-JobTrigger...}  
Manifest TroubleshootingPack  {Get-TroubleshootingPack, Invoke-TroubleshootingPack}      
Script  chef      {chef-apply, chef-client, chef-service-manager, chef-shell...}    

프로그래밍 방식 실행 결과 s "버전" 열이 누락되어 있으며 사용 가능한 모듈의 하위 집합입니다.

필자는 어떻게 든 두 개의 다른 PowerShell 실행 파일을 호출 할 것이라고 생각하여 수동으로 프로그래밍 방식으로 powershell -Command "$PSVersionTable"을 실행했습니다.

powershell -Command "$PSVersionTable"을 수동으로 실행 ::

Name       Value 
----       ----- 
PSVersion      5.0.10586.117 
PSCompatibleVersions   {1.0, 2.0, 3.0, 4.0...} 
BuildVersion     10.0.10586.117 
CLRVersion      4.0.30319.18444 
WSManStackVersion    3.0 
PSRemotingProtocolVersion  2.3 
SerializationVersion   1.1.0.1 

powershell -Command "$PSVersionTable"의 프로그램 실행 ::

Name       Value                                         
----       -----                                         
PSVersion      5.0.10586.117                                       
PSCompatibleVersions   {1.0, 2.0, 3.0, 4.0...}                                     
BuildVersion     10.0.10586.117                                       
CLRVersion      4.0.30319.18444                                       
WSManStackVersion    3.0                                          
PSRemotingProtocolVersion  2.3                                          
SerializationVersion   1.1.0.1 

그래서 나는 내가 실행 해요 생각의 출력에서 ​​출력 동일한 PowerShell 실행 파일.

아무도 동일한 명령을 실행할 때 2 개의 완전히 다른 출력을 얻는 이유에 대한 아이디어가 있습니까?

업데이트 : @EBGreen의 요청에 따라 프로그래밍 방식으로 명령을 실행하는 데 사용되는 실제 Java 코드가 포함됩니다.

public class Example { 

    private void myMethod(String command) throws IOException { 
     Process process = Runtime.getRuntime().exec(command); 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); 

     String output = ""; 
     String line; 
     while((line = bufferedReader.readLine()) != null){ 
      output += (line + "\n"); 
     } 

     System.out.println((output.isEmpty() ? "No output was received!!!" : output)); 


     BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); 
     String errorOutput = ""; 
     while((line = errorBufferedReader.readLine()) != null){ 
      errorOutput += (line + "\n"); 
     } 

     System.out.println((errorOutput.isEmpty() ? "Nothing in the error output stream." : errorOutput)); 
    } 


    public static void main(String[] args) throws IOException { 
     new Example().myMethod("powershell -Command \"Get-Module -ListAvailable\""); 
    } 

} 
+0

프로그램을 실행할 때 사용하는 실제 코드 무엇입니까. 명령이 동일한 사용자 컨텍스트에서 실행되고 있습니까? 하나는 64 비트이고 다른 하나는 32 비트입니까? – EBGreen

+0

@EBGreen 코드가 포함 된 초 단위로 질문에 대한 업데이트를 게시하겠습니다. – Chiefwarpaint

+0

@EBGreen 코드가 이제 게시물에 포함됩니다. 프로그래밍 방식의 실행은 IntelliJ의 32 비트 JDK를 통해 수행됩니다. 수동 실행은 cmd 프롬프트 ('C : \ Windows \ system32 \ cmd.exe')를 통해 수행됩니다. 호스트 OS는 64 비트 Win 7입니다. – Chiefwarpaint

답변

0

저는 이것이 내 문제의 진정한 원인이라고 확신합니다. 내가 수동으로 사용 가능한 모듈의 목록을 확인하기 위해 명령을 실행되었을 때

, 나는 파워 쉘의 64 비트 인스턴스를 사용했다.

내 자바 프로그램은 32 비트 환경 (32 비트 JDK에 내장 된)에서 실행되었다. 내 프로그램이 cmd 프롬프트를 불러 오면 32 비트 cmd 프롬프트가 나타납니다. cmd 프롬프트에서 Powershell을 호출하면 32 비트 Powershell을 얻게됩니다. PowerShell의 32 비트 및 64 비트 버전에는 모듈을 저장하는 고유 한 설치 경로가 있습니다. 내가 수동으로 모듈을 설치할 때

그래서, 난 항상 64 비트 PowerShell을 사용했다. 필자는 수동으로 32 비트 Powershell을 열지 않았으며 모든 모듈을 설치하지 않았습니다. 그래서 Get-Module -ListAvailable의 프로그래밍 방식 출력이 너무 작아서 같은 명령을 수동으로 실행했을 때와 비교했을 때 그 결과가 작았습니다. 나에게 무슨 일이 있었는지 확인 도움이 단서로 날을 제공하는 @BaconBits에

감사합니다. 그 끝은 내 PowerShell을 실제로 실행 된 어떤 OS 아키텍처 컨텍스트 확인하기 위해 [Environment]::Is64BitProcess을 실행하는 것이 었습니다.

1

내 생각 엔 자바에서 프로그램 PowerShell을 호출 할 때 그냥 출력 포맷되지 않거나 다른 버전이 어떤 이유로 다른 기본 형식 구성을 가지고있다.

첫째, 몇 가지 배경 : 명령 줄에서 PowerShell을 실행 얻을

출력은 형식 파일의 형식에 의해 결정됩니다. 이들은 모두 $PSHome\*.format.ps1xml에 저장됩니다. Get-ModuleSystem.Management.Automation.PSModuleInfo 유형의 개체를 반환합니다. Select-String -Pattern 'PSModuleInfo' -Path "$PSHome\*.format.ps1xml"을 실행하면 기본 형식이 지정된 위치를 찾을 수 있습니다. Format-Table에 대해 Table이 표시되며, 이는 일반적으로 기본값입니다. Format-Wide의 경우 Wide이고 Format-List의 경우 List이 있습니다. Get-Help about_Format.ps1xml에서 콘솔 출력 형식에 대해 자세히 알아볼 수 있습니다.

PSModuleInfo의 기본 출력이 표 서식을 사용하는 것이기 때문에, 당신이 호출하여 자바 일치 PowerShell을 만들 수 있어야 : 아마도

new Example().myMethod("powershell -Command \"Get-Module -ListAvailable | Format-Table\""); 

또는 :

new Example().myMethod("powershell -Command \"Get-Module -ListAvailable | Format-Table | Out-String\""); 

또는 어쩌면을 그냥 :

new Example().myMethod("powershell -Command \"Get-Module -ListAvailable | Out-String\""); 

어떤 Java가 다른 작업을하는지 또는 n 비슷하게 서식을 지정하는 것은 잘 모르겠다. 또한 Get-Module -ListAvailable | ConvertTo-Json -Compress -Depth 1 또는 Get-Module -ListAvailable | ConvertTo-Xml -NoTypeInformation -As String -Depth 1 또는 당신이 당신의 출력을 직렬화 할 경우 비슷한 성공을 가질 수있다

new Example().myMethod("powershell -Command \"Get-Module -ListAvailable | Out-String\""); 

:

또한 항상 뭔가를 할 수 있습니다. 그냥 ConvertTo-Json의 기본 깊이가 2 명심, ConvertTo-Xml의 기본 깊이는 1이고, 깊이 3보다 그 아무것도 정말 느린 될 것입니다.

+0

Thx 도움 및 제안을위한 톤, 나는 그들이 편리하게 올 것이라고 확신합니다. 그러나 실제 문제는 다음과 같은 이유 때문에 확실합니다. 수동으로'powershell -Command "Get-Module -ListAvailable"'을 실행할 때 64 비트 명령을 통해 실행했습니다. 신속한. 어느 차례로 64 비트 PowerShell을 호출했는지. 프로그래밍 방식으로 동일한 명령을 실행하면 Java는 32 비트 명령 프롬프트를 사용하고있었습니다. PowerShell은 32 비트 PowerShell을 호출합니다. 32 비트 및 64 비트는 모듈에 대한 설치 경로가 다르므로 diff 출력 값을 얻는 이유입니다. – Chiefwarpaint