简体   繁体   English

在日志文件中打印行号

[英]Print in a log file the line number

I'm trying to manage some non-standard error in my functions (like a wrong input text), and I want to track those errors by writing a sort of log in a variable. 我试图在我的函数中管理一些非标准错误(比如错误的输入文本),我想通过在变量中写入一种日志来跟踪这些错误。 I'm trying to write also the line number, and this is my code 我正在尝试写行号,这是我的代码

$someVar = "line $($MyInvocation.ScriptLineNumber): at least 2 arguments needed, function has been called with only $args.Count arguments"

Sometimes it returns the correct number and sometimes it doesn't. 有时它会返回正确的数字,有时则不会。 Is this the correct way? 这是正确的方法吗? Is there another method? 还有另一种方法吗?

EDIT: I found that this problem could be related to an unconventional way to execute scripts that I use in order to bypass a permission problem on a specific the machine. 编辑:我发现这个问题可能与执行脚本的非常规方式有关,我使用这些脚本来绕过特定机器上的权限问题。 I'll post a more detailed example as soon as I can 我会尽快发布一个更详细的例子

Any reason why you're not using param in your functions and making them mandatory? 你有没有在你的职能中使用param并强制执行它们的原因?

Function A()
{
   Param
   (
      [Parameter(Mandatory=$true)][String]$Arg1,
      [Parameter(Mandatory=$true)][String]$Arg2
   )
   Write-Host "$Arg1 $Arg2"
}

If you run this function without any arguments then it will throw an error asking for the mandatory arguments. 如果你运行这个函数没有任何参数,那么它将抛出一个错误,要求强制参数。

try wrapping in $(). 尝试换入$()。 For example: 例如:

$someVar = "line $($MyInvocation.ScriptLineNumber): at least 2 arguments needed, function has been called with only $($args.Count) arguments"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM