I have a large list of hostnames I need to ping to see if they are pinging or not. I am new at scripting but I managed to figure this much out but getting error when I run this script, I run the script using "PowerShell.exe script.ps > output.csv".
Error Below:
"pinghost.ps : The term 'pinghost.ps' is not recognized as the name of a cmdlet function script file or operable
program. Check the spelling of the name or if a path was included verify that the path is correct and try again.
At line:1 char:1
#NAME?
~~~~~~~~~~~
CategoryInfo: ObjectNotFound: (pinghost.ps:String) [] CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException :"
Code below:
$names = Get-content ".\hnames.txt"
foreach ($name in $names){
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
Write-Host "$name,up"
}
else{
Write-Host "$name,down"
}
}
CodePudding user response:
PowerShell will attempt to resolve unqualified file paths passed as command line arguments relative to its working directory - if you launch PowerShell from the Run prompt or as a scheduled task running as a specific local user account, the working directory will default to the users profile folder.
Either pass a rooted file path:
powershell.exe -File C:\Users\Akshay\path\to\pinghost.ps1
Or a file path that's relative to the expected working directory (using /
instead of \
will prevent PowerShell from interpreting the path as a module-qualified command name):
powershell.exe -File path/to/pinghost.ps1
In order to make PowerShell's provider cmdlets correctly resolve the hnames.txt
file relative to the location of the script itself, prepend the path with the $PSScriptRoot
automatic variable:
$names = Get-content (Join-Path $PSScriptRoot hnames.txt)
foreach ($name in $names){
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
Write-Host "$name,up"
}
else{
Write-Host "$name,down"
}
}
Now it will work as long as the script and text file are in the same directory, regardless of where you call it from.