2

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

$LogFile = ".\userLoad.log"
$Date = Get-Date
Try
{
    $Request = [System.Net.WebRequest]::Create("http://dxscrumassist.zhi.com/maintenance/loadusers.aspx")
    $Response = $Request.GetResponse()
    $LogString = "$Date - User Load Success"
    $Response.Close()
}
Catch
{
    $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?

1
  • What folder are you trying to run it from? Oct 15, 2013 at 15:42

2 Answers 2

2

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).

3

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.

1
  • 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, 2013 at 16:11

You must log in to answer this question.

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