将错误重定向到文件 [英] Redirect error to file
问题描述
我正在编写PowerShell脚本,它的其中一部分应将新用户添加到Active Directory。
我正在使用 New-ADUser
cmdlet,我想将任何错误(如果会产生任何错误)重定向到文件。
所以我写
I'm writing a PowerShell script and one of its parts should add a new user to Active Directory.
I'm using the New-ADUser
cmdlet and I want to redirect any errors (if it will produce any) to a file.
So I write
New-ADUser -smth -smth 2>> ./log.txt
但是它只会创建一个空白的 log.txt
文件,当我模拟错误时。
我怎么了?
But it creates only a blank log.txt
file when I simulate error.
What did I do wrong?
推荐答案
cmdlet本身引发的错误可以像您尝试的那样重定向:
Errors that are thrown by the cmdlet itself can be redirected like you tried:
New-Item -Type File C:\Windows\WinSxS\foo.txt 2>> error.log
环境抛出的错误(例如解析器错误)只能在运行时重定向嵌套上下文中的cmdlet,例如脚本块:
Errors thrown by the environment (parser errors for instance) can only be redirected if you run the cmdlet in a nested context, e.g. a scriptblock:
& { New-Item -Foo } 2>> error.log
这篇关于将错误重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!