I need help with creating a function in a script and within that same script calling the function. I have tested this code:
function FUNC1() {
$source="C:\Folder\file.txt"
$destination="\\Server\folder"
$searchFiles = Get-Content "$source"
foreach($filename in $searchFiles){
Test-Path $destination\$filename
}
}
function FUNC2() {
$source="C:\Folder\file.txt"
$destination="\\Server\folder"
$searchFiles = Get-Content "$source"
foreach($filename in $searchFiles){
Move-Item C:\folder\$filename $destination -force
}
}
if (!(FUNC1)) {FUNC2}
However, when testing FUNC1 for false, it does not move anything. When I run the code in the function separately, everything works as it should. Put them together as functions and it is not working. I do not want to create a separate function.ps1 to call, I would rather have my functions called from within the code. Thanks!
FUNC1is going to return an array (of booleans) if$searchFileshas two or more filenames in it.This will always be true, even if it just contains multiple
$falsevalues (because you’re testing the array, not the values it contains). Negating this (the!) will always give$falseso the contents of theifwill never be executed.Your approach seems very strange, where perform all the tests and then the moves whatever the tests showed for that file. I would have expected something like:
Which will iterate over all the lines in
$source, ignore cases where a file of that name exists at the destination and move the file to the destination.