将错误重定向到文件 [英] Redirect error to file

查看:104
本文介绍了将错误重定向到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