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

Mic*_*iel 12 powershell

我有一个Powershell脚本,它做了很多事情,其中​​一个是移动文件:

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

Move-Item $from $to
Run Code Online (Sandbox Code Playgroud)

但是,$to路径中的目录结构尚未出现.所以我希望Powershell能够用这个突击队员创造它.我试过了Move-Item -Force $from $to,但那没有帮助.

我该怎么做才能确保Powershell创建所需的目录以使其工作正常?
我希望自己清楚,如果没有,请问!

Sha*_*evy 12

你可以自己创建它:

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

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

Move-Item $from $to
Run Code Online (Sandbox Code Playgroud)

  • `-PathType Container`不是`New-Item`的参数.删除它,它按预期工作. (4认同)

Gra*_*old 6

您可以使用 system.io.directory .NET 类来检查目标目录并在它不存在时创建。这是使用您的变量的示例:-

if (!([system.io.directory]::Exists($quarantine))){
   [system.io.directory]::CreateDirectory($quarantine)
}
Copy-File $from $to
Run Code Online (Sandbox Code Playgroud)