A blank line or extra new-line in the txt file would be primary suspect. Add a test to see if $server.trim() -ne "" before you do the Test-Path.
Powershell loop if else problem
Hello,
Im trying to create a loop to copy and install certificates on remote computers:
$servers = Get-Content "D:\scripts\InstallCertRemote\servers.txt"
$LocalPath = "D:\Temp\*.*"
$RemotePath = "D$\Temp\certificates"
$logfile = "D:\scripts\InstallCertRemote\logfile.txt"
ForEach ($server in $servers) {
Get-Date | out-file $logfile -Append
if ( Test-Path -Path "\\$server\$RemotePath" )
{
Write-host Copying files on $server
(copy-item -Path $LocalPath -Destination "\\$server\$RemotePath" -Verbose 4>&1 | out-file $logfile -Append)
Start-Sleep 2
Write-host Installing certificate on $server
(Invoke-Command -ComputerName "$server" -ScriptBlock {Import-Certificate -FilePath "D:\temp\certificates\certificate.cer" -CertStoreLocation Cert:\LocalMachine\ROOT} -Verbose 4>&1 | out-file $logfile -Append)
}
else
{
Write-Warning "$Remotepath not found in $server"
}
Read-Host -Prompt "Press any key to install next server"
}
The loop works fine. But I put a fake server name in the servers.txt to check if warning is working, and this is the output:
*Copying files on SERVER1
Installing certificate SERVER1
Press any key to install next server:
WARNING: D$\Temp\certificates not found in NAMEFAKESERVER
Press any key to install next server:
Copying files on SERVER2
Installing certificate SERVER2
Press any key to install next server:
WARNING: D$\Temp\certificates not found in
Press any key to install next server:
*
Why appears the last warning > "WARNING: D$\Temp\certificates not found in"
Maybe the loop is not be right?
Thanks,
Windows for business | Windows Server | User experience | PowerShell
Answer accepted by question author
2 additional answers
Sort by: Most helpful
-
RAN55 181 Reputation points2021-11-26T07:27:23.987+00:00 Both answers are correct, there was a blank line after last server. And the variable is correct also.
Thanks !
-
Rich Matheisen 48,116 Reputation points
2021-11-25T19:56:49.307+00:00 The problem happens because the Read-Host returns an empty line (if all you did was press the "Enter" key), but you haven't assigned the output of Read-Host to any variable. What happens then is that the output of Read-Host is emitted into the "Success" stream and becomes the next item to be processed by your "ForEach".
Try entering "XXXXXX" instead of just pressing the Enter key and see if the next warning is that certificates can't be found in "XXXXXX".
Changing your Read-Host to this should fix the problem:
$x = Read-Host -Prompt "Press any key to install next server"