1

I'm a newbie to PowerShell. What's wrong with my script below? It's not wanting to emit the value of $config. However, when I wrap that command in double quotes, everything looks okay.

param($config, $logfolder)

# Must run log analysis in chronological order.
ls $logfolder | Sort-Object LastWriteTime | % {
    perl D:\Websites\_awstats\wwwroot\cgi-bin\awstats.pl -LogFile="$($_.FullName)" -config=$config update
}

# Execute with - .\regen-logs.ps1 webgenesis "C:\inetpub\logs\LogFiles\W3SVC5"
# Returns for each file - Error: Couldn't open config file "awstats.config.conf" nor "awstats.conf" after searching in path "D:\Websites\_awstats\wwwroot\cgi-bin,/etc/awstats,/usr/local/etc/awstats,/etc,/etc/opt/awstats": No such file or directory

As-is, what gets emitted and executed seems to have "-config=$config" passed as an argument. At least, that's my best guess. I don't know if $_ is working correctly either.

If I put quotes around the perl command like so, I get the command I do want to execute.

ls $logfolder | Sort-Object LastWriteTime | % {
    "perl D:\Websites\_awstats\wwwroot\cgi-bin\awstats.pl -LogFile=`"$($_.FullName)`" -config=$config update"
}

# Outputs for each log file something like - perl D:\Websites\_awstats\wwwroot\cgi-bin\awstats.pl -LogFile="C:\inetpub\logs\LogFiles\W3SVC5\u_ex110602.log" -config=webgenesis update
Samantha Branham
  • 7,350
  • 2
  • 32
  • 44

3 Answers3

3

If putting quotes around it produces the correct commandline, one way to execute the contents of a string is with Invoke-Expression (alias iex):

$v = "myexe -myarg1 -myarg2=$someVar"
iex $v
Joel B Fant
  • 24,406
  • 4
  • 66
  • 67
1

Put double quotes around "-config=$config". Without this, PowerShell will interpret -config=$config as one string argument that just happens to contain a $ sign in it.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
0

I think you need to start your perl command out with & so that PowerShell interprets things as a command and not a string.

& perl D:\Websites\_awstats\wwwroot\cgi-bin\awstats.pl -LogFile=`"$($_.FullName)`" -config=$config update

Also, see: Run a program in a foreach

Community
  • 1
  • 1
Scott Saad
  • 17,962
  • 11
  • 63
  • 84
  • The term 'perl D:\Websites\_awstats\wwwroot\cgi-bin\awstats.pl -LogFile="D:\Websites\_awstats\update-awstats.bat" -config= update' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling o f the name, or if a path was included, verify that the path is correct and try again. – Samantha Branham Jun 02 '11 at 20:56
  • @Stuart-Branham Sorry about that. I messed up the quoting. Thinking this should work. – Scott Saad Jun 02 '11 at 21:41
  • The call operator "&" can't handle compound expressions like that. See Joel's answer. – zdan Jun 02 '11 at 21:50