Home > Mobile >  How to prevent the application of a variable?
How to prevent the application of a variable?

Time:12-20

I know this is probably a very basic question and should exist in the PowerShell documentation, but the point is that I don't exactly know how to look up the answer to this.

The question is: how to prevent a variable from being applied before being requested in code?

Example:

#Variable
$MoveToTest = Move-Item -Path "C:\Test.jpg" -Destination "C:\Test Folder" -force -ea 0

#Code
If (Test-Path C:\*.mp4) {
   $MoveToTest
}

The If condition asks for the .jpg file to be moved if there is any .mp4 file in the -Path, however the way the code is written the variable is applied before availing the If condition.

Sorry, I know this is probably very basic, but as I'm learning by myself and according to everyday needs, I ended up missing some basic principles.

CodePudding user response:

You can defer execution of a piece of code by wrapping it in a ScriptBlock {...}:

# Variable now contains a scriptblock with code that we can invoke later!
$MoveToTest = { Move-Item -Path "C:\Test.jpg" -Destination "C:\Test Folder" -force -ea 0 }

# Code
If (Test-Path C:\*.mp4) {
    # Use the `&` invocation operator to execute the code now!
    &$MoveToTest
}

This is similar to how the function keyword works - it simply associates the scriptblock with a function name instead of a variable - and of course you could define a function as well:

function Move-TestJpgToTestFolder {
    Move-Item -Path "C:\Test.jpg" -Destination "C:\Test Folder" -force -ea 0
}

# Code
If (Test-Path C:\*.mp4) {
    # We no longer need the `&` invocation operator to execute the code, PowerShell will look up the function name automatically!
    Move-TestJpgToTestFolder
}
  • Related