我正在尝试使用函数设置某些变量的值。我的代码如下:
$BackupFile = $null
$TaskSequenceID = $null
$OSDComputerName = $null
$capturedWimPath = $null
Function Set-OsToBuild
{
switch ($OsToBuild)
{
"Win7x64"
{
$BackupFile = "Win7x64-SP1.wim"
$TaskSequenceID = "WIN7X64BC"
$OSDComputerName = "Ref-Win7x64"
$capturedWimPath = "$($PathToMdtShare)\Captures\$BackupFile"
}
}
}
问题是$ BackupFile,$ TaskSequenceID,$ OSDComputerName和$ capturedWimPath的这些值在此函数之外为空/空。
正确的方法是什么?我想在此函数中设置这些值,并稍后在父范围的脚本中使用这些值。
变量在函数的local
-scope中创建。完成功能后,将删除这些变量。
Global: The scope that is in effect when Windows PowerShell starts. Variables and functions that are present when Windows PowerShell starts have been created in the global scope. This includes automatic variables and preference variables. This also includes the variables, aliases, and functions that are in your Windows PowerShell profiles. Local: The current scope. The local scope can be the global scope or any other scope. Script: The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope.
资料来源:about_Scopes
如果您需要变量可用于脚本,则将它们写入script
作用域。
$BackupFile = $null
$TaskSequenceID = $null
$OSDComputerName = $null
$capturedWimPath = $null
Function Set-OsToBuild
{
switch ($OsToBuild)
{
"Win7x64"
{
$script:BackupFile = "Win7x64-SP1.wim"
$script:TaskSequenceID = "WIN7X64BC"
$script:OSDComputerName = "Ref-Win7x64"
$script:capturedWimPath = "$($PathToMdtShare)\Captures\$BackupFile"
}
}
}
如果要保留整个会话的值(直到关闭powershell进程),则应使用global
范围。
$global:BackupFile = $null
$global:TaskSequenceID = $null
$global:OSDComputerName = $null
$global:capturedWimPath = $null
Function Set-OsToBuild
{
switch ($OsToBuild)
{
"Win7x64"
{
$global:BackupFile = "Win7x64-SP1.wim"
$global:TaskSequenceID = "WIN7X64BC"
$global:OSDComputerName = "Ref-Win7x64"
$global:capturedWimPath = "$($PathToMdtShare)\Captures\$BackupFile"
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句