Script not passing variable information into If, Else, While, or functions












2















I have a script that was working before I started breaking it apart into smaller pieces. Something I noticed is as I try and use variables the information is not brought in. I have to copy paste that variable into my If, Else, While, or other functions in order for them to be used. I was told to use $script: but as far as I can tell that only allows the variable to "report out" of the function to be used later. I don't need that just to pull the info in.



Breakdown of my script thus far:




  1. User drops a folder into a specific drop off folder.

  2. The script detects a new file and starts to run

  3. The name of the folder is noted

  4. All the files are moved from their folder structure into another folder.

  5. All those files are then converted to a single .pdf

  6. That .pdf is moved to a "completed folder"

  7. All the empty folders and files are deleted.


The script runs all this upon startup, then sits and watches for updates.



My code:



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($outLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

#Lone Counter
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName

#Pulls the last write time of a folder to compare later.
$grabStatus = {$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime } }

#Get PDF name from Folder
$grabFileName = {
$folder = get-childitem -Path $inPath -Directory -Name
$fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
$moveFiles = {
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
$makePDF = {
& CD $runPath
& magick "$fileTypes" $fileName
}

#Move final PDF
$moveCmplt = {
Get-ChildItem -Path $pdf -File | Move-Item -Destination $outPath
}

#Delete Old files
$deleteOld = {
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
$stats = {
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
$action = {
$grabStatus
If ($status -eq $statusOld){
$grabFileName
$moveFiles
& CD $runPath
$grabStatus
If ($status -eq $statusOld) {
$makePDF
}
Else{
$stats
}
$deleteOld
}
Else
{
$stats
}
}

#First Time Start, Then Loop run.
While ($freshStart -eq $null) {
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0) {
}
Else {
$action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}


UPDATED CODE
It works on the first time run, but the loop is broken after converting everything to functions.



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

#Lone Vars
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName
#$pathMagick = 'C:Program FilesImageMagick-7.0.8-Q16magick.exe'

#Pulls the last write time of a folder to compare later.
function grabStatus
{
& CD $runPath
$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
}

#Get PDF name from Folder
function grabFileName
{
$folder = get-childitem -Path $inPath -Directory -Name
$global:fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
function moveFiles
{
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
function makePDF
{
& CD $runPath
& magick $fileTypes $global:fileName
}

#Move final PDF
function moveCmplt
{
Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
}

#Delete Old files
function deleteOld
{
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
function stats
{
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
function action
{
grabStatus
If ($status -eq $statusOld)
{
grabFileName
moveFiles
grabStatus
If ($status -eq $statusOld)
{
makePDF
grabStatus
If ($status -eq $statusOld)
{
grabStatus
moveCmplt
If ($status -eq $statusOld)
{
deleteOld
}
}
Else { stats }
}
Else { stats }
}
Else { stats }
}

$runIt = { action }

#First Time Start, Then Loop run.
While ($freshStart -eq $null)
{
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
{
}
Else
{
action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $runIt
#Register-ObjectEvent $watcher "Created" -Action $action
while ($true) { sleep 5 }









share|improve this question

























  • Nice use of FileSystemWatcher! This is really cool but I can't help but think that this project would be much better as a C# or VB.NET project. You could compile it in to an EXE and run it as a windows service. It looks like you are capable of writing the code.

    – HackSlash
    Jan 10 at 21:00











  • I don't see where things go wrong, but you can consider using global variables. In order to do that, type $Global:nameofvar. It should be global, so it will work from one function to another, etc. Note, each time you want to refer to that variable, you use $Global:nameofvar.

    – LPChip
    Jan 10 at 21:00








  • 1





    To me your technique of nesting script blocks in variables looks more like a sort of obfuscating code than I see a real benefit.

    – LotPings
    Jan 10 at 23:14











  • Tohny, I hope I didn't confuse you with those comments from your other post, but I replied back to you there too. I was talking about putting the file/folder operations into it's own function. The $script: prepended to a variable set within that function in the same script would make it available outside the function but so would returning a value from that function and setting that as a variable's value outside the function. In any case, I dropped a quick example pastebin on the other post for you to test for the idea I was referring to there.

    – Pimp Juice IT
    Jan 11 at 2:26













  • Furthermore, I was suggesting to use a function (function name{...}) rather than a scriptblock ($var={...}) for the refactoring or whatever. I any event, check out the other post's comment I left you with a link.

    – Pimp Juice IT
    Jan 11 at 2:26


















2















I have a script that was working before I started breaking it apart into smaller pieces. Something I noticed is as I try and use variables the information is not brought in. I have to copy paste that variable into my If, Else, While, or other functions in order for them to be used. I was told to use $script: but as far as I can tell that only allows the variable to "report out" of the function to be used later. I don't need that just to pull the info in.



Breakdown of my script thus far:




  1. User drops a folder into a specific drop off folder.

  2. The script detects a new file and starts to run

  3. The name of the folder is noted

  4. All the files are moved from their folder structure into another folder.

  5. All those files are then converted to a single .pdf

  6. That .pdf is moved to a "completed folder"

  7. All the empty folders and files are deleted.


The script runs all this upon startup, then sits and watches for updates.



My code:



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($outLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

#Lone Counter
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName

#Pulls the last write time of a folder to compare later.
$grabStatus = {$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime } }

#Get PDF name from Folder
$grabFileName = {
$folder = get-childitem -Path $inPath -Directory -Name
$fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
$moveFiles = {
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
$makePDF = {
& CD $runPath
& magick "$fileTypes" $fileName
}

#Move final PDF
$moveCmplt = {
Get-ChildItem -Path $pdf -File | Move-Item -Destination $outPath
}

#Delete Old files
$deleteOld = {
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
$stats = {
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
$action = {
$grabStatus
If ($status -eq $statusOld){
$grabFileName
$moveFiles
& CD $runPath
$grabStatus
If ($status -eq $statusOld) {
$makePDF
}
Else{
$stats
}
$deleteOld
}
Else
{
$stats
}
}

#First Time Start, Then Loop run.
While ($freshStart -eq $null) {
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0) {
}
Else {
$action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}


UPDATED CODE
It works on the first time run, but the loop is broken after converting everything to functions.



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

#Lone Vars
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName
#$pathMagick = 'C:Program FilesImageMagick-7.0.8-Q16magick.exe'

#Pulls the last write time of a folder to compare later.
function grabStatus
{
& CD $runPath
$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
}

#Get PDF name from Folder
function grabFileName
{
$folder = get-childitem -Path $inPath -Directory -Name
$global:fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
function moveFiles
{
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
function makePDF
{
& CD $runPath
& magick $fileTypes $global:fileName
}

#Move final PDF
function moveCmplt
{
Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
}

#Delete Old files
function deleteOld
{
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
function stats
{
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
function action
{
grabStatus
If ($status -eq $statusOld)
{
grabFileName
moveFiles
grabStatus
If ($status -eq $statusOld)
{
makePDF
grabStatus
If ($status -eq $statusOld)
{
grabStatus
moveCmplt
If ($status -eq $statusOld)
{
deleteOld
}
}
Else { stats }
}
Else { stats }
}
Else { stats }
}

$runIt = { action }

#First Time Start, Then Loop run.
While ($freshStart -eq $null)
{
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
{
}
Else
{
action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $runIt
#Register-ObjectEvent $watcher "Created" -Action $action
while ($true) { sleep 5 }









share|improve this question

























  • Nice use of FileSystemWatcher! This is really cool but I can't help but think that this project would be much better as a C# or VB.NET project. You could compile it in to an EXE and run it as a windows service. It looks like you are capable of writing the code.

    – HackSlash
    Jan 10 at 21:00











  • I don't see where things go wrong, but you can consider using global variables. In order to do that, type $Global:nameofvar. It should be global, so it will work from one function to another, etc. Note, each time you want to refer to that variable, you use $Global:nameofvar.

    – LPChip
    Jan 10 at 21:00








  • 1





    To me your technique of nesting script blocks in variables looks more like a sort of obfuscating code than I see a real benefit.

    – LotPings
    Jan 10 at 23:14











  • Tohny, I hope I didn't confuse you with those comments from your other post, but I replied back to you there too. I was talking about putting the file/folder operations into it's own function. The $script: prepended to a variable set within that function in the same script would make it available outside the function but so would returning a value from that function and setting that as a variable's value outside the function. In any case, I dropped a quick example pastebin on the other post for you to test for the idea I was referring to there.

    – Pimp Juice IT
    Jan 11 at 2:26













  • Furthermore, I was suggesting to use a function (function name{...}) rather than a scriptblock ($var={...}) for the refactoring or whatever. I any event, check out the other post's comment I left you with a link.

    – Pimp Juice IT
    Jan 11 at 2:26
















2












2








2








I have a script that was working before I started breaking it apart into smaller pieces. Something I noticed is as I try and use variables the information is not brought in. I have to copy paste that variable into my If, Else, While, or other functions in order for them to be used. I was told to use $script: but as far as I can tell that only allows the variable to "report out" of the function to be used later. I don't need that just to pull the info in.



Breakdown of my script thus far:




  1. User drops a folder into a specific drop off folder.

  2. The script detects a new file and starts to run

  3. The name of the folder is noted

  4. All the files are moved from their folder structure into another folder.

  5. All those files are then converted to a single .pdf

  6. That .pdf is moved to a "completed folder"

  7. All the empty folders and files are deleted.


The script runs all this upon startup, then sits and watches for updates.



My code:



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($outLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

#Lone Counter
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName

#Pulls the last write time of a folder to compare later.
$grabStatus = {$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime } }

#Get PDF name from Folder
$grabFileName = {
$folder = get-childitem -Path $inPath -Directory -Name
$fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
$moveFiles = {
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
$makePDF = {
& CD $runPath
& magick "$fileTypes" $fileName
}

#Move final PDF
$moveCmplt = {
Get-ChildItem -Path $pdf -File | Move-Item -Destination $outPath
}

#Delete Old files
$deleteOld = {
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
$stats = {
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
$action = {
$grabStatus
If ($status -eq $statusOld){
$grabFileName
$moveFiles
& CD $runPath
$grabStatus
If ($status -eq $statusOld) {
$makePDF
}
Else{
$stats
}
$deleteOld
}
Else
{
$stats
}
}

#First Time Start, Then Loop run.
While ($freshStart -eq $null) {
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0) {
}
Else {
$action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}


UPDATED CODE
It works on the first time run, but the loop is broken after converting everything to functions.



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

#Lone Vars
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName
#$pathMagick = 'C:Program FilesImageMagick-7.0.8-Q16magick.exe'

#Pulls the last write time of a folder to compare later.
function grabStatus
{
& CD $runPath
$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
}

#Get PDF name from Folder
function grabFileName
{
$folder = get-childitem -Path $inPath -Directory -Name
$global:fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
function moveFiles
{
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
function makePDF
{
& CD $runPath
& magick $fileTypes $global:fileName
}

#Move final PDF
function moveCmplt
{
Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
}

#Delete Old files
function deleteOld
{
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
function stats
{
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
function action
{
grabStatus
If ($status -eq $statusOld)
{
grabFileName
moveFiles
grabStatus
If ($status -eq $statusOld)
{
makePDF
grabStatus
If ($status -eq $statusOld)
{
grabStatus
moveCmplt
If ($status -eq $statusOld)
{
deleteOld
}
}
Else { stats }
}
Else { stats }
}
Else { stats }
}

$runIt = { action }

#First Time Start, Then Loop run.
While ($freshStart -eq $null)
{
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
{
}
Else
{
action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $runIt
#Register-ObjectEvent $watcher "Created" -Action $action
while ($true) { sleep 5 }









share|improve this question
















I have a script that was working before I started breaking it apart into smaller pieces. Something I noticed is as I try and use variables the information is not brought in. I have to copy paste that variable into my If, Else, While, or other functions in order for them to be used. I was told to use $script: but as far as I can tell that only allows the variable to "report out" of the function to be used later. I don't need that just to pull the info in.



Breakdown of my script thus far:




  1. User drops a folder into a specific drop off folder.

  2. The script detects a new file and starts to run

  3. The name of the folder is noted

  4. All the files are moved from their folder structure into another folder.

  5. All those files are then converted to a single .pdf

  6. That .pdf is moved to a "completed folder"

  7. All the empty folders and files are deleted.


The script runs all this upon startup, then sits and watches for updates.



My code:



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($outLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

#Lone Counter
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName

#Pulls the last write time of a folder to compare later.
$grabStatus = {$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime } }

#Get PDF name from Folder
$grabFileName = {
$folder = get-childitem -Path $inPath -Directory -Name
$fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
$moveFiles = {
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
$makePDF = {
& CD $runPath
& magick "$fileTypes" $fileName
}

#Move final PDF
$moveCmplt = {
Get-ChildItem -Path $pdf -File | Move-Item -Destination $outPath
}

#Delete Old files
$deleteOld = {
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
$stats = {
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
$action = {
$grabStatus
If ($status -eq $statusOld){
$grabFileName
$moveFiles
& CD $runPath
$grabStatus
If ($status -eq $statusOld) {
$makePDF
}
Else{
$stats
}
$deleteOld
}
Else
{
$stats
}
}

#First Time Start, Then Loop run.
While ($freshStart -eq $null) {
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0) {
}
Else {
$action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}


UPDATED CODE
It works on the first time run, but the loop is broken after converting everything to functions.



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

#Lone Vars
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName
#$pathMagick = 'C:Program FilesImageMagick-7.0.8-Q16magick.exe'

#Pulls the last write time of a folder to compare later.
function grabStatus
{
& CD $runPath
$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
}

#Get PDF name from Folder
function grabFileName
{
$folder = get-childitem -Path $inPath -Directory -Name
$global:fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
function moveFiles
{
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
function makePDF
{
& CD $runPath
& magick $fileTypes $global:fileName
}

#Move final PDF
function moveCmplt
{
Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
}

#Delete Old files
function deleteOld
{
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
function stats
{
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
function action
{
grabStatus
If ($status -eq $statusOld)
{
grabFileName
moveFiles
grabStatus
If ($status -eq $statusOld)
{
makePDF
grabStatus
If ($status -eq $statusOld)
{
grabStatus
moveCmplt
If ($status -eq $statusOld)
{
deleteOld
}
}
Else { stats }
}
Else { stats }
}
Else { stats }
}

$runIt = { action }

#First Time Start, Then Loop run.
While ($freshStart -eq $null)
{
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
{
}
Else
{
action
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $runIt
#Register-ObjectEvent $watcher "Created" -Action $action
while ($true) { sleep 5 }






windows-10 powershell imagemagick






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 14 at 20:55







Tohny.Johnson

















asked Jan 10 at 20:55









Tohny.JohnsonTohny.Johnson

737




737













  • Nice use of FileSystemWatcher! This is really cool but I can't help but think that this project would be much better as a C# or VB.NET project. You could compile it in to an EXE and run it as a windows service. It looks like you are capable of writing the code.

    – HackSlash
    Jan 10 at 21:00











  • I don't see where things go wrong, but you can consider using global variables. In order to do that, type $Global:nameofvar. It should be global, so it will work from one function to another, etc. Note, each time you want to refer to that variable, you use $Global:nameofvar.

    – LPChip
    Jan 10 at 21:00








  • 1





    To me your technique of nesting script blocks in variables looks more like a sort of obfuscating code than I see a real benefit.

    – LotPings
    Jan 10 at 23:14











  • Tohny, I hope I didn't confuse you with those comments from your other post, but I replied back to you there too. I was talking about putting the file/folder operations into it's own function. The $script: prepended to a variable set within that function in the same script would make it available outside the function but so would returning a value from that function and setting that as a variable's value outside the function. In any case, I dropped a quick example pastebin on the other post for you to test for the idea I was referring to there.

    – Pimp Juice IT
    Jan 11 at 2:26













  • Furthermore, I was suggesting to use a function (function name{...}) rather than a scriptblock ($var={...}) for the refactoring or whatever. I any event, check out the other post's comment I left you with a link.

    – Pimp Juice IT
    Jan 11 at 2:26





















  • Nice use of FileSystemWatcher! This is really cool but I can't help but think that this project would be much better as a C# or VB.NET project. You could compile it in to an EXE and run it as a windows service. It looks like you are capable of writing the code.

    – HackSlash
    Jan 10 at 21:00











  • I don't see where things go wrong, but you can consider using global variables. In order to do that, type $Global:nameofvar. It should be global, so it will work from one function to another, etc. Note, each time you want to refer to that variable, you use $Global:nameofvar.

    – LPChip
    Jan 10 at 21:00








  • 1





    To me your technique of nesting script blocks in variables looks more like a sort of obfuscating code than I see a real benefit.

    – LotPings
    Jan 10 at 23:14











  • Tohny, I hope I didn't confuse you with those comments from your other post, but I replied back to you there too. I was talking about putting the file/folder operations into it's own function. The $script: prepended to a variable set within that function in the same script would make it available outside the function but so would returning a value from that function and setting that as a variable's value outside the function. In any case, I dropped a quick example pastebin on the other post for you to test for the idea I was referring to there.

    – Pimp Juice IT
    Jan 11 at 2:26













  • Furthermore, I was suggesting to use a function (function name{...}) rather than a scriptblock ($var={...}) for the refactoring or whatever. I any event, check out the other post's comment I left you with a link.

    – Pimp Juice IT
    Jan 11 at 2:26



















Nice use of FileSystemWatcher! This is really cool but I can't help but think that this project would be much better as a C# or VB.NET project. You could compile it in to an EXE and run it as a windows service. It looks like you are capable of writing the code.

– HackSlash
Jan 10 at 21:00





Nice use of FileSystemWatcher! This is really cool but I can't help but think that this project would be much better as a C# or VB.NET project. You could compile it in to an EXE and run it as a windows service. It looks like you are capable of writing the code.

– HackSlash
Jan 10 at 21:00













I don't see where things go wrong, but you can consider using global variables. In order to do that, type $Global:nameofvar. It should be global, so it will work from one function to another, etc. Note, each time you want to refer to that variable, you use $Global:nameofvar.

– LPChip
Jan 10 at 21:00







I don't see where things go wrong, but you can consider using global variables. In order to do that, type $Global:nameofvar. It should be global, so it will work from one function to another, etc. Note, each time you want to refer to that variable, you use $Global:nameofvar.

– LPChip
Jan 10 at 21:00






1




1





To me your technique of nesting script blocks in variables looks more like a sort of obfuscating code than I see a real benefit.

– LotPings
Jan 10 at 23:14





To me your technique of nesting script blocks in variables looks more like a sort of obfuscating code than I see a real benefit.

– LotPings
Jan 10 at 23:14













Tohny, I hope I didn't confuse you with those comments from your other post, but I replied back to you there too. I was talking about putting the file/folder operations into it's own function. The $script: prepended to a variable set within that function in the same script would make it available outside the function but so would returning a value from that function and setting that as a variable's value outside the function. In any case, I dropped a quick example pastebin on the other post for you to test for the idea I was referring to there.

– Pimp Juice IT
Jan 11 at 2:26







Tohny, I hope I didn't confuse you with those comments from your other post, but I replied back to you there too. I was talking about putting the file/folder operations into it's own function. The $script: prepended to a variable set within that function in the same script would make it available outside the function but so would returning a value from that function and setting that as a variable's value outside the function. In any case, I dropped a quick example pastebin on the other post for you to test for the idea I was referring to there.

– Pimp Juice IT
Jan 11 at 2:26















Furthermore, I was suggesting to use a function (function name{...}) rather than a scriptblock ($var={...}) for the refactoring or whatever. I any event, check out the other post's comment I left you with a link.

– Pimp Juice IT
Jan 11 at 2:26







Furthermore, I was suggesting to use a function (function name{...}) rather than a scriptblock ($var={...}) for the refactoring or whatever. I any event, check out the other post's comment I left you with a link.

– Pimp Juice IT
Jan 11 at 2:26












3 Answers
3






active

oldest

votes


















2














Summed up solution:



Converted my script blocks to functions
i.e.



$variable = {code}


to



function variable {code}


This worked for most of my script but the uninteded side affect was that my loop no longer worked. The solution for that was to convert the main function I was using to a global function.
i.e.



function global:functionName {code}


After this everything is working exactly how it should. Thank you Pimp Juice IT, LPChip, and HackSlash for all your help.



Working Script:



#File Locations
$rootPath = 'C:IT'
$inLoc = 'Convert_Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

#Lone Vars
$freshStart = $null
$statusOld = $null
$pathLoc = (Get-Item -Path ".").FullName

#Pulls the last write time of a folder to compare later.
function grabStatus
{
& CD $runPath
$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
}

#Get PDF name from Folder
function grabFileName
{
$folder = get-childitem -Path $inPath -Directory -Name
$global:fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
function moveFiles
{
Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
function makePDF
{
& CD $runPath
& magick $fileTypes $global:fileName
}

#Move final PDF
function moveCmplt
{
Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
}

#Delete Old files
function deleteOld
{
Remove-Item $remove1 -Recurse -Force
Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
function stats
{
$statusOld = $status
$grabStatus
sleep 10
}

#Exicute main conversion together.
function global:runIt
{
grabStatus
If ($status -eq $statusOld)
{
grabFileName
moveFiles
grabStatus
If ($status -eq $statusOld)
{
makePDF
grabStatus
If ($status -eq $statusOld)
{
grabStatus
moveCmplt
If ($status -eq $statusOld)
{
deleteOld
}
}
Else { stats }
}
Else { stats }
}
Else { stats }
}

#$runIt = { action }

#First Time Start, Then Loop run.
While ($freshStart -eq $null)
{
If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
{
}
Else
{
global:runIt
}
$freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action { global:runIt }
while ($true) { sleep 5 }





share|improve this answer
























  • Instead of making everything global you can pass arguments to the functions. For each variable that needs to be accessed inside the function an argument must be passed in. For each variable that is set and returned, you need a separate function. So you break it down by what each function returns, passing the result in to the next function until you get your final answer. stackoverflow.com/questions/5592531/…

    – HackSlash
    Jan 15 at 16:42











  • NOTE: If this is your final answer please hit the green check mark. You get points for the answer and people will stop coming here trying to help.

    – HackSlash
    Jan 15 at 16:44











  • Good to know! Green check mark has been clicked.

    – Tohny.Johnson
    Jan 16 at 17:46



















1














As with most programming/script languages, variables have a scope. They can share data within the main code, or function, but not cross that boundary unless you tell the script it can do so.



Although you can use global variables to set something globally, you can also work with functions if you do it well. Let me explain.



Functions can get variables from outside the script and return them to the caller of the function. Powershell does functions a bit different than most scripts, because it treats a function as an object, which allows you to do cool things.



Here is a small example of how to use a function with multiple variables:



function Tools
{

param
( [switch]$MySwitch
, [switch]$MySwitchWithReturn
, [Parameter(Mandatory=$false)] [String] $MyParameter
)


if( $MySwitch )
{
write-host "My Switch was activated"
}

if( $MySwitchWithReturn )
{
"My SwitchWithReturn was activated"
}

if( $MyParameter )
{
Write-Host "The parameter has value: " + $MyParameter
$MyValue2 = "Another value, 2"

#Lets return 2 different values.
"Value with nr 1"
$MyValue2
}
}

Tools -MySwitch

$MyVar = Tools -MySwitchWithReturn
write-host "MyVar contains: " + $MyVar

$ReturnValues = Tools -MyParameter "test"

Write-host "The first value is: " + $ReturnValues[0]
Write-host "The second value is: " + $ReturnValues[1]


This returns:




My Switch was activated

MyVar contains: + My SwitchWithReturn was activated

The parameter has value: + test

The first value is: + Value with nr 1

The second value is: + Another value, 2




To recap the above, the param section is used to allow lots of control on how parameters can be passed to a function. This is not the only way, but allows for really cool things, so it is my preferred method.



To give anything back to the section that called the function, simply print it out to console. By typing "a string" or just typing the name of a variable as shown in the MyParameter section.



Lastly, if you want to quickly do something, here's an example of working with global variables. This is useful if you want to have a settings section at the top of your script:



$Global:MySetting = "This string is globally available."

Write-Host "Accessing the global: " + $Global:MySetting

function MyFunction ($MyParameter)
{
write-host "My Parameter is:" + $MyParameter
write-host "The global string is: " + $Global:MySetting
}

MyFunction "testing"


This returns:




Accessing the global: + This string is globally available.

My Parameter is: + testing

The global string is: + This string is globally available.




I hope this helps you. If not, please leave a comment. :)






share|improve this answer

































    0














    According to this Microsoft document about variable scope you need to declare the variable scope:



    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-5.1



    EXAMPLE:
    To create the same variable in the script scope, use the script scope modifier:



    $script:a = "one"


    The "report out" scope you are talking about would be "global". That makes the variable available outside of your script.






    share|improve this answer























      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "3"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1392924%2fscript-not-passing-variable-information-into-if-else-while-or-functions%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Summed up solution:



      Converted my script blocks to functions
      i.e.



      $variable = {code}


      to



      function variable {code}


      This worked for most of my script but the uninteded side affect was that my loop no longer worked. The solution for that was to convert the main function I was using to a global function.
      i.e.



      function global:functionName {code}


      After this everything is working exactly how it should. Thank you Pimp Juice IT, LPChip, and HackSlash for all your help.



      Working Script:



      #File Locations
      $rootPath = 'C:IT'
      $inLoc = 'Convert_Drop'
      $prossLoc = 'Processing'
      $outLoc = 'Converted PDF'

      #File types to include in PDF creation.
      $fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

      #Function Variables
      $inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
      $outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
      $runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
      $remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
      $remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

      #Folder Watching Variables
      $watcher = New-Object System.IO.FileSystemWatcher
      $watcher.Path = "$inPath"
      $watcher.Filter = "*.*"
      $watcher.IncludeSubdirectories = $true
      $watcher.EnableRaisingEvents = $true

      #Lone Vars
      $freshStart = $null
      $statusOld = $null
      $pathLoc = (Get-Item -Path ".").FullName

      #Pulls the last write time of a folder to compare later.
      function grabStatus
      {
      & CD $runPath
      $status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
      }

      #Get PDF name from Folder
      function grabFileName
      {
      $folder = get-childitem -Path $inPath -Directory -Name
      $global:fileName = $folder + ".pdf"
      }

      #Move all nested files to single folder.
      function moveFiles
      {
      Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
      }

      #Convert Nested files into single PDF
      function makePDF
      {
      & CD $runPath
      & magick $fileTypes $global:fileName
      }

      #Move final PDF
      function moveCmplt
      {
      Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
      }

      #Delete Old files
      function deleteOld
      {
      Remove-Item $remove1 -Recurse -Force
      Remove-Item $remove2 -Recurse -Force
      }

      #Set compare status to current status then fetches new status.
      function stats
      {
      $statusOld = $status
      $grabStatus
      sleep 10
      }

      #Exicute main conversion together.
      function global:runIt
      {
      grabStatus
      If ($status -eq $statusOld)
      {
      grabFileName
      moveFiles
      grabStatus
      If ($status -eq $statusOld)
      {
      makePDF
      grabStatus
      If ($status -eq $statusOld)
      {
      grabStatus
      moveCmplt
      If ($status -eq $statusOld)
      {
      deleteOld
      }
      }
      Else { stats }
      }
      Else { stats }
      }
      Else { stats }
      }

      #$runIt = { action }

      #First Time Start, Then Loop run.
      While ($freshStart -eq $null)
      {
      If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
      {
      }
      Else
      {
      global:runIt
      }
      $freshStart = "FreshStartDone!"
      }

      #Scan folder every 5 seconds for new content then run convert on change.
      Register-ObjectEvent $watcher "Created" -Action { global:runIt }
      while ($true) { sleep 5 }





      share|improve this answer
























      • Instead of making everything global you can pass arguments to the functions. For each variable that needs to be accessed inside the function an argument must be passed in. For each variable that is set and returned, you need a separate function. So you break it down by what each function returns, passing the result in to the next function until you get your final answer. stackoverflow.com/questions/5592531/…

        – HackSlash
        Jan 15 at 16:42











      • NOTE: If this is your final answer please hit the green check mark. You get points for the answer and people will stop coming here trying to help.

        – HackSlash
        Jan 15 at 16:44











      • Good to know! Green check mark has been clicked.

        – Tohny.Johnson
        Jan 16 at 17:46
















      2














      Summed up solution:



      Converted my script blocks to functions
      i.e.



      $variable = {code}


      to



      function variable {code}


      This worked for most of my script but the uninteded side affect was that my loop no longer worked. The solution for that was to convert the main function I was using to a global function.
      i.e.



      function global:functionName {code}


      After this everything is working exactly how it should. Thank you Pimp Juice IT, LPChip, and HackSlash for all your help.



      Working Script:



      #File Locations
      $rootPath = 'C:IT'
      $inLoc = 'Convert_Drop'
      $prossLoc = 'Processing'
      $outLoc = 'Converted PDF'

      #File types to include in PDF creation.
      $fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

      #Function Variables
      $inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
      $outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
      $runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
      $remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
      $remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

      #Folder Watching Variables
      $watcher = New-Object System.IO.FileSystemWatcher
      $watcher.Path = "$inPath"
      $watcher.Filter = "*.*"
      $watcher.IncludeSubdirectories = $true
      $watcher.EnableRaisingEvents = $true

      #Lone Vars
      $freshStart = $null
      $statusOld = $null
      $pathLoc = (Get-Item -Path ".").FullName

      #Pulls the last write time of a folder to compare later.
      function grabStatus
      {
      & CD $runPath
      $status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
      }

      #Get PDF name from Folder
      function grabFileName
      {
      $folder = get-childitem -Path $inPath -Directory -Name
      $global:fileName = $folder + ".pdf"
      }

      #Move all nested files to single folder.
      function moveFiles
      {
      Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
      }

      #Convert Nested files into single PDF
      function makePDF
      {
      & CD $runPath
      & magick $fileTypes $global:fileName
      }

      #Move final PDF
      function moveCmplt
      {
      Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
      }

      #Delete Old files
      function deleteOld
      {
      Remove-Item $remove1 -Recurse -Force
      Remove-Item $remove2 -Recurse -Force
      }

      #Set compare status to current status then fetches new status.
      function stats
      {
      $statusOld = $status
      $grabStatus
      sleep 10
      }

      #Exicute main conversion together.
      function global:runIt
      {
      grabStatus
      If ($status -eq $statusOld)
      {
      grabFileName
      moveFiles
      grabStatus
      If ($status -eq $statusOld)
      {
      makePDF
      grabStatus
      If ($status -eq $statusOld)
      {
      grabStatus
      moveCmplt
      If ($status -eq $statusOld)
      {
      deleteOld
      }
      }
      Else { stats }
      }
      Else { stats }
      }
      Else { stats }
      }

      #$runIt = { action }

      #First Time Start, Then Loop run.
      While ($freshStart -eq $null)
      {
      If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
      {
      }
      Else
      {
      global:runIt
      }
      $freshStart = "FreshStartDone!"
      }

      #Scan folder every 5 seconds for new content then run convert on change.
      Register-ObjectEvent $watcher "Created" -Action { global:runIt }
      while ($true) { sleep 5 }





      share|improve this answer
























      • Instead of making everything global you can pass arguments to the functions. For each variable that needs to be accessed inside the function an argument must be passed in. For each variable that is set and returned, you need a separate function. So you break it down by what each function returns, passing the result in to the next function until you get your final answer. stackoverflow.com/questions/5592531/…

        – HackSlash
        Jan 15 at 16:42











      • NOTE: If this is your final answer please hit the green check mark. You get points for the answer and people will stop coming here trying to help.

        – HackSlash
        Jan 15 at 16:44











      • Good to know! Green check mark has been clicked.

        – Tohny.Johnson
        Jan 16 at 17:46














      2












      2








      2







      Summed up solution:



      Converted my script blocks to functions
      i.e.



      $variable = {code}


      to



      function variable {code}


      This worked for most of my script but the uninteded side affect was that my loop no longer worked. The solution for that was to convert the main function I was using to a global function.
      i.e.



      function global:functionName {code}


      After this everything is working exactly how it should. Thank you Pimp Juice IT, LPChip, and HackSlash for all your help.



      Working Script:



      #File Locations
      $rootPath = 'C:IT'
      $inLoc = 'Convert_Drop'
      $prossLoc = 'Processing'
      $outLoc = 'Converted PDF'

      #File types to include in PDF creation.
      $fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

      #Function Variables
      $inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
      $outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
      $runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
      $remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
      $remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

      #Folder Watching Variables
      $watcher = New-Object System.IO.FileSystemWatcher
      $watcher.Path = "$inPath"
      $watcher.Filter = "*.*"
      $watcher.IncludeSubdirectories = $true
      $watcher.EnableRaisingEvents = $true

      #Lone Vars
      $freshStart = $null
      $statusOld = $null
      $pathLoc = (Get-Item -Path ".").FullName

      #Pulls the last write time of a folder to compare later.
      function grabStatus
      {
      & CD $runPath
      $status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
      }

      #Get PDF name from Folder
      function grabFileName
      {
      $folder = get-childitem -Path $inPath -Directory -Name
      $global:fileName = $folder + ".pdf"
      }

      #Move all nested files to single folder.
      function moveFiles
      {
      Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
      }

      #Convert Nested files into single PDF
      function makePDF
      {
      & CD $runPath
      & magick $fileTypes $global:fileName
      }

      #Move final PDF
      function moveCmplt
      {
      Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
      }

      #Delete Old files
      function deleteOld
      {
      Remove-Item $remove1 -Recurse -Force
      Remove-Item $remove2 -Recurse -Force
      }

      #Set compare status to current status then fetches new status.
      function stats
      {
      $statusOld = $status
      $grabStatus
      sleep 10
      }

      #Exicute main conversion together.
      function global:runIt
      {
      grabStatus
      If ($status -eq $statusOld)
      {
      grabFileName
      moveFiles
      grabStatus
      If ($status -eq $statusOld)
      {
      makePDF
      grabStatus
      If ($status -eq $statusOld)
      {
      grabStatus
      moveCmplt
      If ($status -eq $statusOld)
      {
      deleteOld
      }
      }
      Else { stats }
      }
      Else { stats }
      }
      Else { stats }
      }

      #$runIt = { action }

      #First Time Start, Then Loop run.
      While ($freshStart -eq $null)
      {
      If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
      {
      }
      Else
      {
      global:runIt
      }
      $freshStart = "FreshStartDone!"
      }

      #Scan folder every 5 seconds for new content then run convert on change.
      Register-ObjectEvent $watcher "Created" -Action { global:runIt }
      while ($true) { sleep 5 }





      share|improve this answer













      Summed up solution:



      Converted my script blocks to functions
      i.e.



      $variable = {code}


      to



      function variable {code}


      This worked for most of my script but the uninteded side affect was that my loop no longer worked. The solution for that was to convert the main function I was using to a global function.
      i.e.



      function global:functionName {code}


      After this everything is working exactly how it should. Thank you Pimp Juice IT, LPChip, and HackSlash for all your help.



      Working Script:



      #File Locations
      $rootPath = 'C:IT'
      $inLoc = 'Convert_Drop'
      $prossLoc = 'Processing'
      $outLoc = 'Converted PDF'

      #File types to include in PDF creation.
      $fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

      #Function Variables
      $inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
      $outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
      $runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
      $remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "*")"
      $remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "*")"

      #Folder Watching Variables
      $watcher = New-Object System.IO.FileSystemWatcher
      $watcher.Path = "$inPath"
      $watcher.Filter = "*.*"
      $watcher.IncludeSubdirectories = $true
      $watcher.EnableRaisingEvents = $true

      #Lone Vars
      $freshStart = $null
      $statusOld = $null
      $pathLoc = (Get-Item -Path ".").FullName

      #Pulls the last write time of a folder to compare later.
      function grabStatus
      {
      & CD $runPath
      $status = Get-Item $pathLoc | Foreach { $_.LastWriteTime }
      }

      #Get PDF name from Folder
      function grabFileName
      {
      $folder = get-childitem -Path $inPath -Directory -Name
      $global:fileName = $folder + ".pdf"
      }

      #Move all nested files to single folder.
      function moveFiles
      {
      Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
      }

      #Convert Nested files into single PDF
      function makePDF
      {
      & CD $runPath
      & magick $fileTypes $global:fileName
      }

      #Move final PDF
      function moveCmplt
      {
      Get-ChildItem -Path "$runPath*.pdf" -File | Move-Item -Destination $outPath
      }

      #Delete Old files
      function deleteOld
      {
      Remove-Item $remove1 -Recurse -Force
      Remove-Item $remove2 -Recurse -Force
      }

      #Set compare status to current status then fetches new status.
      function stats
      {
      $statusOld = $status
      $grabStatus
      sleep 10
      }

      #Exicute main conversion together.
      function global:runIt
      {
      grabStatus
      If ($status -eq $statusOld)
      {
      grabFileName
      moveFiles
      grabStatus
      If ($status -eq $statusOld)
      {
      makePDF
      grabStatus
      If ($status -eq $statusOld)
      {
      grabStatus
      moveCmplt
      If ($status -eq $statusOld)
      {
      deleteOld
      }
      }
      Else { stats }
      }
      Else { stats }
      }
      Else { stats }
      }

      #$runIt = { action }

      #First Time Start, Then Loop run.
      While ($freshStart -eq $null)
      {
      If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
      {
      }
      Else
      {
      global:runIt
      }
      $freshStart = "FreshStartDone!"
      }

      #Scan folder every 5 seconds for new content then run convert on change.
      Register-ObjectEvent $watcher "Created" -Action { global:runIt }
      while ($true) { sleep 5 }






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 14 at 23:55









      Tohny.JohnsonTohny.Johnson

      737




      737













      • Instead of making everything global you can pass arguments to the functions. For each variable that needs to be accessed inside the function an argument must be passed in. For each variable that is set and returned, you need a separate function. So you break it down by what each function returns, passing the result in to the next function until you get your final answer. stackoverflow.com/questions/5592531/…

        – HackSlash
        Jan 15 at 16:42











      • NOTE: If this is your final answer please hit the green check mark. You get points for the answer and people will stop coming here trying to help.

        – HackSlash
        Jan 15 at 16:44











      • Good to know! Green check mark has been clicked.

        – Tohny.Johnson
        Jan 16 at 17:46



















      • Instead of making everything global you can pass arguments to the functions. For each variable that needs to be accessed inside the function an argument must be passed in. For each variable that is set and returned, you need a separate function. So you break it down by what each function returns, passing the result in to the next function until you get your final answer. stackoverflow.com/questions/5592531/…

        – HackSlash
        Jan 15 at 16:42











      • NOTE: If this is your final answer please hit the green check mark. You get points for the answer and people will stop coming here trying to help.

        – HackSlash
        Jan 15 at 16:44











      • Good to know! Green check mark has been clicked.

        – Tohny.Johnson
        Jan 16 at 17:46

















      Instead of making everything global you can pass arguments to the functions. For each variable that needs to be accessed inside the function an argument must be passed in. For each variable that is set and returned, you need a separate function. So you break it down by what each function returns, passing the result in to the next function until you get your final answer. stackoverflow.com/questions/5592531/…

      – HackSlash
      Jan 15 at 16:42





      Instead of making everything global you can pass arguments to the functions. For each variable that needs to be accessed inside the function an argument must be passed in. For each variable that is set and returned, you need a separate function. So you break it down by what each function returns, passing the result in to the next function until you get your final answer. stackoverflow.com/questions/5592531/…

      – HackSlash
      Jan 15 at 16:42













      NOTE: If this is your final answer please hit the green check mark. You get points for the answer and people will stop coming here trying to help.

      – HackSlash
      Jan 15 at 16:44





      NOTE: If this is your final answer please hit the green check mark. You get points for the answer and people will stop coming here trying to help.

      – HackSlash
      Jan 15 at 16:44













      Good to know! Green check mark has been clicked.

      – Tohny.Johnson
      Jan 16 at 17:46





      Good to know! Green check mark has been clicked.

      – Tohny.Johnson
      Jan 16 at 17:46













      1














      As with most programming/script languages, variables have a scope. They can share data within the main code, or function, but not cross that boundary unless you tell the script it can do so.



      Although you can use global variables to set something globally, you can also work with functions if you do it well. Let me explain.



      Functions can get variables from outside the script and return them to the caller of the function. Powershell does functions a bit different than most scripts, because it treats a function as an object, which allows you to do cool things.



      Here is a small example of how to use a function with multiple variables:



      function Tools
      {

      param
      ( [switch]$MySwitch
      , [switch]$MySwitchWithReturn
      , [Parameter(Mandatory=$false)] [String] $MyParameter
      )


      if( $MySwitch )
      {
      write-host "My Switch was activated"
      }

      if( $MySwitchWithReturn )
      {
      "My SwitchWithReturn was activated"
      }

      if( $MyParameter )
      {
      Write-Host "The parameter has value: " + $MyParameter
      $MyValue2 = "Another value, 2"

      #Lets return 2 different values.
      "Value with nr 1"
      $MyValue2
      }
      }

      Tools -MySwitch

      $MyVar = Tools -MySwitchWithReturn
      write-host "MyVar contains: " + $MyVar

      $ReturnValues = Tools -MyParameter "test"

      Write-host "The first value is: " + $ReturnValues[0]
      Write-host "The second value is: " + $ReturnValues[1]


      This returns:




      My Switch was activated

      MyVar contains: + My SwitchWithReturn was activated

      The parameter has value: + test

      The first value is: + Value with nr 1

      The second value is: + Another value, 2




      To recap the above, the param section is used to allow lots of control on how parameters can be passed to a function. This is not the only way, but allows for really cool things, so it is my preferred method.



      To give anything back to the section that called the function, simply print it out to console. By typing "a string" or just typing the name of a variable as shown in the MyParameter section.



      Lastly, if you want to quickly do something, here's an example of working with global variables. This is useful if you want to have a settings section at the top of your script:



      $Global:MySetting = "This string is globally available."

      Write-Host "Accessing the global: " + $Global:MySetting

      function MyFunction ($MyParameter)
      {
      write-host "My Parameter is:" + $MyParameter
      write-host "The global string is: " + $Global:MySetting
      }

      MyFunction "testing"


      This returns:




      Accessing the global: + This string is globally available.

      My Parameter is: + testing

      The global string is: + This string is globally available.




      I hope this helps you. If not, please leave a comment. :)






      share|improve this answer






























        1














        As with most programming/script languages, variables have a scope. They can share data within the main code, or function, but not cross that boundary unless you tell the script it can do so.



        Although you can use global variables to set something globally, you can also work with functions if you do it well. Let me explain.



        Functions can get variables from outside the script and return them to the caller of the function. Powershell does functions a bit different than most scripts, because it treats a function as an object, which allows you to do cool things.



        Here is a small example of how to use a function with multiple variables:



        function Tools
        {

        param
        ( [switch]$MySwitch
        , [switch]$MySwitchWithReturn
        , [Parameter(Mandatory=$false)] [String] $MyParameter
        )


        if( $MySwitch )
        {
        write-host "My Switch was activated"
        }

        if( $MySwitchWithReturn )
        {
        "My SwitchWithReturn was activated"
        }

        if( $MyParameter )
        {
        Write-Host "The parameter has value: " + $MyParameter
        $MyValue2 = "Another value, 2"

        #Lets return 2 different values.
        "Value with nr 1"
        $MyValue2
        }
        }

        Tools -MySwitch

        $MyVar = Tools -MySwitchWithReturn
        write-host "MyVar contains: " + $MyVar

        $ReturnValues = Tools -MyParameter "test"

        Write-host "The first value is: " + $ReturnValues[0]
        Write-host "The second value is: " + $ReturnValues[1]


        This returns:




        My Switch was activated

        MyVar contains: + My SwitchWithReturn was activated

        The parameter has value: + test

        The first value is: + Value with nr 1

        The second value is: + Another value, 2




        To recap the above, the param section is used to allow lots of control on how parameters can be passed to a function. This is not the only way, but allows for really cool things, so it is my preferred method.



        To give anything back to the section that called the function, simply print it out to console. By typing "a string" or just typing the name of a variable as shown in the MyParameter section.



        Lastly, if you want to quickly do something, here's an example of working with global variables. This is useful if you want to have a settings section at the top of your script:



        $Global:MySetting = "This string is globally available."

        Write-Host "Accessing the global: " + $Global:MySetting

        function MyFunction ($MyParameter)
        {
        write-host "My Parameter is:" + $MyParameter
        write-host "The global string is: " + $Global:MySetting
        }

        MyFunction "testing"


        This returns:




        Accessing the global: + This string is globally available.

        My Parameter is: + testing

        The global string is: + This string is globally available.




        I hope this helps you. If not, please leave a comment. :)






        share|improve this answer




























          1












          1








          1







          As with most programming/script languages, variables have a scope. They can share data within the main code, or function, but not cross that boundary unless you tell the script it can do so.



          Although you can use global variables to set something globally, you can also work with functions if you do it well. Let me explain.



          Functions can get variables from outside the script and return them to the caller of the function. Powershell does functions a bit different than most scripts, because it treats a function as an object, which allows you to do cool things.



          Here is a small example of how to use a function with multiple variables:



          function Tools
          {

          param
          ( [switch]$MySwitch
          , [switch]$MySwitchWithReturn
          , [Parameter(Mandatory=$false)] [String] $MyParameter
          )


          if( $MySwitch )
          {
          write-host "My Switch was activated"
          }

          if( $MySwitchWithReturn )
          {
          "My SwitchWithReturn was activated"
          }

          if( $MyParameter )
          {
          Write-Host "The parameter has value: " + $MyParameter
          $MyValue2 = "Another value, 2"

          #Lets return 2 different values.
          "Value with nr 1"
          $MyValue2
          }
          }

          Tools -MySwitch

          $MyVar = Tools -MySwitchWithReturn
          write-host "MyVar contains: " + $MyVar

          $ReturnValues = Tools -MyParameter "test"

          Write-host "The first value is: " + $ReturnValues[0]
          Write-host "The second value is: " + $ReturnValues[1]


          This returns:




          My Switch was activated

          MyVar contains: + My SwitchWithReturn was activated

          The parameter has value: + test

          The first value is: + Value with nr 1

          The second value is: + Another value, 2




          To recap the above, the param section is used to allow lots of control on how parameters can be passed to a function. This is not the only way, but allows for really cool things, so it is my preferred method.



          To give anything back to the section that called the function, simply print it out to console. By typing "a string" or just typing the name of a variable as shown in the MyParameter section.



          Lastly, if you want to quickly do something, here's an example of working with global variables. This is useful if you want to have a settings section at the top of your script:



          $Global:MySetting = "This string is globally available."

          Write-Host "Accessing the global: " + $Global:MySetting

          function MyFunction ($MyParameter)
          {
          write-host "My Parameter is:" + $MyParameter
          write-host "The global string is: " + $Global:MySetting
          }

          MyFunction "testing"


          This returns:




          Accessing the global: + This string is globally available.

          My Parameter is: + testing

          The global string is: + This string is globally available.




          I hope this helps you. If not, please leave a comment. :)






          share|improve this answer















          As with most programming/script languages, variables have a scope. They can share data within the main code, or function, but not cross that boundary unless you tell the script it can do so.



          Although you can use global variables to set something globally, you can also work with functions if you do it well. Let me explain.



          Functions can get variables from outside the script and return them to the caller of the function. Powershell does functions a bit different than most scripts, because it treats a function as an object, which allows you to do cool things.



          Here is a small example of how to use a function with multiple variables:



          function Tools
          {

          param
          ( [switch]$MySwitch
          , [switch]$MySwitchWithReturn
          , [Parameter(Mandatory=$false)] [String] $MyParameter
          )


          if( $MySwitch )
          {
          write-host "My Switch was activated"
          }

          if( $MySwitchWithReturn )
          {
          "My SwitchWithReturn was activated"
          }

          if( $MyParameter )
          {
          Write-Host "The parameter has value: " + $MyParameter
          $MyValue2 = "Another value, 2"

          #Lets return 2 different values.
          "Value with nr 1"
          $MyValue2
          }
          }

          Tools -MySwitch

          $MyVar = Tools -MySwitchWithReturn
          write-host "MyVar contains: " + $MyVar

          $ReturnValues = Tools -MyParameter "test"

          Write-host "The first value is: " + $ReturnValues[0]
          Write-host "The second value is: " + $ReturnValues[1]


          This returns:




          My Switch was activated

          MyVar contains: + My SwitchWithReturn was activated

          The parameter has value: + test

          The first value is: + Value with nr 1

          The second value is: + Another value, 2




          To recap the above, the param section is used to allow lots of control on how parameters can be passed to a function. This is not the only way, but allows for really cool things, so it is my preferred method.



          To give anything back to the section that called the function, simply print it out to console. By typing "a string" or just typing the name of a variable as shown in the MyParameter section.



          Lastly, if you want to quickly do something, here's an example of working with global variables. This is useful if you want to have a settings section at the top of your script:



          $Global:MySetting = "This string is globally available."

          Write-Host "Accessing the global: " + $Global:MySetting

          function MyFunction ($MyParameter)
          {
          write-host "My Parameter is:" + $MyParameter
          write-host "The global string is: " + $Global:MySetting
          }

          MyFunction "testing"


          This returns:




          Accessing the global: + This string is globally available.

          My Parameter is: + testing

          The global string is: + This string is globally available.




          I hope this helps you. If not, please leave a comment. :)







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 11 at 8:43

























          answered Jan 11 at 8:33









          LPChipLPChip

          35.7k55185




          35.7k55185























              0














              According to this Microsoft document about variable scope you need to declare the variable scope:



              https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-5.1



              EXAMPLE:
              To create the same variable in the script scope, use the script scope modifier:



              $script:a = "one"


              The "report out" scope you are talking about would be "global". That makes the variable available outside of your script.






              share|improve this answer




























                0














                According to this Microsoft document about variable scope you need to declare the variable scope:



                https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-5.1



                EXAMPLE:
                To create the same variable in the script scope, use the script scope modifier:



                $script:a = "one"


                The "report out" scope you are talking about would be "global". That makes the variable available outside of your script.






                share|improve this answer


























                  0












                  0








                  0







                  According to this Microsoft document about variable scope you need to declare the variable scope:



                  https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-5.1



                  EXAMPLE:
                  To create the same variable in the script scope, use the script scope modifier:



                  $script:a = "one"


                  The "report out" scope you are talking about would be "global". That makes the variable available outside of your script.






                  share|improve this answer













                  According to this Microsoft document about variable scope you need to declare the variable scope:



                  https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-5.1



                  EXAMPLE:
                  To create the same variable in the script scope, use the script scope modifier:



                  $script:a = "one"


                  The "report out" scope you are talking about would be "global". That makes the variable available outside of your script.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 10 at 21:04









                  HackSlashHackSlash

                  1,9971720




                  1,9971720






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Super User!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1392924%2fscript-not-passing-variable-information-into-if-else-while-or-functions%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Index of /

                      Tribalistas

                      Listed building