我希望这是一个愚蠢的错误,我忽略了一些非常简单的事情。我有一个映射网络驱动器并将网络驱动器的内容复制到目标的功能。最后,我返回目标路径以便以后重新使用。但是,它似乎返回了目标路径的不同类型的对象。以下是代码段:
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
函数(Write-Host $ destinationDirectory)的输出是:
c:\temp\mycopieddirectory-20161228-1422\
但是,从进行调用的主脚本开始,输出为:
Staged to Z c:\temp\mycopieddirectory-20161228-1422\
似乎返回的stageDirectory变量以某种方式映射到Z:这是在函数中映射的新驱动器。
关于如何实际仅返回函数中上面打印的路径的任何想法?
答案 0 :(得分:2)
PowerShell具有管道概念。您调用的 Everything 返回的值您没有分配给变量或管道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
}
三项主要改进: