9

This may be a simple question, but I am new to PowerShell and could not find a way to do it. Basically, I have to run a .BAT file 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. Pseudo 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?

2 Answers 2

23

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&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

Sign up to request clarification or add additional context in comments.

1 Comment

how to guild a string based on today's date, in a pattern mmddyyyy? For example "11132009" for today.
7

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

function GetDateFileName
{   
    $date = Get-Date
    $dateFileName = "$(get-date -f MMddyyyy).dat"
    return $dateFileName
}
$fileName = GetDateFileName
$filePath = "c:\temp\" + $fileName

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

6 Comments

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").
$dateFileName = "{0:MMddyyyy}.dat" -f (Get-Date) would be a little bit shorter and less convoluted.
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"
$dateFileName = "$(get-date -f MMddyyyy).dat" would be even shorter and less convoluted. :-)
You should be using the cmdlet Test-Path in PowerShell, instead of using the .NET File.Exists directly
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.