我正在尝试编写一个powershell脚本,它将返回txt文件中的内容。但是,我不想指定txt文件的驱动器,因为txt文件将放在与powershell脚本相同的文件夹中。
我正在使用这行代码:
get-content。\ document.txt | select -first 1 -skip 1
但它不起作用。
内幕document.txt:
我要写什么脚本来检索第二行"这是第二行"无需像#C; \ Data \ Scripts \ Document.txt"?那样完整的路径我已经搜索了在线解决方案,但许多解决方案要求我必须放置其目标路径。
答案 0 :(得分:4)
get-content $psscriptroot\document.txt | select -first 1 -skip 1
请注意,$psscriptroot
在脚本执行时只会有一个值,但它将代表脚本所在的路径。
答案 1 :(得分:0)
我可能无法正确理解问题,但您可以通过
显示文本文件的内容cat <yourfile.name>
如果你想获得文本文件的一部分,你可以做到
cat <yourfile.name> | Select-String '<text you want to get>'
您可以参考此网站,了解如何操作输出https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/select-string
如果您想在Bash中运行脚本,则需要使用不同的脚本
答案 2 :(得分:0)
找到文本文件看看这个链接 PowerShell: current directory relative to executing script
在你得到它之后,我们可以轻松地移动到文件的第二行,
Solution here:-to print the required line
代码可能会将自己转换为类似的东西
#include this is in your script,this part of the code will get the absolute path of the script from whereever its running
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$path = Join-Path (Get-ScriptDirectory) 'Your Script Name'
$path.ToString()
$path =$path.Substring(0,$path.IndexOf('Your Script Name'))
$path
#now $path has the directory in which you have your files,append it with your text file name
(Get-content $path+'textfilename.txt')[1]
#and get the second line of the content
对SomeShinyobjects的信任
这可以简单地写成
$path=$PSScriptRoot+'\textfilename.txt'
(Get-content $path)[1]
答案 3 :(得分:0)
如果您正在寻找第二行,请使用以下内容: 默认情况下,每一行都是数组的索引。所以第二行的索引为1
(get-content .\document.txt)[1]