2017-10-10 43 views
0

我嘗試在不在我們的域中的設備上替換.ini文件中的一些行。我需要使用本地管理員帳戶執行復制/粘貼項目和get/set-content cmdlet。所有設備的IP都在一個單獨的文本文件中。有人能告訴我,我可以如何執行我的cmdlet作爲本地管理員?以管理員身份更改我們網絡中的文件槽powershell

$user = ".\administrator" 
$pass = ConvertTo-SecureString "password" -AsPlainText -Force 
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$pass 

$IP_Array = (Get-Content \\iparraypath) 

foreach ($IP in $IP_Array) { 
    mainreplace 
} 

function mainreplace { 
    $path = "\\$IP\path.." 
    Copy-Item $path path.. 

    $l = (Get-Content $path) 

    if ($l.StartsWith('oldtext')) { 
     ($l) -replace "oldtext.*",'newtext' | Set-Content $path 
    } 
} 

回答

1

您正在查找的cmdlet是Invoke-Command。另外,您希望對輸入文件的全部內容運行-replace,否則將從輸出中刪除所有不匹配的行。

foreach ($IP in $IP_Array) { 
    Invoke-Command -Computer $IP -ScriptBlock { 
     # use local path here, b/c the scriptblock is running on the remote host 
     $file = 'C:\path\to\your.ini' 
     (Get-Content $file) -replace 'oldtext.*', 'newtext' | 
      Set-Content $file 
    } -Credential $cred 
} 

複製文件是沒有必要的(除非你想保留一個備份副本),因爲把括號Get-Content(所謂的分組表達式)讀取整個內容到內存替換之前。這樣你可以將修改後的輸出直接寫回源文件。

+0

感謝您的快速響應。現在我開始尋找一種解決方法,將驅動器映射到網絡使用。我會定義看看你的方式並嘗試一下。祝你今天愉快 :) – MichaelS

相關問題