cra*_*aig 10 powershell powershell-2.0
我希望Write-Verbose在脚本和函数中使用命令行开关.它在脚本(.ps1)文件中按预期工作,但在模块(.psm1)文件中不起作用 - 在模块中忽略命令行开关.
运行以下脚本:
PS> .\scaffold.ps1 -verbose
Run Code Online (Sandbox Code Playgroud)
生产:
VERBOSE: starting foo
path: c:\bar.txt
[missing entry here - 'verbose path: c:\bar.txt']
VERBOSE: ending foo
Run Code Online (Sandbox Code Playgroud)
scaffold.ps1:
[cmdletbinding()]
param()
import-module Common -force
write-verbose "starting foo"
foo "c:\bar.txt"
write-verbose "ending foo"
Run Code Online (Sandbox Code Playgroud)
Common.psm1:
function foo {
[cmdletbinding()]
Param(
[string]$path
)
write-host "path: $path"
write-verbose "verbose path: $path"
}
Run Code Online (Sandbox Code Playgroud)
此时我没有将清单(.psd1)与模块(.psm1)相关联.
是否需要使用特定于模块的语法?
**编辑**
我需要的是一种确定-verbose标志是否已在.PS1文件上设置的方法,以便我可以将其传递给.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"
Run Code Online (Sandbox Code Playgroud)
要从Write-Verbose模块中的cmdlet 获取输出,您需要使用-verbosecommon参数.请参阅http://technet.microsoft.com/en-us/magazine/ff677563.aspx
使用你的代码:
>import-module R:\Common.psm1
>foo "c:\users"
path: c:\users
>foo "c:\users" -verbose
path: c:\users
VERBOSE: verbose path: c:\users
Run Code Online (Sandbox Code Playgroud)
在这里找到答案:如何在自定义cmdlet中正确使用-verbose和-debug参数
scaffold.ps1:
[cmdletbinding()]
param()
import-module Common -force
write-verbose "starting foo"
foo "c:\bar.txt" -Verbose:($PSBoundParameters['Verbose'] -eq $true)
write-verbose "ending foo"
Run Code Online (Sandbox Code Playgroud)
小智 5
这里的问题是调用者范围内的变量不会被脚本模块中的代码获取。当您调用“.\scaffold.ps1 -verbose”时,$VerbosePreference 在 scaffold.ps1 的脚本范围内设置为“Continue”。如果您从该脚本调用已编译的 Cmdlet,它会遵循 $VerbosePreference 值,但是当您从脚本模块调用高级函数时,它们不会。
我最近编写了一个函数,允许您从调用方导入首选项变量,使用 $PSCmdlet 和 $ExecutionContext.SessionState 的组合来获取适当的变量范围。在脚本模块的导出函数的开头,对此命令的调用如下所示:
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Run Code Online (Sandbox Code Playgroud)
Get-CallerPreference 函数可以从http://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d下载
| 归档时间: |
|
| 查看次数: |
8023 次 |
| 最近记录: |