2009-11-13 202 views
9

這可能是一個簡單的問題,但我是PowerShell的新手,無法找到解決方法。基本上,如果指定的文件不存在,我必須運行.BAT文件。文件名稱的格式類似於文件夾中的「mmddyyy .dat」,其中mmddyyyy是今天的月份,日期(如果是< 10,則爲0前綴)和年份。僞代碼將是這樣的:檢查文件是否存在並在PowerShell中運行批處理文件?

$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? 

回答

7

我建議你做可重複使用的功能如下:

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 
} 
+0

如果我想將兩個參數作爲參數添加到函數中,並以「{0} {1:d2} {2:d2} {3} {4}」-f arg [0],的格式返回結果。 ..,ARG [1]。我怎樣才能使這個功能?我通過調用GetDateFleName(「C:\ temp \ *」,「* .dat」)失敗。 – 2009-11-13 23:00:21

+2

'$ dateFileName =「{0:MMddyyyy} .dat」-f(Get-Date)'會稍微短一些,不太複雜。 – Joey 2009-11-14 01:13:24

+0

您的參數添加到功能,像這樣: 函數foo([字符串] $ FOO = 「富」,[字符串] $欄= 「巴」) { 寫主機 「精氨酸:$ foo」 的; 寫主機「Arg:$ bar」; } 和調用功能,像這樣: 富「參數1」「參數2」 – BlueSam 2009-11-15 05:22:01

23

的命令是:

test-path .\example.txt 

返回TRUE或FALSE

對於如何對官方文檔的文檔?這就是我檢查的地方。 http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx

也eggheadcafe.com有很多例子: http://www.eggheadcafe.com/conversationlist.aspx?groupid=2464&activetopiccard=0

雖然我還沒有嘗試過的正則表達式中poweshell這可以幫助你:

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

+0

how t根據今天的日期公會一個字符串,模式爲mmddyyyy?例如今天的「11132009」。 – 2009-11-13 22:32:23

相關問題