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

时间:2016-05-19 12:30:05

标签: powershell

我有以下PowerShell脚本,我想从命令提示符运行,但它为Cannot find the path errorServerList.txt文件提供了Urls.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************"

1 个答案:

答案 0 :(得分:1)

您可以使用以下方式确定脚本的路径:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

现在,您可以使用$scriptPath使用Join-Path cmdlet组合路径:

$servers = Get-Content (Join-Path $scriptPath  'ServerList.txt')
$Urls = Get-Content (Join-Path $scriptPath 'Urls.txt')