tags:

views:

613

answers:

2

This may be simple question, but I am new to Powershell and could not find a way to do it. Basically, I have to run a bat process if a specified file does not exist. The file name is in a patten like "mmddyyy.dat" in a folder, where mmddyyyy is today's month, day(0 prefix if < 10) and year. Pusdo codes would be something like this:

 $File = "C:\temp\*mmddyyyy*.dat" # how to parse Get-Date mmddyyyy and build this pattern?
 #if $File exist # check any file exist?
     .\myBatch.bat  # run the bat file, can I run it in hidden mode?

By the way, any good site with example or tutorial information about PowerShell?

+2  A: 

The command is :

`test-path .\example.txt`

Returns True or False

For Docs how about official documentation? That's where I check. http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx

also eggheadcafe.com has a lot of examples: http://www.eggheadcafe.com/conversationlist.aspx?groupid=2464&amp;activetopiccard=0

Although I haven't tried regex in poweshell this may help you:

http://www.eggheadcafe.com/software/aspnet/33029659/regex-multiline-question.aspx

Nick Gorbikoff
how to guild a string based on today's date, in a pattern mmddyyyy? For example "11132009" for today.
David.Chu.ca
+1  A: 

I'd recommend making a reusable function like the following:

function GetDateFileName
{   
    $date = Get-Date
    $dateFileName = "{0:d2}{1:d2}{2}.dat" -f $date.month,$date.day,$date.year
    return $dateFileName
}
$fileName = GetDateFileName
$filePath = "c:\temp\" + $fileName

if([IO.File]::Exists($filePath) -ne $true)
{
 #do whatever
}

To answer your second question, PowerGUI Script Editor (link) is a must for someone starting out in PowerShell mainly for the syntax highlighting and intellisense. Hope this helps!

BlueSam
If I want to add two parameters as args to the function and return the result in the format of "{0}{1:d2}{2:d2}{3}{4}" -f arg[0],...,arg[1]. How Can I make the call this function? I got failure by calling GetDateFleName("C:\temp\*", "*.dat").
David.Chu.ca
`$dateFileName = "{0:MMddyyyy}.dat" -f (Get-Date)` would be a little bit shorter and less convoluted.
Joey
You add the parameters to a function like so:function foo([string]$foo = "foo", [string]$bar = "bar"){ Write-Host "Arg: $foo"; Write-Host "Arg: $bar";}and you call the function like so:foo "param1" "param2"
BlueSam
`$dateFileName = "$(get-date -f MMddyyyy).dat"` would be even shorter and less convoluted. :-)
Keith Hill