我发现了一个PowerShell script,它可以更改我的Windows 7 PC的桌面墙纸,其图像文件的路径作为参数提供。我想要的最终结果是在启动时通过批处理文件调用此脚本。PowerShell脚本第一次失败,但第二次运行
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$false)]
$Style = "NoChange"
)
BEGIN {
try {
$WP = [Wallpaper.Setter]
} catch {
$WP = add-type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Tile, Center, Stretch, NoChange
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper (string path, Wallpaper.Style style) {
SystemParametersInfo(SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange);
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
switch(style)
{
case Style.Stretch :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Center :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Tile :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
case Style.NoChange :
break;
}
key.Close();
}
}
}
"@ -Passthru
}
}
PROCESS {
Write-Verbose "Setting Wallpaper ($Style) to $(Convert-Path $Path)"
$WP::SetWallpaper((Convert-Path $Path), $Style)
}
我使用的命令调用该脚本:
C:\scripts\Set-Wallpaper.ps1 C:\Users\myProfile\Pictures\MyWallpaper.jpg
我完全新的PowerShell脚本的世界,我遇到的问题是,当我执行脚本在PowerShell它始终未能在第一时间与以下错误:
C:\scripts\Set-Wallpaper.ps1 : Unable to cast object of type 'System.Object[]' to type 'System.Type'.
At line:1 char:29
- C:\scripts\Set-Wallpaper.ps1 <<<< C:\Users\mbaleato\Pictures\MyWallpaper.jpg
- CategoryInfo : NotSpecified: (:) [Set-Wallpaper.ps1], InvalidCastException
- FullyQualifiedErrorId : System.InvalidCastException,Set-Wallpaper.ps1
但是,当我打电话完全相同的命令脚本和参数,第二次它的工作原理。
这是第一次导致我的批处理文件失败的失败。
任何更有经验的人都会对第一次失败的原因有一些建议,但第二次工作?任何关于如何让它第一次运作的建议?
谢谢stej,那修好了 – Span 2011-05-27 06:50:48