2015-07-28 226 views
3

考慮以下PowerShell代碼:PowerShell的找不到文件

IF(Test-Path -Path "C:\Windows\System32\File123") 
{Remove-Item -Force -Path "C:\Windows\System32\File123"} 

如果該代碼已在x86 PowerShell控制檯執行,下面的錯誤引發的Get-ChildItem:找不到路徑「C:\ Windows \ System32下\ File123',因爲它不存在。

但是,當代碼在x64 Powershell控制檯中運行時,該命令的行爲與預期相同。

是否有解決此問題的任何腳本化方法?

+1

您可以使用'$ env:Processor_Architecture'查看答案中顯示的Powershell是x86還是x64。然後,你可以從'c:\ windows \ sysWOW64'(x86下的x64 env),'c:\ windows \ sysnative'(x86下的x64)或'c:\ windows \ system32'中選擇適當的'system32'每個env都是原生的)。 – Vesper

回答

2

一個哈克解決方法是檢測腳本使用PowerShell的x86運行,並通過把這個片段在你的腳本開始用64 PowerShell中調用它:

if ($env:Processor_Architecture -eq "x86") 
{ 
    &"$env:windir\sysnative\WindowsPowerShell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path -executionpolicy bypass 
    exit 
} 
+0

我認爲'-website'是一個不需要的參數,但是感謝'sysnative'從x86訪問x64的'system32'。 – Vesper

+0

謝謝Vesper,你是對的,我從我的一個腳本中複製了一個片段,它帶有一個-WebSite參數。我刪除它。 –

+0

感謝你們,我在我的班次結束時發佈了這個問題。我有一些時間來正確地研究這個問題,並提出了一些看起來有用的技巧。 – user4317867

0

感謝偉大的回覆,我有一些時間來做一些探索,並提出以下建議。我正在使用Powershell v4。你可以把任何東西放在ps64別名之後,例如腳本或函數。別名的積分爲this page。還要感謝https://stackoverflow.com/a/19835164/4317867對於[ScriptBlock]::Create("")提示,在執行此操作之前,Script塊不會正確地擴展$ server。

這樣做的目標是刪除Powershell的計劃任務/作業文件以允許重新創建它。

Param(
[Parameter(Mandatory=$true, 
    HelpMessage="ServerName goes here")] 
[string]$server, 
[Parameter(Mandatory=$true, 
    HelpMessage="Enter a Date/Time 07-28-15 16:00 For July 28th, 2015 at 4:00 PM")] 
    [ValidatePattern('\d{2}-\d{2}-\d{2}\s\d{2}[:]\d{2}')]  
$date) 

if($env:PROCESSOR_ARCHITECTURE -eq "x86") 
{ 
set-alias ps64 "$env:windir\sysnative\WindowsPowerShell\v1.0\powershell.exe" 
ps64 -command "IF(Test-Path -Path C:\Windows\System32\Tasks\Microsoft\Windows\PowerShell\ScheduledJobs\RebootOnce2){Remove-Item -Force -Path C:\Windows\System32\Tasks\Microsoft\Windows\PowerShell\ScheduledJobs\RebootOnce2}" #End 64 bit powershell. 
} 
Else{ 
Get-ScheduledJob | Unregister-ScheduledJob 
} 
$user = Get-Credential -UserName $env:USERNAME -Message "UserName/password for scheduled Reboot" 
$trigger = New-JobTrigger -once -at $date 
$script = [ScriptBlock]::Create("D:\Scripts\Scheduled-Reboot-Single.ps1 -server $server | Out-File -Force \\LogServer\d$\scripts\$server-Reboot.log") 
Register-ScheduledJob -Name RebootOnce2 -Credential $user -Trigger $trigger -ScriptBlock $script