Mar*_*tts 4 powershell powershell-dsc
我对PowerShell DSC相当新,对此的回答可能非常明显,但我找不到任何地方描述的类似问题.
我有一个PowerShell DSC复合资源,可以下载一些MSI并运行它们.下载文件的目录在几个地方被引用,所以我试图将它存储在一个变量中.但是,当我来应用使用此资源的配置时,Start-DscConfiguration值始终显示为null.
以下是资源的示例:
Configuration xExample {
Import-Module -ModuleName 'PSDesiredStateConfiguration'
$path = 'C:\Temp\Installer.msi'
Script Download {
SetScript = {
Invoke-WebRequest -Uri "..." -OutFile $path
}
GetScript = {
@{
Result = $(Test-Path $path)
}
}
TestScript = {
Write-Verbose "Testing $($path)"
Test-Path $path
}
}
}
Run Code Online (Sandbox Code Playgroud)
当执行此资源时,详细输出显示"Testing",并且Test-Path由于Path参数为null ,调用失败.
我已经尝试$path在配置之外声明变量并且使用$global无效.
我错过了什么?
DSC将脚本存储为已编译的mof文件中的字符串.标准变量不会扩展,因为它不知道要扩展哪个以及作为脚本的一部分保留哪个.
但是,您可以使用using-scope访问脚本外部的变量.在mof-compilation期间,定义变量的代码将添加到Test-/Set-/GetScript的每个scriptblock的开头.
如果需要在GetScript,TestScript或SetScript脚本块中使用配置脚本中的变量,请使用$ using:Scope
例:
Configuration xExample {
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
#Can also be set outside of Configuration-scriptblock
$path = 'C:\Temp\Installer2.msi'
Script Download {
SetScript = {
Invoke-WebRequest -Uri "..." -OutFile $using:path
}
GetScript = {
@{
Result = $(Test-Path "$using:path")
}
}
TestScript = {
Write-Verbose "Testing $using:path"
Test-Path "$using:path"
}
}
}
Run Code Online (Sandbox Code Playgroud)
localhost.mof(scriptresource-part):
instance of MSFT_ScriptResource as $MSFT_ScriptResource1ref
{
ResourceID = "[Script]Download";
GetScript = "$path ='C:\\Temp\\Installer2.msi'\n\n @{ \n Result = $(Test-Path \"$path\")\n }\n ";
TestScript = "$path ='C:\\Temp\\Installer2.msi'\n\n Write-Verbose \"Testing $path\"\n Test-Path \"$path\"\n ";
SourceInfo = "::7::3::Script";
SetScript = "$path ='C:\\Temp\\Installer2.msi'\n \n Invoke-WebRequest -Uri \"...\" -OutFile $path\n ";
ModuleName = "PSDesiredStateConfiguration";
ModuleVersion = "1.0";
ConfigurationName = "xExample";
};
Run Code Online (Sandbox Code Playgroud)
资料来源:MSDN
| 归档时间: |
|
| 查看次数: |
2309 次 |
| 最近记录: |