Powershell 脚本跨计算机和本地打开文件

Powershell 脚本跨计算机和本地打开文件

我一点也不喜欢微软内置的记事本。我更喜欢使用 notepad++,但由于它不是内置的,所以从命令行使用起来并不容易。我正在编写一个可以提供帮助的 powershell 脚本,以下是我目前所拥有的:

Function Read ([string] $file)
{
$currentPath = (get-location).Path
cd "C:\program Files (x86)\Notepad++\"
.\notepad++.exe $file
cd $currentPath
}

问题是,我每次都必须输入完整路径。大多数时候我都在想要读取文件的位置,因此如果能够像这样调用该函数就好了:

read .\docu.txt

而不是:读取 C:\users\user\desktop\docu.txt 我在想类似的事情:

$fullPath = '$currentPath\$file'
.\notepad++.exe $fullPath

但是如果我输入整个路径,它就不再起作用了,而且无论如何都不起作用,因为它看起来像“C:\users\user\documents.\docu.txt”。而且它不处理 UNC 路径。当我从那里选择 get-location 时,它看起来像

Microsoft.Powershell.Core\FileSystem::\\server\drive

我无法让它工作。

答案1

现在是使用正则表达式的好时机。不过这里有几个问题,让我们从上到下解决它们。首先,您需要能够处理网络路径。通过在脚本开头添加以下内容来消除路径中的所有额外垃圾

$UNCPath = $pwd.ProviderPath

这将仅为您提供 \\network\drive。

现在,为了处理您想要在 $file 参数中发送信息的不同方式,请使用正则表达式来检查您发送的内容。

$first = $file -match "\.\\" #does file contain .\ ?
$second = $file -match "\\"  #does file contain \ ?
if($first -eq $true)
{ #for instances when you sent in .\filename.txt
$subFile = $file.Substring(2) #Eliminate the .\ from the path
$completeFile = "$UNCPath\$subFile"
.\notepad++.exe $completedFile
}
else if($second -eq $true) #Contains \ but not .\ so you've sent the complete path
{
.\notepad++.exe $file   #easy when the full path is already sent
}
else
{  #You sent just the name of the document
$pathfile = $UNCPath + "\" + $file   #we assume if you just sent the name, the file is 
.\notepad++.exe $pathfile            #located at your current location
}
cd $currentPath
}

答案2

我认为你让这件事变得比它本来的更难了。:)

1)Notepad++会根据参数是否具有路径来加载文件,基于标准的Windows路径系统。

因此,如果它在本地文件夹中,它Notepad++ file.txt将会打开,并且无论您在哪个文件夹中,它都会打开。file.txtNotepad++ c:\path\file.txtC:\path\file.txt

2)只需将您的 Notepad++ 文件夹添加到系统路径,然后您只需在命令提示符下输入“notepad++ c:\path\file.txt”即可。

如果您希望更短,请在 Notepad++ 文件夹中创建一个批处理文件,也许命名为read.bat,其内容将类似于:

Notepad++.exe %1 %2 %3 %4 %5

这样做应该可以让你运行read file.txt和/或read c:\pathto\file.txt

相关内容