Passing on variable to invoke-item

时间:2017-08-04 12:23:11

标签: powershell

Looking for a solution. I have simple script that will browse to specific directory on network pc's.

However I'm not sure how to pass on $compname variable to invoke-item. I'm running PS v2.0. With current script I'm getting error: Invoke-Item : Cannot find path '\\C$\Program Files\IBM\Lotus\Notes\Data' because it does not exist.

$dskbox = New-Object system.windows.Forms.TextBox
$dskbox.Width = 134
$dskbox.Height = 20
$dskbox.location = new-object system.drawing.point(24,41)
$dskbox.Font = "Microsoft Sans Serif,10,style=Bold"
$Title.controls.Add($dskbox)
$compname = $dskbox.Text


$Open = New-Object system.windows.Forms.Button
$Open.BackColor = "#23b14d"
$Open.Text = "Open"
$Open.ForeColor = "#ffffff"
$Open.Width = 163
$Open.Height = 51
$Open.location = new-object system.drawing.point(6,77)
$Open.Font = "Microsoft Sans Serif,10,style=Bold"
$Title.controls.Add($Open)


$Open.Add_Click({


ii "\\$compname\C$\Program Files\IBM\Lotus\Notes\Data"

}) 

[void]$Title.ShowDialog()
$Title.Dispose()

2 个答案:

答案 0 :(得分:0)

You set $compname when creating the textbox, which is obviously going to be empty at that point in time. You need to move it into the scriptblock:

$Open.Add_Click({
    $compname = $dskbox.Text
    ii "\\$compname\C$\Program Files\IBM\Lotus\Notes\Data"
})

Or you could just get rid of that variable entirely: ii "\\$($dskbox.Text)\C$\Program Files\IBM\Lotus\Notes\Data"

答案 1 :(得分:0)

You can associate your $Open.add_Click($Open_OnClick) to a scriptblock and start invoke-item inside the scriptblock.

$dskbox = New-Object system.windows.Forms.TextBox
$dskbox.Width = 134
$dskbox.Height = 20
$dskbox.location = new-object system.drawing.point(24,41)
$dskbox.Font = "Microsoft Sans Serif,10,style=Bold"
$Title.controls.Add($dskbox)
$compname = $dskbox.Text


$Open = New-Object system.windows.Forms.Button
$Open.BackColor = "#23b14d"
$Open.Text = "Open"
$Open.ForeColor = "#ffffff"
$Open.Width = 163
$Open.Height = 51
$Open.location = new-object system.drawing.point(6,77)
$Open.Font = "Microsoft Sans Serif,10,style=Bold"
$Open.add_Click($Open_OnClick)
$Title.controls.Add($Open)

$Open_OnClick= 
{
   ii "\\$compname\C$\Program Files\IBM\Lotus\Notes\Data"
}

[void]$Title.ShowDialog()
$Title.Dispose()