Powershell功能在首次调用时不起作用

时间:2019-01-25 18:31:47

标签: powershell

我正在使用一个相当简单的powershell脚本在我的主要脚本中包含一组支持脚本。

无论何时不存在文件,我都会在终端上显示一条通知,效果很好。我也想将通知写到我的日志文件中。

所以我写了一个简单的函数来创建时间戳:

function psa_get_timestamp {
    return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date);
}

该功能正常工作,但不是我第一次调用它。

# Set logfile
$logfile = join-path -path $PSScriptRoot -childpath "ps-admin_log.txt";

# Create array of needed files
$supporting_files = @(
    '/resources/requirements/environment.ps1',
    '/resources/loggers/logger.ps1',
    '/resources/menus/menus.ps1',
    '/resources/views/headers.ps1'
    );

# Include supporting files, throw non-fatal error if fails
foreach($support_file in $supporting_files) {

  $file = join-path -path $PSScriptRoot -childpath $support_file;

    if(Test-Path $file) {
    . $file;
    Write-Output "$(psa_get_timestamp) Successfully included file: $file" | Out-file $logfile -append
    } else {
    # Throw non-fatal error in terminal and write it to logfile
    Write-Host "! Notice: Could not include supporting file: $file" -ForegroundColor Yellow;
    Write-Output "$(psa_get_timestamp) ! Notice: Could not include supporting file: $file" | Out-file $logfile -append
    }
}

我的日志文件如下所示(注意第一行缺少时间戳):

��  S u c c e s s f u l l y   i n c l u d e d   f i l e :   <file_name>
 [ 0 1 / 2 5 / 1 9   1 9 : 2 1 : 3 1 ]   S u c c e s s f u l l y   i n c l u d e d   f i l e :    <file_name>
 [ 0 1 / 2 5 / 1 9   1 9 : 2 1 : 3 1 ]   S u c c e s s f u l l y   i n c l u d e d   f i l e :    <file_name>
 [ 0 1 / 2 5 / 1 9   1 9 : 2 1 : 3 1 ]   S u c c e s s f u l l y   i n c l u d e d   f i l e :    <file_name>

为什么我的功能在第一次通话时不起作用?

这是第一次通话时出现的错误:

psa_get_timestamp : The term 'psa_get_timestamp' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At <scriptlocation>:19 char:21
+     Write-Output "$(psa_get_timestamp) Successfully included file: $f ...
+                     ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (psa_get_timestamp:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

使用-Verbose时:

VERBOSE: Performing the operation "Output to File" on target
"<logfile_location>".
VERBOSE: Performing the operation "Output to File" on target
"<logfile_location>".
VERBOSE: Performing the operation "Output to File" on target
"<logfile_location>".
VERBOSE: Performing the operation "Output to File" on target
"<logfile_location>".

1 个答案:

答案 0 :(得分:1)

“仅在第一次运行后 起作用”的一种方式是,在第一次调用之前未定义所讨论的项目。例如当您在第3行调用一个函数,但直到第33行才定义它... [ grin ]

PoSh从脚本的开始运行到脚本的结尾,并且根本不知道所引用的功能是否存在,更不用说能够运行代码了。

通常的解决方法是确保定义在第一次使用之前。这就是脚本/编码指南倾向于建议将所有初始化项(包括函数定义)放在脚本顶部的原因。