質問

I am trying to create a powershell script that will open an HTA file, but only if it can see an HTML file in the same folder.

I have the following script from another question on stackoverflow, but cannot seem to get it to work--can someone please point me in the right direction?

The first part determines the name of the HTML file (called Textbox1.html). The next part sets the file path as \\network location\Textbox1.html. Then the final part says that if Textbox1.html exists, open \\network location\HTA3.hta.

function GetTextboxExists
{
  $TextboxExists = "$Textbox1.html"
  return $TextboxExists
}
$filename = TextboxExists
$filePath = "\\*****path to file" + $filename

if ([IO.File]::Exists($filePath) -ne $true)
{
  & "\\*****path to file\HTA3.hta"
}
役に立ちましたか?

解決

I'm not sure why you're using a separate function to determine the name of the .html file, but in any case, if you want to open one file based on whether another file exists, it's as simple as

if (Get-Item -ea SilentlyContinue <path of file to check for>) {
  Invoke-Item <path of file to open>
}

(Assuming that by "open" you mean the default action associated with the file extension - which is what you're essentially doing when you use & "<path>".)

So, to put it in terms of your code more specifically:

if (Get-Item -ea SilentlyContinue "\\*****path to file\$Textbox1.html") {
    Invoke-Item '\\*****path to file\HTA3.hta'
}
  • You didn't specify what $Textbox1 is and how it's defined, but I'm inferring that it contains the base name of the .html file.

  • I single-quoted the path argument to Invoke-Item because you show a static path to the .hta file; if you're using any variables to determine the path, be sure to change to double quotes.

  • The -ne operator means "not equal", so in fact you're trying to open the .hta file only if the .html file doesn't exist. The code you have, although overly cumbersome, does work other than that, so that's probably the reason it isn't working for you.

  • Another tip is that you don't need to test a boolean condition for equality or inequality. if (<boolean> -eq $true) { ... is the same as if (<boolean>) { ..., and likewise if (<boolean> -ne $true) { ... is the same as if (! <boolean>) { .... So, your if statement using using the .NET class (which you don't really need) should be simply if ([IO.File]::Exists($filePath) { ....

他のヒント

An easy way, would be to see if there are txt files. I chose to use an int, but a Boolean would work too.

$files

Get-Content c:\Users\Athomsfere\Desktop\ | ForEach-Object `
    {
        if ($_.Extension -eq ".txt")
        {
            $files++  #Could also do $files = true
        }
    }

    if ($files -gt 0) 
      {
        Write-Host "Open HTA"
        #Start HTA code here.
      }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top