Win32 API 関数を使用する方法について、サンプルコードを用いて説明します。
ファイルの属性を Win32 API の SetFileAttributes 関数を使用して変更
1. 次のファンクションを作成します。
function set-attr ([string]$path, [long]$att)
{
$memberDefinition = @'
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern bool SetFileAttributes(string lpFileName, long dwFileAttributes);
'@
$type = Add-Type -Name test -MemberDefinition $memberDefinition -PassThru
$type::SetFileAttributes($path, $att)
}
2. このファンクションをコールして、ファイルに Hidden 属性を付けます。
set-attr D:\Sample.txt 2 2. このファンクションをコールして、ファイルを通常の状態に戻します。 set-attr D:\Sample.txt 0
(補足説明)
Win32 API には関数名の最後に A や W が付くものがあります。SetFileAttributes にも SetFileAttributesA がありますが、A が付いた関数はコールに失敗しました。理由は不明です。