Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 当前目录显然不是当前目录_Powershell - Fatal编程技术网

Powershell 当前目录显然不是当前目录

Powershell 当前目录显然不是当前目录,powershell,Powershell,在ISE中运行此代码是可行的 Push-Location -Path $(Split-Path -Parent $myInvocation.MyCommand.Path) Get-Location $file = '.\ex.txt' $reader = New-Object System.IO.StreamReader($file) 在控制台中运行相同的代码失败。我错过了什么 PS H:\src\powershell> .\ccount.ps1 Path ---- H:\src\po

在ISE中运行此代码是可行的

Push-Location -Path $(Split-Path -Parent $myInvocation.MyCommand.Path)
Get-Location
$file = '.\ex.txt'
$reader = New-Object System.IO.StreamReader($file)
在控制台中运行相同的代码失败。我错过了什么

PS H:\src\powershell> .\ccount.ps1

Path
----
H:\src\powershell
New-Object : Exception calling ".ctor" with "1" argument(s): "Could not find file
'C:\src\powershell\ex.txt'."
At H:\src\powershell\ccount.ps1:9 char:11
+ $reader = New-Object System.IO.StreamReader($file)
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands
   .NewObjectCommand
这与建议的副本有何不同

另一个问题/答案确实解释了PowerShell在这种情况下失败的原因。然而,它并没有给出任何关于为什么这在ISE中有效的提示。这似乎是控制台和ISE主机之间的一个显著区别

我正在Windows 7 Enterprise SP1上运行PS5.0.10586.117版。

只需使用:

Push-Location -Path $(Split-Path -Parent $myInvocation.MyCommand.Path)
$myInvocation.MyCommand.Path
Get-Location
$file = Resolve-Path '.\ex.txt'
$reader = New-Object System.IO.StreamReader($file)
Push-Location $PSScriptRoot

只要您使用的是最新的PowerShell版本(v3+),它就可以在这两种情况下工作。

答案似乎是,
推送位置
不会更改控制台主机中的[Environment]::CurrentDirectory。它确实在ISE中改变了它

PS 09:02 \\SRV1\SH1\home\pwatson2 H:\
>Push-Location H:\src\t

PS 09:02 \\SRV1\SH1\home\pwatson2 H:\src\t
>Get-Location

Path
----
H:\src\t

PS 09:02 \\SRV1\SH1\home\pwatson2 H:\src\t

>Write-Host ([Environment]::CurrentDirectory)
C:\Windows\System32\WindowsPowerShell\v1.0

这可能是不正确的,问题不在于
$myInvocation.MyCommand.Path
,而在于使用
新建对象System.IO.StreamReader($file)
创建.Net对象。如询问者所示,由
Get location
H:\src\powershell
返回的位置与错误消息
'C:\src\powershell\ex.txt'
中的位置不匹配这正是控制台主机中不起作用的地方。你是在ISE上运行的吗?我是在ISE和控制台主机上运行的。我的环境是Windows10。检查
[Environment]::CurrentDirectory
环境变量。在控制台主机和ISE中可能会有不同的设置