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?
animuson
  • 53,861
  • 28
  • 137
  • 147
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190

2 Answers2

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

Richard
  • 106,783
  • 21
  • 203
  • 265
konung
  • 6,908
  • 6
  • 54
  • 79
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
}
animuson
  • 53,861
  • 28
  • 137
  • 147
BlueSam
  • 1,888
  • 10
  • 17
  • 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 Nov 13 '09 at 23:00
  • 2
    `$dateFileName = "{0:MMddyyyy}.dat" -f (Get-Date)` would be a little bit shorter and less convoluted. – Joey Nov 14 '09 at 01:13
  • 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 Nov 15 '09 at 05:22
  • 3
    `$dateFileName = "$(get-date -f MMddyyyy).dat"` would be even shorter and less convoluted. :-) – Keith Hill Nov 16 '09 at 03:02
  • 1
    You should be using the cmdlet Test-Path in PowerShell, instead of using the .NET File.Exists directly – Thiago Silva Aug 05 '13 at 16:25
  • See also: [A better way to check if a file exists or not in PowerShell](http://stackoverflow.com/a/31888581/450913) – orad Aug 08 '15 at 17:38