我希望在脚本和函数中使用 Write-Verbose
命令行开关 . 它在脚本(.ps1)文件中按预期工作,但在模块(.psm1)文件中不起作用 - 在模块中忽略命令行开关 .
运行以下脚本:
PS> .\scaffold.ps1 -verbose
生产环境 :
VERBOSE: starting foo
path: c:\bar.txt
[missing entry here - 'verbose path: c:\bar.txt']
VERBOSE: ending foo
scaffold.ps1:
[cmdletbinding()]
param()
import-module Common -force
write-verbose "starting foo"
foo "c:\bar.txt"
write-verbose "ending foo"
Common.psm1:
function foo {
[cmdletbinding()]
Param(
[string]$path
)
write-host "path: $path"
write-verbose "verbose path: $path"
}
此时我没有将清单(.psd1)与模块(.psm1)相关联 .
是否需要使用特定于模块的语法?
编辑
我需要的是一种方法来确定是否已在.PS1文件上设置 -verbose
标志,以便我可以将其传递给.PSM1文件 .
scaffold.ps1:
[cmdletbinding()]
param()
import-module Common -force
write-verbose "starting foo"
foo "c:\bar.txt" $verbose_flag # pass verbose setting to module based on what was set on the script itself
write-verbose "ending foo"
3 回答
要从模块中的cmdlet获取
Write-Verbose
输出,需要使用-verbose
common参数 . 见http://technet.microsoft.com/en-us/magazine/ff677563.aspx使用你的代码:
在这里找到答案:How to properly use the -verbose and -debug parameters in custom cmdlet
scaffold.ps1:
这里的问题是调用者范围中的变量不会被脚本模块中的代码拾取 . 当您调用“ . \ scaffold.ps1 -verbose”时,$ verbosePreference在scaffold.ps1的脚本范围中设置为“Continue” . 如果从该脚本调用已编译的Cmdlet,它将遵循$ VerbosePreference值,但是当您从脚本模块调用高级函数时,它们不会 .
我最近编写了一个函数,允许您从调用者导入首选项变量,使用$ PSCmdlet和$ ExecutionContext.SessionState的组合来获取适当的变量作用域 . 在脚本模块的导出函数的开头,对此命令的调用如下所示:
Get-CallerPreference函数可以从http://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d下载