简体   繁体   中英

StringExpansion in c# called from Powershell

I have a small c# class, that does some logging stuff and that is called from a powershell scripting framework using:

[System.Reflection.Assembly]::LoadFrom("$ExtensionsPath\LogWriter.dll") 
$Log = New-Object LogWriter($LogFile, $addTimeStamp, $logLevel, $overWrite)

Writing into the log file goes like this

$Log.AddInfo("myText")

Works fine so far.

What I am thinking about for some time is, if I am able to use stringexpansion in the AddInfo() method of my LogWriter class?

Look at the example:

$ModulesPath = ‘C:\temp\modules’
$test = ‘This is a text and I want to expand $ModulesPath in my c# LogWriter class’
$Log.AddInfo($test)

The c# class shall now expand the $modulespath in $test as powershell does. I already know that in c# I have access to the powershell runspace from which the c# class was called using System.Management.Automation Namespace. But then I am lost how to really expand the variable.

The entry written into the logfile should look like this:

This is a text and I want to expand C:\\temp\\modules in my c# LogWriter class

Of course I know I can do this in my script using

$Log.AddInfo(($ExecutionContext.InvokeCommand.ExpandString($test)))

But this is nasty because it looks ugly and if I forget to add this statement no expansion is done.

So I thought of retrieving the current Runspace in my c# class and do the ExpandString-Command there to get the expanded variable but I fail. This is beyond my knowledge.

Anyone here to tell my if this is possible? I already think of some other tasks where to use this so please do not start a flame war about if this makes sense or not.

Rgds

Jan

How can the value for $ModulesPath be known outside of your script? If you want it to be expanded in C#, then you have to send it, may be as a second Parameter to AddInfo like:

$Log.AddInfo($test, $ModulesPath)

Now it's known and the replacement could be done by:

string sNew = sTest.Replace("$ModulesPath", sModulesPath);

where sTest and sModulesPath are the parameters.

not sure if this is what you're asking about, but please try using double quotes on the $test string:

$test = "This is a text and I want to expand $ModulesPath in my c# LogWriter class"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM