【问题标题】:Check if file exist and run a batch file in PowerShell?检查文件是否存在并在 PowerShell 中运行批处理文件?
【发布时间】:2017-02-16 01:23:59
【问题描述】:

这可能是一个简单的问题,但我是 PowerShell 新手,找不到解决方法。基本上,如果指定的文件不存在,我必须运行一个 .BAT 文件。文件名位于文件夹中的“mmddyyy.dat”之类的模式中,其中 mmddyyyy 是今天的月份、日期(如果

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

【问题讨论】:

    标签: powershell


    【解决方案1】:

    命令是:

    test-path .\example.txt
    

    返回真或假

    对于 Docs,官方文档如何?那是我检查的地方。 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

    【讨论】:

    • 如何根据今天的日期以 mmddyyyy 模式创建字符串?例如今天的“11132009”。
    【解决方案2】:

    我建议创建一个可重用的函数,如下所示:

    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
    }
    

    【讨论】:

    • 如果我想在函数中添加两个参数作为 args 并以“{0}{1:d2}{2:d2}{3}{4}”的格式返回结果 - f arg[0],...,arg[1]。我怎样才能调用这个函数?我调用 GetDateFleName("C:\temp*", "*.dat") 失败了。
    • $dateFileName = "{0:MMddyyyy}.dat" -f (Get-Date) 会更短一些,不那么复杂。
    • 您将参数添加到函数中,如下所示: function foo([string]$foo = "foo", [string]$bar = "bar") { Write-Host "Arg: $foo ";写主机 "Arg: $bar"; } 然后你像这样调用函数: foo "param1" "param2"
    • $dateFileName = "$(get-date -f MMddyyyy).dat" 会更短,更简洁。 :-)
    • 您应该在 PowerShell 中使用 cmdlet Test-Path,而不是直接使用 .NET File.Exists
    猜你喜欢
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 2013-04-30
    • 2015-07-09
    • 1970-01-01
    相关资源
    最近更新 更多