WinAPI from a script, not the ISE - winapi

I am using this code and it works fine in the ISE but not when run as a script. The error I get is "Specified cast is not valid" and it occurs at the last line shown here. I am thinking it is the Set-Type that is actually the problem, but I removed -ignoreWarnings and I get no indication of a problem. I get the same error if I launch the script with Run as administrator or not. My hope is that WinAPIs isn't something that is limited to the ISE
Add-Type -typeDefinition #'
using System;
using System.Runtime.InteropServices;
namespace WinAPIs {
public class UserAccountPicture {
[DllImport("shell32.dll", EntryPoint = "#262", CharSet = CharSet.Unicode, PreserveSig = false)]
public static extern void SetUserTile(string username, int notneeded, string picturefilename);
}
}
'# -ignoreWarnings
[WinAPIs.UserAccountPicture]::SetUserTile($userName, 0, $imagePath)
I also tried an alternate approach with the same results.
$methodDefinition = #'
[DllImport("shell32.dll", EntryPoint = "#262", CharSet = CharSet.Unicode, PreserveSig = false)]
public static extern bool SetUserTile(string username, int notneeded, string picturefilename);
'#
$shell32 = Add-Type -memberDefinition:$methodDefinition -name:'shell32' -namespace:'Win32' -passThru
$shell32::SetUserTile("RTC", 0, "$scriptPath\RTC.bmp")
I am rather out of my element here, so hopefully someone can point me at my mistake. Or verify that I just can't do this in a script.
thanks!

From this post:
CoInitialize(NULL)/CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) must
be called prior to calling this function.
Have you tried to call this functions beforehand?
What's your PowerShell version? Because this may be related to STA\MTA modes:
Did you know that in Windows PowerShell 3.0, we changed the Windows
PowerShell console from multi-threaded apartment (MTA) to
single-threaded apartment (STA)? If you did not notice the change, you
are probably not doing anything that requires MTA mode. If all of a
sudden, you have some Windows PowerShell 2.0 or even Windows
PowerShell 1.0 scripts that no longer work, now you know why.
You can check your PS host's mode this way: $host.Runspace.ApartmentState
Even if you're using PS 3 and higher, you could try to launch PowerShell.exe with -Sta or -Mta parameters and see, if this makes any difference.
Moreover, I've tried your code on PS 5.0 and it works both in ISE and PowerShell console.
UPDATE: This is defintely STA\MTA issue:
The function is in shell32.dll. It doesn’t have a name but the ordinal
262. It takes a username (MACHINE\user or DOMAIN\user format), a zero (the usual reserved stuff, I guess), and a picture path (can be any
well known format or size) parameter, and returns an HRESULT. If you
pass a null username, then the result of GetUserNameEx with a
NameSamCompatible parameter will be used. It uses COM inside, and
only works on STA threads (otherwise throws an InvalidCastException (0×80004002, E_NOINTERFACE)).
The thing I don't understand, is that why your PowerShell console runs as MTA, it shouldn't do this.

Related

Cannot find type Windows.Data.Xml.Dom.XmlDocument when running a toast notification from CMD

I created a PowerShell script that has some XML stuff in there. In the Powershell ISE, the built-in terminal works. BUT when I ran the file from CMD, I got a error that says New-Object : Cannot find type [Windows.Data.Xml.Dom.XmlDocument]: verify that the assembly containing this type is loaded at line 31.
Here's the rest of the code
$ToastXml = New-Object Windows.Data.Xml.Dom.XmlDocument
$ToastXml.LoadXml($ToastTemplate.OuterXml)
$Notification = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppID)
$Notification.Show($ToastXml)
I guess it's installed built-in to the ISE, but not on windows....itself? Is there something missing in the runtime?
The Windows.Data assembly exists in a PowerShell session after invoking a method in Windows.UI.Notifications.ToastNotificationManager, such as your call to CreateToastNotifier.
I suggest setting $Notification earlier in your script.
Alternatively, you can evaluate this expression:
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data, ContentType=WindowsRuntime]
(Unless you want your script to output it, you will want to capture this somehow, perhaps with the [void] type accelerator.)
Someone more familiar with the Windows Runtime may be able to explain, but for practical purposes, this works well enough. The Windows.Data assembly is not a typical assembly, nor is it found in the Global Assembly cache:
PS> [Windows.Data.Xml.Dom.XmlDocument].Assembly | Format-List FullName,Location,GlobalAssemblyCache,Is*
FullName : Windows.Data, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime
Location : C:\WINDOWS\system32\WinMetadata\Windows.Data.winmd
GlobalAssemblyCache : False
IsDynamic : False
IsFullyTrusted : True

How can I automatically syntax check a powershell script file?

