我正试图在PowerShell中运行一些内联C#代码,目的是刷新Windows资源管理器.
以下是代码(基于this question):
function Request-ExplorerRefresh {
$code = @"
using System;
namespace VSYSRefresh
{
public static class Util
{
public static void RefreshExplorer(){
Console.WriteLine("Refreshing Explorer");
Guid CLSID_ShellApplication = new Guid("13709620-C279-11CE-A49E-444553540000");
Type shellApplicationType = Type.GetTypeFromCLSID(CLSID_ShellApplication, true);
object shellApplication = Activator.CreateInstance(shellApplicationType);
object windows = shellApplicationType.InvokeMember("Windows", System.Reflection.BindingFlags.InvokeMethod, null, shellApplication, new object[] { });
Type windowsType = windows.GetType();
object count = windowsType.InvokeMember("Count", System.Reflection.BindingFlags.GetProperty, null, windows, null);
for (int i = 0; i < (int)count; i++)
{
object item = windowsType.InvokeMember("Item", System.Reflection.BindingFlags.InvokeMethod, null, windows, new object[] { i });
if(item != null){
Type itemType = item.GetType();
}
// only refresh windows explorer
string itemName = (string)itemType.InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, item, null);
if ((itemName == "Windows Explorer") || (itemName == "File Explorer")) {
itemType.InvokeMember("Refresh", System.Reflection.BindingFlags.InvokeMethod, null, item, null);
}
}
}
}
}
"@
Add-Type -TypeDefinition $code -Language CSharp
Invoke-Expression "[VSYSRefresh.Util]::RefreshExplorer()"
}
我收到以下错误:
(26,43): error CS0165: Use of unassigned local variable 'itemType'
(string)itemType.InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, item, null);
Cannot add type. Compilation errors occurred.
Unable to find type [VSYSRefresh.Util].
我甚至都不能让Console.WriteLine()
美元go 工作.我是否需要引用某些程序集才能使其正常工作?
我走进了死胡同,任何帮助都将不胜感激.