运行powershell脚本时在cmd中找不到路径错误

运行powershell脚本时在cmd中找不到路径错误,powershell,Powershell,我有下面的PowerShell脚本,我想从命令提示符下运行它,但是它给了我找不到文件ServerList.txt和url.txt的路径错误。当我将目录更改为脚本和文件所在的文件夹时,脚本工作 write-host "********* Changing IE Settings********************" $servers = Get-Content .\ServerList.txt $Urls = Get-Content .\Urls.txt $command ={ $r

我有下面的PowerShell脚本,我想从命令提示符下运行它,但是它给了我
找不到文件
ServerList.txt
url.txt
的路径错误。当我将目录更改为脚本和文件所在的文件夹时,脚本工作

 write-host "********* Changing IE Settings********************"
 $servers = Get-Content .\ServerList.txt
 $Urls = Get-Content .\Urls.txt
 $command ={
 $registryPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\InternetSettings\ZoneMap\Domains"
 Foreach ($url in $Urls)
 {
  $checkRegistryPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\" + $url
 if(!(Test-Path $checkRegistryPath))
 {
    write-host "Adding url to local intranet"
    if($url -eq "localhost")
    {

     $key = (get-item HKCU:\).OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains", $true)
     $subkey=$key.CreateSubKey('localhost')
     $subkey.SetValue("http","1","DWORD")
     $subkey.SetValue("https","1","DWORD")
     $key.Close()
     $subkey.Close()


    }
    elseif($url -like '*system*')
    {
     $key = (get-item HKCU:\).OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains", $true)
     $subkey = $key.CreateSubKey('//system')
     $subkey.SetValue("hcp","1","DWORD")
     $key.Close()
     $subkey.Close()

    }
    elseif($url -like '*next.loc*')
    {
      $key = (get-item HKCU:\).OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains", $true)
      $key.CreateSubKey("next.loc")
      $serverkey =(get-item HKCU:\).OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\next.loc", $true)
      $servername=  (([System.Uri]$url).Host).split('.')
      $subkey=$serverkey.CreateSubKey($servername[0]) 
      $subkey.SetValue("http","1","DWORD")
      $key.Close()
      $serverkey.Close()
      $subkey.close()

    }
 }
 else
 {
   write-host $url "url already added to local intranet"
 }
}
}

Foreach ($server in $servers)
 {
   if([string]::IsNullOrEmpty($server))
    {
      Invoke-Command  -ScriptBlock $command
   }
   else
    {
    Invoke-Command -Computer $server -ScriptBlock $command
     }

   }
 write-host "****** IE Settings Changed Sucessfully************"

您可以使用以下命令确定脚本的路径:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
现在,您可以使用
$scriptPath
使用cmdlet组合您的路径:


或者使用
Set Location$scriptPath
更改脚本中的工作目录。@AnsgarWiechers是的,这也可以,但我尽量避免,因为我不喜欢在运行脚本时更改我的工作目录,不是吗?是的,尽管您可以使用
推送位置
弹出位置
来避免/缓解这种情况。
$servers = Get-Content (Join-Path $scriptPath  'ServerList.txt')
$Urls = Get-Content (Join-Path $scriptPath 'Urls.txt')