Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a simple powershell script that opens a ur and logs whether it was successful:

$LogFile = ".\userLoad.log"
$Date = Get-Date
    $Request = [System.Net.WebRequest]::Create("")
    $Response = $Request.GetResponse()
    $LogString = "$Date - User Load Success"
    $LogString = "$Date - User Load Failure"
Add-content $LogFile -value $LogString

When I run the program from PowerShell ISE it works fine and logs as expected:

powershell.exe -executionpolicy bypass -file C:\AAA\loadUsers.ps1

When I run the exact same file from the Windows command line I am not getting a log file entry. What am I doing wrong?

share|improve this question
What folder are you trying to run it from? – Ƭᴇcʜιᴇ007 Oct 15 '13 at 15:42
up vote 2 down vote accepted

Here's the thing, you're telling powershell to write to ".\log.log" and it is. It's just I don't think it's writing where you expect it to be. It's writing to where get-location is, which is actually a default that's usually your user directory (or that of the account executing it). Check .\users\<username>\log.log and see if it's there. Now, what you want is a way to get the current script execution directory and write your output there. You can do this like so:

function Get-ScriptDirectory
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
$ScriptDir = Get-ScriptDirectory

In your case, $LogFile would actually be:

$LogFile = "$ScriptDir\log.log"

Check out Invoke-WebRequest :) You might find it easier for web requests. You might also want to consider adding a finally to your try\catch so that it's a try\catch\finally. The finally block always runs and you can use it to log script execution (in this instance).

share|improve this answer

My suspicion is that it is a working directory issue. Look in C:\Windows\System32 and see if your log is there. Or give and explicit path to where you want the log rather than using a relative path.

share|improve this answer
I agree with you about the working directory, but I think it's probably defaulting to the user directory or root. +1 – Colyn1337 Oct 15 '13 at 16:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .