2016-12-05 54 views
0

我決定改變劇本我都在Script able to run from any folder我scprit「你不能叫一個空值表達式的方法」

用於訪問該數據應該通過XML點符號改變了數據,我有問題用它。 Here's腳本以目前的形式:

$SetCount = Read-Host -Prompt "How many copies do you need" 
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 
$name = 420566666000 
$fileContent = Get-Content (Join-Path $scriptPath '420566666000.xml') -Raw 

for ($i=1; $i -le $SetCount; $i++) 
{ 
$name++; 
$fileContent.subscriptionDetail.subscription.customerAccountNumber.Replace($name) | Set-Content (Join-Path $scriptPath "$name.xml") 
} 
Write-Host "Done!" 

而且不管我做什麼,我總是在行$fileContent.subscriptionDetail.subscription.customerAccountNumbe..."

得到"You cannot call a method on a null-valued expression"據我瞭解,它實際上說$fileContent是空的時它的調用,但我不明白爲什麼,因爲它是在達到$fileContent.subscriptionDetail.subscription.customerAccountNumbe..."腳本之前的幾行之前發起的+不空的(如果您將Write-Host $fileContent放在前面提到的行之前,它將會吐出一個.XML的整個內容文件)。

我在做什麼錯? 我是否調用了錯誤的替換的.XML調用?

我很抱歉,如果這感覺像基本的東西(這是),但我只是殺了整整一天尋找解決方案,並沒有得到任何地方。

編輯:// 感謝您的答案,最後的工作代碼(我不得不改變它替換元素的部分)如下:

$SetCount = Read-Host -Prompt "How many copies do you need" 
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 

$name = 420566666000 
[xml]$fileContent = Get-Content (Join-Path $scriptPath '420566666000.xml') 

for ($i=1; $i -le $SetCount; $i++) 
{ 
    $name++; 
    #Modify the XML element to appropriate value   
    $fileContent.subscriptionDetail.subscription.serviceNumber="$name" 

    #Save it 
    $OutPath = (Join-Path $scriptPath "$name.xml") 
    $fileContent.Save($OutPath)   
} 

Write-Host "Done!" 
+2

我認爲$ filecontent是一個字符串而不是xml對象。將它明確地轉換爲xml時會發生什麼:[xml] $ filecontent = get-content ... – BenH

+0

嘗試檢查表達式$ fileContent.subscriptionDetail.subscription.customerAccountNumber中每個部分包含的內容。 '$ fileContent'本身可能不是null,但是每個級別你可能會更深入。 – Shai

回答

3

$fileContent變量,當被填充Get-Content命令只是一個很大的字符串,所以當你嘗試通過XML結構挖掘它時,結果是沒有任何結果,因爲文本字符串沒有.subscription屬性或方法。

[xml]$fileContent = Get-Content (Join-Path $scriptPath '420566666000.xml') -Raw 

首先[xml]語句導致PowerShell來推斷的結構:

要強制PowerShell來對待你的$fileContent變量作爲XML樹,你必須在賦值給XML類型的時間轉換的變量文件並創建允許您隨意導航文檔樹的屬性。

+1

並且不需要'-Raw'開關。 – Swonkie

+0

非常感謝,雖然現在它說'無法找到超過「替換」和參數計數:「1」。'''在行''fileContent.subscriptionDetail.subscription.customerAccountNumbe ...'我有這個錯誤之前和雖然我發現了類似的問題與同樣的錯誤,問題似乎是非常具體的每個人,我無法推斷出我的問題的答案。 – Blu3Rat

+0

'string.Replace()'函數需要2個參數,在字符串中查找什麼,以及在找到時替換它的位置。 $ a ='我喜歡雞蛋。' $ b = $ a.Replace('eggs','applesauce') $ b #我喜歡蘋果醬。 但公平地說,這是一個不同的問題,應該在其他地方發佈。 – HipCzeck