I am practicing Powershell in VSCode. I have noticed that when I hit F5 to run my script, Powershell runs the previous version of the script (before my changes). I am definitely saving the file after my edits. So, for example, I might change the text in this line:
Add-Content -Path "D:\Text_File.txt" -value "$_ - MP3 File count is: $Cnt"
But it will continue to show the same output until I run it a second time.
This is the script I am using in case it is relevant:
Param(
[string]$Path = 'D:\WMA - BU of wma music files',
[string]$DestinationPath = "D:\WMA-Only",
[string]$OutputFileDest = "D:\Text_File.txt"
)
$MainDirList = Get-ChildItem -Path $Path -Directory | ForEach-Object {$_.FullName}
$MainDirList | Out-File -FilePath D:\Text_File.txt
$MainDirList | WriteFolder
function WriteFolder
{
process
{
$FilteredList = Get-ChildItem -Path $_ -Force -Recurse -Filter "*.mp3"
$Cnt = $FilteredList.count
Add-Content -Path "D:\Text_File.txt" -value "$_ - MP3 File count is: $Cnt"
}
}
Visual Studio code version is 1.62.2 Powershell extension is v2021.10.2
I am wondering if I am meant to clear variables or the like at the end of a script? I am viewing the output in the latest version of notepad
CodePudding user response:
Could it be because you've defined one function inside another function? Normally when you run a script, it finds any Functions and pre-processes them before running the script. But in your case, it only processes the outer function, which only creates the inner function when it's run.
I'm not sure what your parent function is called, but you could try just having the two functions side-by-side:
Function myFunction{
Param(
[string]$Path = 'D:\WMA - BU of wma music files',
[string]$DestinationPath = "D:\WMA-Only",
[string]$OutputFileDest = "D:\Text_File.txt"
)
Process{
$MainDirList = Get-ChildItem -Path $Path -Directory | ForEach-Object {$_.FullName}
$MainDirList | Out-File -FilePath D:\Text_File.txt
$MainDirList | WriteFolder
}
}
function WriteFolder
{
process
{
$FilteredList = Get-ChildItem -Path $_ -Force -Recurse -Filter "*.mp3"
$Cnt = $FilteredList.count
Add-Content -Path "D:\Text_File.txt" -value "$_ - MP3 File count is: $Cnt"
}
}
Or else you could move the WriteFolder function into its own Powershell module (*.psm1) and load it in your main script:
Import-Module "WriteFolder.psm1" -Force
The -Force
parameter is optional, but if you're regularly changing the module file you'll need it to ensure the updates are loaded, rather than just caching the old version of the module.