.ps1 worked in PS shell and IDE; failed when called from .bat

I have a simple setup for a Windows local user logon script.

There are three files:
(a) a batch (LogonHello.bat) file, invoked from the logon profile.
(b) a PowerShell (HelloScript.ps1) file called from the .bat file
*** HelloScript Get-Content from c:\LogonScripts\Phrases.txt
(c) a text file (Phrases.txt) contains phrases.

HelloScript.ps1 ran fine in PowerShell window and in PowerShell ISE. However when the HelloScript.ps1 is called from the LogonHello.bat, an error occurred. Based on the error message, PowerShell shortened the fully qualified -path “c:\LogonScripts\Phrases.txt” to “c:\Phrases.txt”. As a test, I put “Phrases.txt” in C:, the script worked as expected.


PowerShell shortened the path of the input file (Phrase.txt). The error is a follow:
Get-Content : Cannot find path ‘C:\Phrases.txt’ because it does not exist.
At \Localhost\Netlogon\HelloScript.ps1:18 char:12

  • $phrases = Get-Content Phrases.txt
  •        ~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (C:\Phrases.txt:String) [Get-Content], ItemNotFoundException
    • FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

It seemed to be a bug in PowerShell.

Here’s the code:
(A) LogonHello.bat file:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File \Localhost\Netlogon\HelloScript.ps1 -WindowStyle Hidden

(B) HelloScript.ps1 file

Add-Type -AssemblyName System.speech
$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
$voice = $speak.GetInstalledVoices().VoiceInfo | where {$_.gender -like '*Female*'}
if ( (Get-Date -UFormat %p) -eq "AM" ) {
  $speak.Speak('Good Morning Human') 
} ELSE {
  $timeOfDay = Get-Date
  if ($timeOfDay -gt 6) {
    $speak.Speak('Good Evening Human')
  } ELSE {
    $speak.Speak('Good Afternoon Human') 
  }
} 
$phrases = Get-Content -path 'c:\LogonScripts\Phrases.txt'
$phrase = Get-Random $phrases
$speak.Speak($phrase)


(C) Phrases.txt
“Stupid is as stupid does”
“Idiot is as idiot does”

You could try to explicitly set the working directory with something like this:

Push-Location -Path c:\LogonScripts</pre>

Thanks for the idea.
I finally figured out the error. It’s a human error. It’s in the LogonHello.bat file.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File \Localhost\Netlogon\HelloScript.ps1 -WindowStyle Hidden
The Localhost share [folder] name “Netlogon” (as required by Windows logon script) was pointing to a different folder. That folder had a bad HelloScript.ps1 in it.