Write-Verbose is ignored in PowerShell module

I hope to use the Write-Verbose command in scripts and functions. It works as expected in script files (.ps1), but not in module files (.psm1) - the command line is ignored in modules.

Running the following script:

 PS> .\scaffold.ps1 -verbose 

It produces:

 VERBOSE: starting foo path: c:\bar.txt [missing entry here - 'verbose path: c:\bar.txt'] VERBOSE: ending foo 

scaffold.ps1:

 [cmdletbinding()] param() import-module Common -force write-verbose "starting foo" foo "c:\bar.txt" write-verbose "ending foo" 

Common.psm1:

 function foo { [cmdletbinding()] Param( [string]$path ) write-host "path: $path" write-verbose "verbose path: $path" } 

I did not associate the manifest (.psd1) with the module (.psm1) at this point.

Is there a module specific syntax that I need to use?

** edit **

I need a way to determine if the -verbose flag is -verbose in the -verbose file so that I can transfer it to the .PSM1 file.

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" 
+6
source share
3 answers

Found the answer here: How to properly use the -verbose and -debug options in a custom cmdlet

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" 
+4
source

To get Write-Verbose output from a cmdlet in a module, you need to use the -verbose general parameter. See http://technet.microsoft.com/en-us/magazine/ff677563.aspx

Using your code:

 >import-module R:\Common.psm1 >foo "c:\users" path: c:\users >foo "c:\users" -verbose path: c:\users VERBOSE: verbose path: c:\users 
+5
source

The problem is that the variables in the caller area do not receive the code in the script module. When you call ". \ Scaffold.ps1 -verbose", $ VerbosePreference is set to "Continue" in the scope of the scaffold.ps1 script. If you call the compiled Cmdlet from this script, it distinguishes this value from $ VerbosePreference, but when you call additional functions from the script module, they do not.

I recently wrote a function that allows you to import preference variables from the caller using a combination of $ PSCmdlet and $ ExecutionContext.SessionState to get the corresponding variable areas. The call to this command at the beginning of the exported function of the script module is as follows:

 Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState 

The Get-CallerPreference function can be downloaded from http://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d

+3
source

Source: https://habr.com/ru/post/944393/


All Articles