代码之家  ›  专栏  ›  技术社区  ›  mnieto

在当前目录中找不到文件

  •  1
  • mnieto  · 技术社区  · 6 年前

    我有以下脚本:

    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文件在桌面文件夹中):

    Exception calling "ReadAllText" with "1" argument(s): "Can't find the file 'D:\Usuarios\<MyUserName>\EXPORT.txt'."
    

    编辑

    如果我调试并尝试[System.Environment]::currentDirectory,它将返回 'D:\Usuarios\<MyUserName> 那是因为我的脚本失败了。NET函数和PowerShell不共享“当前目录”

    还有其他方法来获取内容并解析$scriptfile文件吗?

    3 回复  |  直到 6 年前
        1
  •  1
  •   mnieto    6 年前

    我在这一行得到了通过powershell命令更改net调用的解决方案

    $content = Get-Content $scriptFile -Raw
    $tokens = ( $content -split '(?:\bGO\b)' )
    

    技巧在-raw参数中,因此文件被读取为单个字符串

        2
  •  1
  •   LotPings    6 年前

    根据我的经验,.dot-net函数不喜欢相对路径。

    我会用

    $scriptfile = (Get-Item $Scriptfile).FullName
    

    要解析为前面函数中的完整路径,请执行以下操作:

    $tokens = ( [system.io.file]::ReadAllText( $scriptFile ) -split '(?:\bGO\b)' )
    
        3
  •  0
  •   Quiron    6 年前

    我也有同样的情况,当我添加一个点“.”来调用csv时就解决了。

    $path2=$path+“.\file.csv”

    或者检查$excelfile变量是否有空格。