I am trying to run the below PowerShell script from a job step:
Duplicate of http://powershell.com/cs/forums/p/22865/50611.aspx#50611
It is not duplicate, the other one is about using environment variable in the same script. This one is about connecting to sql server without it.
I imagine that this is because SQL Agent is running on an instance, but because you didn't specify it, it's trying to connect to the hostname.
I have a Windows server with two instances, Default (sql2008) and the R2 instance (sql2008\sql2k8r2)
When I run my job that just consists of $ServerName = Invoke-Sqlcmd -query "SELECT @@ServerName" on sql2008\sql2k8r2's agent, the job is a success, but returns sql2008. When I turned off the sql2008 instance, the job failed.
Please see my answer to your previous question. All in all, the approach you tried above is not recommended. I don't do much with PowerShell in SQL Agent (this was actually just the second time I've worked with it, I don't like how it takes so long to initiate), so I'm not sure what's the best way to get your server name. I did just do some digging and it apparently uses sqlps.exe, so you can try running sqlps.exe on the server itself as the SQL Agent service account, and you'll have an interactive shell to test with.
I found a beautiful way to solve this problem for SQL jobs, you just need to use this command to extract the instance name:
$Srv = '$(ESCAPE_SQUOTE(SRVR))'
This won't work from Powershell window, only in a job step.