preprocessor/ macro expansion with powershell

无人久伴 提交于 2019-12-12 04:07:05

问题


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

来源:https://stackoverflow.com/questions/36344425/preprocessor-macro-expansion-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!