0

Im trying to run a ps script with this code

 private void materialButton3_Click(object sender, EventArgs e)
    {
        using (PowerShell pshell = PowerShell.Create())
        {
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            pshell.AddCommand("Zuordnung.ps1");
            pshell.Invoke();
        }
    }

from this thread in a c# winforms app

the ps script includes:

$Destination = "\\path1\"
Get-ChildItem "\\path2" | ForEach-Object {
    $Tail = ($_.BaseName -split '_')[-2]
    $Filter = "*_{0}" -f $Tail
    $DestDir = Get-ChildItem $Destination -Filter $Filter -Directory | Select-Object -ExpandProperty FullName -First 1
    if ($DestDir) {
        Copy-Item $_.FullName $DestDir -Force
    } else {
        "No Directory was found that matched the Filter {0} in Directory {1}" -f $Filter, $Destination | Write-Host
    }

Path1 and Path2 are supposed to be pulled off textboxes

pshell.AddParameter("Path1", "C:\somepath")

is looking good but im trying to set them dynamic e.g.

pshell.AddParameter(@"$Destination", {textbox1.text}

textbox1.text gets its value from a folder browser dialog

im also trying

 SessionState.PSVariable.Set("source", {guna2TextBox4.Text});
SessionState.PSVariable.Set("$source", {guna2TextBox4.Text});
SessionState.PSVariable.Set($@"source", {guna2TextBox4.Text});

Is there an elegant way to solve this?

Thanks in advance

7
  • Use pshell.AddParameters as documented. Also I think you want AddCommand not AddScript Commented Jan 4, 2022 at 12:10
  • no, i dont get how to assign a certain value to the ps variables Commented Jan 4, 2022 at 14:53
  • pshell.AddParameter("Path1", "C:\somepath") Commented Jan 4, 2022 at 14:56
  • ive updated the question, im trying to set textbox.text string as $destination Commented Jan 4, 2022 at 15:14
  • pshell.AddParameter("Destination", textbox1.text); you don't need the $ Commented Jan 4, 2022 at 15:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.