21

I have a Powershell script which does a lot of things and one of them is moving files:

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

Move-Item $from $to

But it happens the directory structure isn't already present in the $to path. So I would like Powershell to create it with this commando. I've tried Move-Item -Force $from $to, but that didn't help out.

What can I do to make sure Powershell creates the needed directories in order to get things working?
I hope I make myself clear, if not, please ask!

Michiel
  • 7,855
  • 16
  • 61
  • 113

3 Answers3

19

You could create it yourself:

$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
Hashbrown
  • 12,091
  • 8
  • 72
  • 95
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
6

You could use the system.io.directory .NET class to check for destination directory and create if it doesn't exist. Here is an example using your variables:-

if (!([system.io.directory]::Exists($quarantine))){
   [system.io.directory]::CreateDirectory($quarantine)
}
Copy-File $from $to
Graham Gold
  • 2,435
  • 2
  • 25
  • 34
  • Why would you use this over the simpler and more common `Test-Path`/`New-Item`? – Nelson Rothermel Jun 23 '16 at 01:37
  • 1
    @NelsonRothermel At the time of writing I was new to powershell, unaware of them and the answer I gave was how I would do this at the time - this was 4 years ago. These days I would indeed use test-path/new-item. – Graham Gold Jun 23 '16 at 01:55
  • @NelsonRothermel it's actually something I find pretty nice about powershell though - if you come into it with a .NET background, a lot of what you are used to is portable and reusable in powershell with ease. And if there's not a cmdlet that does what you need, but there's a .NET class that does, problem solved! – Graham Gold Jun 23 '16 at 01:59
  • Perfect, thanks. I was just wondering if there was something I didn't know. I do like how you can fall back on full .NET as needed or even write your own. – Nelson Rothermel Jun 24 '16 at 02:56
  • Actually you don't need `Exists($quarantine)` with `CreateDirectory` because it does it internally anyways. Even better, if you have access to `\\server\share\my\path` directory but not `\\server\share\my` directory `Exists(@"\\server\share\my\path\subfolder")` will fail but `CreateDirectory(@"\\server\share\my\path\subfolder")` won't. – Jürgen Steinblock Jun 23 '23 at 07:47
0

You could also add a utility function like this:

Function Move-Item-Parent([string]$path, [string]$destination) {
    New-Item $destination -ItemType Directory -Force
    Move-Item $path $destination
}

Then invoke it like this:

Move-Item-Parent $from $to
KyleMit
  • 30,350
  • 66
  • 462
  • 664