I want to write a unit-test for some code which generates a powershell script and then check that the script has valid syntax.
What's a good way to do this without actually executing the script?
A .NET code solution is ideal, but a command line solution that I could use by launching an external process would be good enough.
I stumbled onto Get-Command -syntax 'script.ps1' and found it concise and useful.
ETA from the comment below: This gives a detailed syntax error report, if any; otherwise it shows the calling syntax (parameter list) of the script.
You could run your code through the Parser and observe if it raises any errors:
# Empty collection for errors
$Errors = #()
# Define input script
$inputScript = 'Do-Something -Param 1,2,3,'
[void][System.Management.Automation.Language.Parser]::ParseInput($inputScript,[ref]$null,[ref]$Errors)
if($Errors.Count -gt 0){
Write-Warning 'Errors found'
}
This could easily be turned into a simple function:
function Test-Syntax
{
[CmdletBinding(DefaultParameterSetName='File')]
param(
[Parameter(Mandatory=$true, ParameterSetName='File', Position = 0)]
[string]$Path,
[Parameter(Mandatory=$true, ParameterSetName='String', Position = 0)]
[string]$Code
)
$Errors = #()
if($PSCmdlet.ParameterSetName -eq 'String'){
[void][System.Management.Automation.Language.Parser]::ParseInput($Code,[ref]$null,[ref]$Errors)
} else {
[void][System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$null,[ref]$Errors)
}
return [bool]($Errors.Count -lt 1)
}
Then use like:
if(Test-Syntax C:\path\to\script.ps1){
Write-Host 'Script looks good!'
}
PS Script Analyzer is a good place to start at static analysis of your code.
PSScriptAnalyzer provides script analysis and checks for potential
code defects in the scripts by applying a group of built-in or
customized rules on the scripts being analyzed.
It also integrates with Visual Studio Code.
There are a number of strategies for mocking PowerShell as part of unit tests, and also have a look at Pester.
The Scripting Guy's Unit Testing PowerShell Code With Pester
PowerShellMagazine's Get Started With Pester (PowerShell unit testing framework)

how to track all function calls of some modules?

I'd like to have some usage statistics for a bunch of my modules.
It would be handy if I could run code whenever a function is called from a set of modules. Is it doable? Do powershell generate internal events we can hook on? I can not find any guidance yet
It's not completely clear to me whether you're more interested in logging events or executing code (hooking).
Logging
There are 2 places where in the event log where Powershell writes to the logs:
Applications and Services > Windows PowerShell
Applications and Services > Microsoft > Windows > PowerShell
On a per-module level, you can enable the LogPipelineExecutionDetails property. To do it on load:
$mod = Import-Module ActiveDirectory
$mod.LogPipelineExecutionDetails = $true
Or for an already loaded module:
$mod = Get-Module ActiveDirectory
$mod.LogPipelineExecutionDetails = $true
After that you check the first of the event log locations I listed (Windows PowerShell) and you'll see logs that show the calls to various cmdlets with the bound parameters.
You can also enable this via Group Policy as a Computer or User setting:
Administrative Templates > Windows Components > Windows PowerShell > Turn On Module Logging
You can specify the module(s) you want to enable logging for.
In PowerShell v5, there will be even more detailed logging available (see the link).
Source
You can see more detailed information about the logging settings (current and upcoming) on Boe Prox's blog: More New Stuff in PowerShell V5: Extra PowerShell Auditing
Hooking
As far as I know there is no direct way to hook calls in an existing module, but I have a crappy workaround.
You can effectively override existing cmdlets/functions by creating functions or aliases with the same name as the original.
Using this method, you could create wrappers around the specific functions you want to track. Consider something like this:
# Override Get-Process
function Track-GetProcess {
[CmdletBinding()]
param(
# All the parameters that the original function takes
)
# Run pre-execution hook here
& { "before" }
$params = #{}
foreach($h in $MyInvocation.MyCommand.Parameters.GetEnumerator()) {
try {
$key = $h.Key
$val = Get-Variable -Name $key -ErrorAction Stop | Select-Object -ExpandProperty Value -ErrorAction Stop
if (([String]::IsNullOrEmpty($val) -and (!$PSBoundParameters.ContainsKey($key)))) {
throw "A blank value that wasn't supplied by the user."
}
Write-Verbose "$key => '$val'"
$params[$key] = $val
} catch {}
}
Get-Process #params # call original with splatting
# run post execution hook here
& { "after" }
}
The middle there uses splatting to send the given parameters and sending them to the real cmdlet.
The hardest is part is manually recreating the parameter block. There are ways you could likely do that programmatically if you wanted to quickly run something to hook any function, but that's a bit beyond the scope of this answer. If you wanted to go that route, have a look at some of the code in this New-MofFile.ps1 function, which parses powershell code using powershell's own parser.

