0

我正在使用以下代码通过 Windows 窗体“浏览”功能选择一个文件夹,然后将该路径传递给 gci cmdlet

cls

Function Get-Directory($initialDirectory)
{   
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
 Out-Null

 $OpenfolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
 $OpenfolderDialog.RootFolder = $initialDirectory
 $OpenfolderDialog.ShowDialog()| Out-Null
 $StartDir = $OpenfolderDialog.SelectedPath 
 Return $StartDir | Out-String
 } 

 $myDir = Get-Directory -initialDirectory "Desktop"

 $Child = gci -path $mydir -r -Filter *.jpg 

 Foreach ($item in $Child) {Move-Item -path $item.pspath -Destination $myDir -Force}

但我收到这些错误:

***在 C:\Test\Combine Pics2.ps1:17 char:13 + $Child = gci <<<< -path $mydir -r -Filter *.jpg + CategoryInfo : ObjectNotFound: (C:\Test :String ) [Get-ChildItem], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Move-Item:无法将参数绑定到参数“路径”,因为它为空。在 C:\Test\Combine Pics2.ps1:19 char:43 + Foreach ($item in $Child) {Move-Item -path <<<< $item.pspath -Destination $myDir -Force} + CategoryInfo : InvalidData: (:) [Move-Item],ParameterBindingValidationException + FullyQualifiedErrorId:ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.MoveItemCommand***

$myDir 变量是 String 类型的,为什么不传给 -path 参数。

4

3 回答 3

2

如果用户取消了对话怎么办?试试这个:

Function Get-Directory($initialDirectory)
{   
     [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

     $OpenfolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
     $OpenfolderDialog.RootFolder = $initialDirectory
     $result = $OpenfolderDialog.ShowDialog()

     if($result -eq 'ok')
     {
         $OpenfolderDialog.SelectedPath
     }
     else
     {
        "canceled"
     }
 } 


$mydir = Get-Directory -initialDirectory Desktop

if($mydir -ne 'canceled')
{
    gci -path $mydir
}
于 2013-01-23T20:15:27.420 回答
1

尝试这个:

Function Get-Directory($initialDirectory)
{   
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null

    $OpenfolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
    $OpenfolderDialog.RootFolder = $initialDirectory
    if ($OpenfolderDialog.ShowDialog() -eq "OK") {
        #Continue only if a folder was selected
        $OpenfolderDialog.SelectedPath
    }
} 

$myDir = Get-Directory -initialDirectory "Desktop"

#Continue only if a folder was selected
if($myDir) {
    $Child = Get-ChildItem -path $mydir -Recurse -Filter *.jpg
    Foreach ($item in $Child) {
        Move-Item -path $item.pspath -Destination $myDir -Force
    }
}

我用一些 if 测试对其进行了清理,因此当人们取消对话框时它不会返回错误。不需要Out-StringasSelectedPath本身返回单个字符串。

于 2013-01-23T20:09:39.733 回答
0

我在值的末尾有一个换行符和回车符$mydir,所以尝试用这样的东西进行修剪,看看这是否是你的问题:

$Child = gci -path $mydir.Trim("`r`n") -r -Filter *.jpg

更新:更好的是,只是失去Out-String你的功能:

Return $StartDir
于 2013-01-23T20:02:20.590 回答