Powershell 在当前目录中找不到文件
我有以下脚本:Powershell 在当前目录中找不到文件,powershell,Powershell,我有以下脚本: function Export-sql-toExcel { [CmdletBinding()] Param ( [string]$scriptFile, [string]$excelFile, [string]$serverInstance, [string]$database, [string]$userName, [string]$password )
function Export-sql-toExcel {
[CmdletBinding()]
Param (
[string]$scriptFile,
[string]$excelFile,
[string]$serverInstance,
[string]$database,
[string]$userName,
[string]$password
)
$tokens = ( [system.io.file]::ReadAllText( $scriptFile ) -split '(?:\bGO\b)' )
foreach ($token in $tokens) {
$token = $token.Trim()
if ($token -ne "") {
$lines = $token -split '\n'
$title = $lines[0]
if ($title.StartsWith("--")) {
$title = $title.Substring(2)
$title
}
Invoke-Sqlcmd -ServerInstance $serverInstance -Database $database -Username $userName -Password $password -Query $token |
Export-Excel -Path $excelFile -WorkSheetname $title -FreezeTopRow -ExcludeProperty RowError,RowState,Table,ItemArray,HasErrors
}
}
}
我已将此功能作为模块安装。例如,当我从桌面文件夹调用命令时,如下所示:
PS D:\Usuarios\mnieto\Desktop> Export-sql-toExcel -scriptFile .\EXPORT.txt -excelFile Excel.xlsx
我收到以下错误(export.txt文件位于桌面文件夹中):
使用“1”参数调用“ReadAllText”时出现异常:“找不到文件'D:\Usuarios\\EXPORT.txt'
已编辑
如果我调试并尝试[system.environment]::CurrentDirectory,它将返回
'D:\Usuarios\
那是因为我的脚本失败了。NET函数和powershell不共享“当前目录”
获取内容和解析$scriptFile文件的任何其他方法?我也遇到过同样的情况,当我添加一个点“.”来调用csv时,问题得到了解决 $path2=$path+“\file.csv”
或者检查$excelFile变量中的空格。我在这一行通过powershell命令获得了更改网络调用的解决方案
$content = Get-Content $scriptFile -Raw
$tokens = ( $content -split '(?:\bGO\b)' )
诀窍在于-Raw参数,因此根据我的经验,该文件将作为单个字符串读取 我会用
$scriptfile = (Get-Item $Scriptfile).FullName
要解析为前面函数中的完整路径,请执行以下操作:
$tokens = ( [system.io.file]::ReadAllText( $scriptFile ) -split '(?:\bGO\b)' )
但是如果我在调用中传递了一个绝对路径,会发生什么呢:
exportsqltoexcel-scriptFile c:\Export.txt
。我不能用点作为文件名的前缀
$tokens = ( [system.io.file]::ReadAllText( $scriptFile ) -split '(?:\bGO\b)' )