using registry to run a prog at startup

i am trying to run a code in c++ which will result in an .exe file running at startup using registry...but the problem is that the code results fails without showing any errors...i compiled the code in devcpp...
the code is
void createkey(char *path)
{
int reg;
HKEY hkey,Hkey1;
DWORD ptr;
reg=RegOpenKeyEx(HKEY_LOCAL_MACHINE,TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),0,KEY_SET_VALUE,&hkey);
if(reg=ERROR_SUCCESS)
cout<<"success"<<endl;
else
cout<<"failure"; //(a)
cout<<reg<<endl; //(b)
if(reg==0)
{
RegSetValueEx(hkey,TEXT("key"),0,REG_SZ,(BYTE*)path,strlen(path));
}
}
in the command line failure and 0 got printed as a result of (a) and (b)...(dont know how as the two mean completely opposite things )....the char *path passed to regsetvalueex was "c:/Dev-Cpp/bin/Untitled2.exe"...i am sure that the functions are not working as key doesnt appear in run key(i checked using regedit)...
if(reg=ERROR_SUCCESS)
That's an assignment, you need to use the == operator. Most modern compilers warn about this, be sure to update yours. You probably got an access denied error, can't write to HKLM\Software without elevation.
Standard users don't have write access to HKLM. You need to run this process elevated.

Detect if running with administrator privileges under Windows XP

I am trying to work out how to detect whether a user is running with admin rights under Windows XP. This is fairly easy to do in Vista/Win7 thanks to the whoami command. Here's a snippet in Ruby for how to do it under Vista:
Note, the following link now incorporates the solution suggested by muteW
http://gist.github.com/65931
The trouble is, whoami doesn't come with Windows XP and so the above linked method will always return false on WinXP, even if we're running as an administrator.
So, does anyone know of a way to detect whether we're running as an admin under Windows XP using Ruby, command-line tools, batch-files, or even third-party (needs to be open source, really) tools?
This will detect if the user is running in elevated mode (eg a command prompt that was "Run As" Administrator). It relies on the fact that you require admin privileges to read the LOCAL SERVICE account reg key:
reg query "HKU\S-1-5-19"
this will return a non-zero error code if it cannot be read, and zero if it can.
Works from XP up...
If you run
>net localgroup administrators
in a command shell you should get the list of administrator accounts in Windows XP. Simply parse and scan the output to check for the particular user account you want. For e.g. to check if the current user is an administrator you could do -
>net localgroup administrators | find "%USERNAME%"
Piskvor option its fine, or check this url
http://weseetips.com/2008/04/16/how-to-check-whether-current-user-have-administrator-privilege/
this is the code in that page
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
// Initialize SID.
if( !AllocateAndInitializeSid( &NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup))
{
// Initializing SID Failed.
return false;
}
// Check whether the token is present in admin group.
BOOL IsInAdminGroup = FALSE;
if( !CheckTokenMembership( NULL,
AdministratorsGroup,
&IsInAdminGroup ))
{
// Error occurred.
IsInAdminGroup = FALSE;
}
// Free SID and return.
FreeSid(AdministratorsGroup);
return IsInAdminGroup;
Check out the CheckTokenMembership method. There is a sample there of IsUserAdmin() implementation plus some other useful community feedback on when that function does not return what is expected and what to do to improve it.
This will find out without shelling out:
require 'win32/registry'
is_admin = false
begin
Win32::Registry::HKEY_USERS.open('S-1-5-19') {|reg| }
is_admin = true
rescue
end
The strategy is similar to Peter's, but with less overhead.
Here is the better (PowerShell) way of doing it: https://stackoverflow.com/a/16617861/863980
In one line, you can say (copy/paste in posh and it will work):
(#(([ADSI]"WinNT://./Administrators,group").psbase.Invoke("Members")) | `
foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}) -contains "Administrator"
=> returns True when user belongs to Administrators group (as opposed to checking user IS Administrator)
(Note: backtick or grave accent ` escapes the carriage return in PowerShell, in Ruby it executes the shell commands, like C++'s system('command')..)
So in Ruby, you can say (copy/paste in irb):
def is_current_user_local_admin?
return `powershell "(#(([ADSI]'WinNT://./Administrators,group').psbase.Invoke('Members')) | foreach {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}) -contains 'Administrator'"`.include? "True"
end
Don't know the (even better) WMI way of doing it though. With that, you could have done something like (in Ruby again):
require 'win32ole'
wmi = WIN32OLE.connect('WinNT://./Administrators,group')
# don't know what should come here...

Resources