使用BAT文件检查PSSnapin是否已注册

时间:2014-08-05 08:49:37

标签: windows batch-file powershell pssnapin

我在这里打了一小块砖墙。我写了一个相当大的PS脚本,需要SQLServerProviderSnapin100,这一切都很愉快。

为了运行脚本,我编写了一个BAT文件供用户运行,这样他们就不必使用executionptionpolicy,所以它设置了不受限制的调用脚本,一旦脚本完成就设置了执行策略回到限制。

我遇到的问题是我需要BAT文件来检测用户是否在32Bit Powershell或64Bit PowerShell中注册了SqlServerProvider100管理单元。

我知道我可以在powershell中运行类似的东西

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

但是我如何在BAT中做到这一点,或者我正在尝试做什么呢?

我希望我能帮助我克服这个颠簸的人! :)

2 个答案:

答案 0 :(得分:0)

尝试以下两个命令:

C:\Windows\Syswow64\WindowsPowerShell\v1.0\powershell.exe "if(Get-PSSnapin -registered "SqlServerCmdletSnapin100" -ea 0){ write-host "sql snapin present in 32bit shell"}"

代表64位:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "if(Get-PSSnapin -registered "SqlServerCmdletSnapin100" -ea 0){ write-host "sql snapin present in 64bit shell"}"

如果存在sql snapin,它们将返回一条漂亮的消息。

答案 1 :(得分:0)

好了解决了!

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

这个练习现在教给我两件事:显然当我在BAT中测试NULL时,如果值为NULL,它将删除变量,其次是如何将PS变量传递回BAT。