preprocessor/ macro expansion with powershell

2019-09-19 04:56发布

From time to time, I use write-host in my scripts to do poor-man debugging/ logging, but having all of them fire on each run clutters my screen with tons of unneeded info.
Of course, I can comment/ uncomment the ones I need for the current run but this is a lot of editing and very error-prone.

here is what I finally came to:

[cmdletbinding()]
param(
    [parameter()]
    [string[]]$dbg_points=@('*')
)

$debug   = ($PSCmdlet.myInvocation.BoundParameters['Debug'].isPresent -eq $true)
$dbg_all = $dbg_points -contains '*'

if(($debug) -and ($dbg_all -or ($dbg_points -contains 'foo'))) { Write-host '@foo debug point' }
if(($debug) -and ($dbg_all -or ($dbg_points -contains 'bar'))) { Write-host '@bar debug point' }

if(($debug) -and ($dbg_all -or ($dbg_points -contains 'foo') -or ($dbg_points -contains 'bar'))) { Write-host 'common debug point' }

this does the job but is a lot of typing on each place where I want to have some debugging/ logging info, especially for the common points.

with some other language I would have defined some kind of macro/ preprocessor directive, say DBG(foo) {...} or DBG(foo,bar) {...} which would have expanded respectivly to to

if(($debug) -and ($dbg_all -or ($dbg_points -contains 'foo'))) {...}

and

if(($debug) -and ($dbg_all -or ($dbg_points -contains 'foo') -or ($dbg_points -contains 'bar'))) {...}

but I dont think this is possible in powershell.

do you know a better, more powershell-ish way of doing it?

oh, I forgot to tell you... I'm stuck with v2 on that computer and ca not install a newer version

0条回答
登录 后发表回答