0

My Below Code returns me the value of Barcode and Id as "bac","test_id". But now My requirement is to replace the value of Barcode from bac to some other random text value and Id should be concanated with value of Barcode and Id. What should I pass in Script block for replacing the value of Barcode, I figured out for concanating by passing ({-join($.Barcode,$.Id)}) as script in CreateScriptBlock() but how do I do the replace part?

PowerShell ps = PowerShell.Create();
public ScriptBlock CreateScriptBlock(string script)
{
    ps.AddScript(script);
    return ps.Invoke()[0].BaseObject as ScriptBlock;
}
public IEnumerable<object> RunScriptBlock(ScriptBlock scriptBlock, Dictionary<string, object> scriptParameters)
{
    var vars = scriptParameters.Select(p => new PSVariable(p.Key, p.Value)).ToList();
    return scriptBlock.InvokeWithContext(null, vars);
}
void Main()
{
//Sample Data created-----------
    var row = new Dictionary<string,object>();
    row.Add("BarCode", "bac");
    row.Add("Id", "test_id");
    //---------------------------------
    var pars = new Dictionary<string, object>();
    pars.Add("_", row);
    var scriptBlock1 = CreateScriptBlock(@"{ $_.BarCode, $_.Id }");  
    
    var results = RunScriptBlock(scriptBlock1, pars);
    results.Dump();
   
}

Sample Input: {"some random value", "some random value 2"} Sample OutPut: BarCode: some random value and Id:some random value 2

ZZZSharePoint
  • 1,163
  • 1
  • 19
  • 54
  • In my [previous answer](https://stackoverflow.com/a/66338852/45375) I originally missed that your approach of _indirectly_ obtaining a script block - by letting PowerShell create it for you - and then invoking it directly from C# by calling its `.Invoke()` method _half_ works. However, because it doesn't provide access to the other output streams, notably not to error information, that approach should be avoided - I've updated the answer with details. – mklement0 Feb 24 '21 at 19:36
  • Leaving that aside: is your only question here how to perform string replacement _in PowerShell code_? If so, all the PowerShell _SDK_ stuff is incidental to the solution - and it's not clear what your specific string-replacement problem is. To learn about PowerShell's regex-based `-replace` operator, see [this answer](https://stackoverflow.com/a/40683667/45375). – mklement0 Feb 24 '21 at 19:39
  • To give a quick example: If `$_` contains the following: `$_ = @{ BarCode = 'bac'; Id = 'test_id' }`, then `-join (($_.BarCode -replace 'c', 'd'), ($_.Id -replace '^test_'))` outputs `'badid'`. – mklement0 Feb 24 '21 at 19:43
  • to make it more clear :in above example, if i am passing $_.Barcode in script, I get the value of Barcode and this I am assigning it to my another variable. Now question is if i just want to assign some hardcoded value to my another variable. how should i pass it in my script? – ZZZSharePoint Feb 25 '21 at 07:40

0 Answers0