PowerShell command prompt

Solve PowerShell Dependency Within Function Problems

Q: I have a PowerShell file with a Desired State Configuration that relies on a module that I copy earlier in the script. When I try to run the file, I receive an error message saying the module isn't found. What should I do?

A: Typically, when a PowerShell script is executed, any functions found in the script are executed, and then the actual logic of the script executed. This might be a problem if you have Desired State Configurations (DSCs) that rely on modules that might not have been copied to the local machine but will cause the DSC to fail validation and the entire script to therefore also fail.

The best way to solve this problem is to place the DSC in a separate file and then call that file at the right place in the script, after any kind of modules are copied to the machine.

If you don't want to take this approach, you can place the DSC in a "here string," which means placing the configuration in a variable and then executing that variable via Invoke-Expression at the desired place in the script. The problem with this approach is that any quote, double quote, or reserved character in the DSC will need to be escaped via the ` character, which is painful. The following is an example of this approach:

[email protected]"
Configuration SavillTechWebsite 
        # Target nodes to apply the configuration 
        [string[]]`$NodeName = `'localhost`' 
    # Import the module that defines custom resources 
    Import-DscResource -Module xWebAdministration 
    Node `$NodeName 
    { .. }
Invoke-Expression $configString 

Note the use of ` prefixed to any quotes or dollar signs ($). This could be placed anywhere in a PowerShell script and will only be validated at time of execution in the script rather than at initial script launch.

The best practice is to use a separate file for the DSC, which prevents having to escape any special characters.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.