Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent the application of a variable?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading