Function 追加子目录时,Powershell函数返回双路径

Function 追加子目录时,Powershell函数返回双路径,function,powershell,subdirectory,Function,Powershell,Subdirectory,我有一个奇怪的问题。我有一个函数,它接受$srcDir和$destDir以及$topDir $srcDir的格式为\$topDir\subDir1\subDir2\subDir..n 我需要的是将所有subDir部分附加到$destDir 到目前为止,我的方法是分割路径,直到到达$topDir,然后使用joinpath将结果字符串附加到$destDir 如果$destPath中没有附加子目录,则返回结果是完美的 如果我将路径附加到$destPath,那么返回值是$destPath$destPat

我有一个奇怪的问题。我有一个函数,它接受$srcDir和$destDir以及$topDir $srcDir的格式为\$topDir\subDir1\subDir2\subDir..n 我需要的是将所有subDir部分附加到$destDir

到目前为止,我的方法是分割路径,直到到达$topDir,然后使用joinpath将结果字符串附加到$destDir

如果$destPath中没有附加子目录,则返回结果是完美的

如果我将路径附加到$destPath,那么返回值是$destPath$destPath

以下是示例值中的输出

  • srcIn:C:\path\topdir\
  • 目的地:\\server\path\
  • destOut:\\server\path\
现在如果我有子目录

  • scrIn:C:\path\topdir\subpath\subpath1
  • 目的:\server\path\
  • destOut:\\server\path\subpath\subpath1\\server\path\subpath\subpath1
在函数内部,路径看起来是正确的。destOut值没有dbl。一旦我从函数返回,它就具有双重值

我如何防止这种情况?我只是想要一个简单的函数来获取子目录并附加到destDir,这样我就可以保留文件夹结构并将文件移动到相应的目录中

md函数(新项的别名)返回它创建的目录。由于您不使用该值执行任何操作,因此它被添加到函数的输出流中

要解决此问题,请执行以下操作之一:

md $destPath | out-null

[null]md $destPath
md函数(新项的别名)返回它创建的目录。由于您不使用该值执行任何操作,因此它被添加到函数的输出流中

要解决此问题,请执行以下操作之一:

md $destPath | out-null

[null]md $destPath

对于@Tessellinghecker,我同意一行就足够了,但我相信这一行是需要的:

$srcPath -replace [Regex]::Escape($topDir), $destDir
现在让我们将其封装在函数中

function MapSubDir($srcPath, $topDir, $destDir)
{
    $srcPath -replace [Regex]::Escape($topDir), $destDir
}
并将您最初的两个测试用例提供给它,以观察您是否获得了所需的结果:

PS> $srcPath= "C:\path\topdir\"
PS> $topDir= "C:\path\topdir\"
PS> $destDir= "\\server\path\"
PS> MapSubDir $srcPath $topDir $destDir
\\server\path

PS> $srcPath = "C:\path\topdir\subpath\subpath1"
PS> MapSubDir $srcPath $topDir $destDir
\\server\path\subpath\subpath1

对于@Tessellinghecker,我同意一行就足够了,但我相信这一行是需要的:

$srcPath -replace [Regex]::Escape($topDir), $destDir
现在让我们将其封装在函数中

function MapSubDir($srcPath, $topDir, $destDir)
{
    $srcPath -replace [Regex]::Escape($topDir), $destDir
}
并将您最初的两个测试用例提供给它,以观察您是否获得了所需的结果:

PS> $srcPath= "C:\path\topdir\"
PS> $topDir= "C:\path\topdir\"
PS> $destDir= "\\server\path\"
PS> MapSubDir $srcPath $topDir $destDir
\\server\path

PS> $srcPath = "C:\path\topdir\subpath\subpath1"
PS> MapSubDir $srcPath $topDir $destDir
\\server\path\subpath\subpath1

似乎有很多代码需要执行
($srcPath-replace“*\\$topDir”,“$destDir\\$topDir”)
…似乎有很多代码需要执行
($srcPath-replace“*\\$topDir”,“$destDir\\$topDir”)
…虽然这是返回值的技术原因,我确实喜欢下面的答案,因为它以更好的格式完成了同样的事情。感谢所有帮助提醒我函数返回的次数比你想象的要多的人。我忘了。我希望它只返回我在表达式return$destDir.dam右侧指定的变量值,经过数小时的黑客攻击,这终于救了我的命,谢谢!虽然这在技术上是返回值的原因,但我确实喜欢下面的答案,因为它以更好的格式完成了同样的事情。感谢所有帮助提醒我函数返回的次数比你想象的要多的人。我忘了。我希望它只返回我在表达式return$destDir.dam右侧指定的变量值,经过数小时的黑客攻击,这终于救了我的命,谢谢!