0

以下が発生する理由を知っている人はいますか?また、回避策はありますか?

mklink コマンド出力をキャプチャするのに苦労しています (cmd.exe mklink > out.txt 経由)

mklink コマンドが成功した場合、出力は out.txt に正常に送信されます

例えば:%comspec% /c mklink /d C:\Test C:\Windows > out.txt && notepad out.txt

ただし、コマンドが無効または失敗した場合、out.txt には何も書き込まれません。

EG: Run above command again(C:\Test が既に存在するため失敗) または

例えば:%comspec% /c mklink > out.txt && notepad out.txt

私は VBScript でコマンドを使用しています。コマンドが正常に完了しなかった場合に mklink の出力をキャプチャする方法を知っている人はいますか?

Set o_shell = CreateObject("Wscript.Shell")
Set o_fso = CreateObject("Scripting.FileSystemObject")
mklinkCommandOutput = GetCommandOutput("mklink /D ""C:\Test"" ""C:\Windows""")
WScript.echo mklinkCommandOutput

Function GetCommandOutput(runCmd)
  on error resume next
  Dim o_file, tempFile: tempFile = o_shell.ExpandEnvironmentStrings("%TEMP%") & "\tmpcmd.txt"

  ' Run command and write output to temp file
  o_shell.Run "%COMSPEC% /c " & runCmd & " > """ & tempFile & """", 0, 1

  ' Read command output from temp file
  Set o_file = o_fso.OpenTextFile(tempFile, 1)
  GetCommandOutput = o_file.ReadAll
  o_file.Close

  ' Delete temp file
  Set o_file = o_fso.GetFile(tempFile)
  o_file.Delete
End Function
4

2 に答える 2

1

run コマンドではなく、「Exec」コマンドを活用して出力結果を収集することを検討しましたか?

ファイルを必要とせず、簡単です。

新しいコード

Function GetCommandOutput(runCmd)
  Dim WshShell, oExec
  Set WshShell = CreateObject("WScript.Shell")
  Set oExec    = WshShell.Exec("%COMSPEC% /c " & runCmd)
  GetCommandOutput = oExec.StdOut.ReadAll
End Function 

古いコード

Function GetCommandOutput(runCmd)
  on error resume next
  Dim o_file, tempFile: tempFile = o_shell.ExpandEnvironmentStrings("%TEMP%") & "\tmpcmd.txt"

  ' Run command and write output to temp file
  o_shell.Run "%COMSPEC% /c " & runCmd & " > """ & tempFile & """", 0, 1

  ' Read command output from temp file
  Set o_file = o_fso.OpenTextFile(tempFile, 1)
  GetCommandOutput = o_file.ReadAll
  o_file.Close

  ' Delete temp file
  Set o_file = o_fso.GetFile(tempFile)
  o_file.Delete
End Function 
于 2014-03-25T16:44:32.253 に答える
1

(1) Using multiple commands and conditional processing symbolsによると、シンボル&&は、左側のコマンドが成功した場合にのみ、右側のコマンドを実行します。& が失敗した場合でも、メモ帳を起動するために使用する必要がありmlinkます。

(2) mlink のドキュメントでは明示的には述べていませんが、mlinkがそのエラー メッセージを Stderr に書き込むと仮定します (こちらを参照) dir

証拠:

dir 01.vbs
...
19.10.2012  11:29             2.588 01.vbs
...
(dir succeeded)

dir nix
...
File Not Found
(dir failed)

dir nix && echo nothing to see, because lefty failed
...
File Not Found
(dir failed, no output because of &&)

dir nix & echo much to see, although lefty failed
...
File Not Found
much to see, although lefty failed
(dir succeeded, echo done because of &)

(3)失敗したかどうかに関係なくmlink(rsp。 )の出力をキャプチャし、結果(ファイル)をメモ帳に表示するには、次を使用する必要がありますdir

dir 01.vbs 1> out.txt 2>&1 & notepad out.txt
dir nix 1> out.txt 2>&1 & notepad out.txt

StdoutとStderr を出力ファイルにリダイレクトします。

証拠:

Dos & メモ帳

于 2014-03-25T18:26:12.287 に答える