Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell 'Move-Item' doesn't make directory if it doesn't exists

Tags:

powershell

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!

like image 823
Michiel Avatar asked Dec 17 '12 10:12

Michiel


People also ask

How do you create a directory if it doesn't exist in PowerShell?

PowerShell Create Directory If Not Exists using Test-Path If a path or directory is missing or doesn't exist, it will return $False. Using PowerShell New-Item cmdlet, it will create directory if not exists using Test-Path.

How do you check if a directory exists or not in PowerShell?

The Test-Path Cmdlet$Folder = 'C:\Windows' "Test to see if folder [$Folder] exists" if (Test-Path -Path $Folder) { "Path exists!" } else { "Path doesn't exist." } This is similar to the -d $filepath operator for IF statements in Bash. True is returned if $filepath exists, otherwise False is returned.

What does move-Item do in PowerShell?

The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider. For example, it can move a file or subdirectory from one directory to another or move a registry subkey from one key to another.

How do I move a file from one directory to another in PowerShell?

In the PowerShell console, type Move-Item –Path c:\testfolder -Destination c:\temp and press ENTER. Replace c:\testfolder with the full path to the folder you want to move; and c:\temp with the full path of the target folder.


2 Answers

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
like image 161
Shay Levy Avatar answered Nov 16 '22 00:11

Shay Levy


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
like image 29
Graham Gold Avatar answered Nov 16 '22 01:11

Graham Gold