Adis1102
Adis1102

Reputation: 212

Powershell 5.1.17763.1007 How to execute a string-command stored in a variable (Copy-Item)

I have a simple tasks that doesnt work:

$Copy = copy-item -path "C:\Folder 0" -destination "C:\Folder $x\" -recurse

for($x=1; $x -le 9;$x++)
{
$Copy
}

I cannot execute the command in the variable $Copy, when I run the loop it just prints $Copy to the console as the variable seems to be empty. I tried Invoke-Expression, & $Copy, putting the Copy-Item command under "", but that doesnt work here...

Any advice for a beginner?

Thanks in advance!

Upvotes: 0

Views: 60

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174505

As explained in the comments, Copy-Item doesn't return anything by default, so the value of $copy is $null.

From your clarifying comment:

I wanted actually just to store the command

If you want an executable block of code that you can invoke later, you might want to define a [scriptblock]. Scriptblock literals in PowerShell are easy, simply wrap your code in {}, and optionally supply parameter definitions:

$CopyCommand = {
  param([string]$X)

  Copy-Item -Path "C:\Folder 0" -Destination "C:\Folder $X\" -Recurse
}

& $CopyCommand 1
# later in the script
& $CopyCommand 2

or you can define a function with the same:

function Copy-MyFolderTree
{
  param([string]$X)

  Copy-Item -Path "C:\Folder 0" -Destination "C:\Folder $X\" -Recurse
}

Copy-MyFolderTree -X 1
# later in the script
Copy-MyFolderTree -X 2

Upvotes: 1

Related Questions