2016-12-28 54 views
2

我希望这是一个愚蠢的错误,我忽略了一些非常简单的事情。我有一个映射网络驱动器并将网络驱动器的内容复制到目标的功能。最后,我返回目标路径以供稍后重新使用。但是,它似乎正在为目标路径返回不同类型的对象。以下是代码片段:是否复制项目更改PowerShell中的目标参数类型

function CopyDropFolder { 
param(
    [string] $dropFolder, 
    [string] $releaseName, 
    [string] $mapDrive 
) 

$stageDirectory= $('c:\temp\' + $releaseName + '-' + (Get-Date -Uformat %Y%m%d-%H%M).ToString() + '\') 
[string]$destinationDirectory = $stageDirectory 
Write-Host 'Mapping Folder ' $dropFolder ' as ' $mapDrive 
MountDropFolder -mapfolder $dropFolder -mapDrive $mapDrive 

$sourceDir = $mapDrive + ':' + '\' 
Write-Host 'Copying from mapped drive (' $sourceDir ') to ' $stageDirectory 
Copy-Item $sourceDir -Destination $stageDirectory -Recurse 
Write-Host $destinationDirectory 
return $destinationDirectory 
} 

我所说的功能如下:

$stageDirectory = CopyDropFolder -dropFolder $mapFolder -releaseName $releaseName -mapDrive $newDrive 
Write-Host 'Staged to ' $stageDirectory 

从与功能(写主机$ destinationDirectory)的输出是:

c:\temp\mycopieddirectory-20161228-1422\ 

然而从其中呼叫由主脚本,输出:

Staged to Z c:\temp\mycopieddirectory-20161228-1422\ 

看起来返回的stageDirectory变量以某种方式映射到Z:这是在函数内映射的新驱动器。

如何实际只返回被上面的函数中打印路径中的任何想法?

回答

2

PowerShell有管道的概念。 全部你调用的那个返回一个值,其中你没有分配给变量或管道e。 G。到Out-Null cmdlet将从函数返回(即使您没有明确使用return关键字)。所以,你应该管你的职权范围内输出Out-Null

function CopyDropFolder { 
param(
    [string] $dropFolder, 
    [string] $releaseName, 
    [string] $mapDrive 
) 

$stageDirectory= $('c:\temp\' + $releaseName + '-' + (Get-Date -Uformat %Y%m%d-%H%M).ToString() + '\') 
[string]$destinationDirectory = $stageDirectory 
Write-Host 'Mapping Folder ' $dropFolder ' as ' $mapDrive 
MountDropFolder -mapfolder $dropFolder -mapDrive $mapDrive | Out-Null 

$sourceDir = $mapDrive + ':' + '\' 
Write-Host 'Copying from mapped drive (' $sourceDir ') to ' $stageDirectory 
Copy-Item $sourceDir -Destination $stageDirectory -Recurse | Out-Null 
Write-Host $destinationDirectory 
return $destinationDirectory 
} 

此外,您还可以重构你的方法是这样的:

function Copy-DropFolder 
{ 
    [CmdletBinding()] 
    param 
    (
     [string] $dropFolder, 
     [string] $releaseName, 
     [string] $mapDrive 
    ) 

    $stageDirectory = Join-Path 'c:\temp\' ('{0}-{1}' -f $releaseName, (Get-Date -Uformat %Y%m%d-%H%M).ToString()) 

    MountDropFolder -mapfolder $dropFolder -mapDrive $mapDrive | Out-Null 
    Copy-Item "$($mapDrive):\" -Destination $stageDirectory -Recurse | Out-Null 

    $stageDirectory 
} 

主要改进:

  1. 使用批准动词(Copy-DropyFolder)
  2. 使用Join-Path cmdlet
  3. 删除写主机输出(你会发现很多文章为什么你不应该使用写主机)。
+0

知道这很有趣。我会试试这个,让你知道结果。 – sohail

+0

不,上述尝试,但结果是一样 – sohail

+0

另外,我很困惑,为什么会影响变量$ destinationDirectory当我使用$ stageDirectory作为我的目标变量 – sohail