windowsbatch-filepowershellpssnapin

Use BAT file to check if PSSnapin is registered


I've hit a little bit of a brick wall here. I have written a rather large PS script that requires the SQLServerProviderSnapin100 and this all works happily.

To run the script I have written a BAT file for the users to run so that they won't have to fiddle around with execuptionpolicy, so it sets it unrestricted calls the script and once the script completes it sets the executionpolicy back to restricted.

The problem I have is that I need the BAT file to detect if the user has the SqlServerProvider100 snapin registered to the 32Bit Powershell or the 64Bit powershell.

I know I could run something like this in powershell

$prov = get-pssnapin -registered | where-object{$_.Name -eq "Sqlserverprovidersnapin100"}
if($prov -eq $null){ <call powershell x86>}else{<call powershell 64Bit>}

But how do I do this in the BAT, or is what I am trying to do even possible?

I hope I making sense to someone who can help me get over this bump! :)


Solution

  • Ok worked it out!

    FOR /F "usebackq delims=" %%i IN (`powershell -command "get-pssnapin -registered | where-object { $_.Name -eq 'sqlserverprovidersnapin100' }"`) DO ( set snapin=%%i )
    REM if /i {%snapin:~0,4%}=={%test:~0,4%} (goto :there)
    if not defined snapin goto :notthere
    (goto :there)
    :there
    echo %snapin%
    pause
    exit
    
    :notthere
    echo "Not loaded!"
    pause
    exit
    

    This exercise has taught me two things now: apparently when I was testing against NULL within a BAT, if the value was NULL it would remove the variable and secondly how to pass a PS variable back to BAT.