这是可能的,如about_script_blocks中所述:
与函数一样,脚本块可以包含 DynamicParam、Begin、
处理和结束关键字。有关详细信息,请参阅 about_Functions
和 about_Functions_Advanced。
为了测试这一点,我修改了你的脚本块并运行了这个:
$startStopService = {
Param(
# a bool needs $true or $false passed AFAIK
# A switch is $true if specified, $false if not included
[switch] $startService
)
Begin {
$oldPreference = $VerbosePreference
Write-Output "Setting VerbosePreference to Continue"
# $Using:VerbosePreference gave me an error
$VerbosePreference = "Continue"
}
Process {
if ($startService){
Write-Verbose "Service was started"
}
else {
Write-Verbose "Service was not started"
}
}
End {
# Restore the old preference
Write-Output "Setting VerbosePreference back to $oldPreference"
$VerbosePreference = $oldPreference
}
}
Write-Verbose "This message will not print if VerbosePreference is the default SilentlyContinue"
. $startStopService -startService
Write-Verbose "This message will not print if VerbosePreference is the default SilentlyContinue"
您追求什么功能?如果您想在运行脚本块时打印详细消息但不更改脚本其余部分中的$VerbosePreference,请考虑使用[CmdletBinding()] 和-Verbose 标志:
$startStopService = {
[CmdLetBinding()]
Param(
[switch] $startService
)
Write-Verbose "This is a verbose message"
}
Write-Verbose "This message will not print if VerbosePreference is the default SilentlyContinue"
. $startStopService -verbose
Write-Verbose "This message will not print if VerbosePreference is the default SilentlyContinue"
编辑 - 调用命令
在您发表评论后,我正在研究Invoke-Command 的功能。并且发现很多东西都不行。
我认为对您最有用的简短版本:您可以在脚本块中声明$VerbosePreference = "Continue",这将仅限于脚本块的范围。以后不用改回来了。
$startStopService = {
[CmdLetBinding()]
Param(
[parameter(Position=0)]
[switch]$startStopService,
[parameter(Position=1)]
[switch]$Verbose
)
if($Verbose){
$VerbosePreference = "Continue"
}
Write-Verbose "This is a verbose message"
}
Write-output "VerbosePreference: $VerbosePreference"
Write-Verbose "This message will not print if VerbosePreference is the default SilentlyContinue"
Invoke-Command -Scriptblock $startStopService -ArgumentList ($true,$true)
Write-output "VerbosePreference: $VerbosePreference"
Write-Verbose "This message will not print if VerbosePreference is the default SilentlyContinue"
试图将-Verbose 开关CommonParameter 传递给Invoke-Command 是不行的。这使用标准的Verbose 开关参数,允许您传递$true/$false(或省略)来控制详细输出。
相关:
about_Functions
about_Functions_Advanced