如果目录不存在,Powershell 'Move-Item' 不会创建目录

标签 powershell

我有一个 Powershell 脚本,它可以执行很多操作,其中之一就是移动文件:

$from = $path + '\' + $_.substring(8)
$to   = $quarantaine + '\' + $_.substring(8)

Move-Item $from $to

但碰巧 $to 路径中尚不存在目录结构。所以我希望 Powershell 用这个突击队来创建它。我尝试过 Move-Item -Force $from $to,但这没有帮助。

我可以做什么来确保 Powershell 创建所需的目录以使事情正常工作?
希望我说清楚了,如果不清楚,请追问!

最佳答案

您可以自己创建它:

$from = Join-Path $path $_.substring(8)
$to = Join-Path $quarantaine $_.substring(8)

if(!(Test-Path $to))
{
    New-Item -Path $to -ItemType Directory -Force | Out-Null
}

Move-Item $from $to

关于如果目录不存在,Powershell 'Move-Item' 不会创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13912038/

相关文章:

powershell - 如何使powershell在错误上不那么冗长?

xml - 循环遍历节点并更改树结构xml

sql-server - 如何从 PowerShell 运行 sp_configure 'Ad Hoc Distributed Queries'?

powershell - 是否可以使用变量在Powershell中引用.NET静态类?

powershell - 合并两个相似的 PSObject

powershell - 错误重定向在 powershell 中不起作用

Powershell - 文件已存在时的另存为功能

windows - 使用 powershell 写入 excel 时防止覆盖弹出窗口

function - 为什么我的函数没有公共(public)参数?

powershell - 批量隐藏Invoke-WebRequest