Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Weird error with VBscript and PCOMM V.14 Automation

$
0
0

I have some VBscripts that automate IBM Personal Communications

This happens with VBscript but not with VBA

Since I have to use the version 14 (64 bits) sometimes I get errors:

If I use the function CreatObject the error is: The specified module could not be found.

If I use the Wscript method Wscript.CreatObject the error is: WScript.CreateObject: Could not create object named "PCOMM.autECLConnMgr.1"

I have tried 2 ProgID for each of the 4 DLL

"PCOMM.autECLConnMgr" or "PCOMM.autECLConnMgr.1" "PCOMM.autECLPS" or "PCOMM.autECLPS.1" "PCOMM.autECLConnList" or "PCOMM.autECLPS.1" "PCOMM.autECLOIA" or "PCOMM.autECLPS.1"

I'm using LENOVO workstations with Windows 10 Enterprise Build 1809 64 bits

And also tried

C:\Windows\SysWOW64\Cscript and C:\Windows\System32\Cscript

Both works and both sometimes return the errors

Also have tried 2 different workstations in spite of those machines have the same "image" of software...

With IBM PC Version 12 this didn't happen!

And here is my pain... The error happens just the first time the script runs... Then okay.

I even can't induce the error !!

Any hint would be appreciated.

João.



Joao Simplicio Rodrigues


Append to CSV in PowerShell?

$
0
0
I'd like to find a way to append to an outputted csv file in Powershell.  Out-File has too much wasted space and duplicate lines.  Here's the script I'm trying to run:

$a=Get-Content users.txt
foreach ($i in $a)
{
    get-user $i | select displayname,samaccountname | Export-Csv output.csv -notype
}


I can't seem to find anything when dealing with an input file...  Thx.

Refresh Windows Server 'Collection' connections via command line/PowerShell

$
0
0

Hi folks, 

Apologies if this has been asked before, I've been looking for a while and had no luck. 

As the title states i'm looking for a way to activate the 'refresh' button in Remote Desktop services via command line for any given collection of ours, ideally with PowerShell. Is there a way to refresh it without having to open Server Manager and manually clicking this button? 

What is this 'refresh' button actually doing behind the scenes?


WSUS Cleanup script: cannot connect to WSUS Server

$
0
0

Hi guys,

I'm trying to apply a script (already posted) which allows to perform the WSUS server cleanup with an unattended way.

The script begins as follow:

[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | out-null
#...Get hostname...
$sysinfo = Get-WmiObject -Class Win32_ComputerSystem
$fullname = “{0}.{1}” -f $sysinfo.Name, $sysinfo.Domain
#...Connection to WSUS...
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($fullname,$false,8530)

The $fullname variable returns the expected info, but $wsus doesn't. It displays the following:

Exception calling "GetUpdateServer" with "3" argument(s): "Request for principal permission failed."
At C:\Users\*******\Desktop\WSUS_Server_Cleanup.ps1:7 char:1+ $wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($f ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : SecurityException


Please could anybody tell me what am I doing wrong???

Thanks a lot in advance!

Best Regards.

How do you get the correct file mime types in .net?

$
0
0
Is it just as simple as comparing the file extension and searching online for the correct type, e.g. Content-Type: application/msword ?

[WSH] How to properly run non English scripts in English Windows?

$
0
0

For example, below simple `test.vbs` code displays some Cyrillic characters, but was encoded using ANSI encoding with Cyrillic code page 1251.

wscript.echo "БГДЖЗИЙ"

The file's binary data:

77 73 63 72 69 70 74 2E 65 63 68 6F 20 22
C1 C3 C4 C6 C7 C8 C9
22 0D 0A

In English Windows' Notepad, the code shows as:

wscript.echo "ÁÃÄÆÇÈÉ"

When run with CSCRIPT from the command prompt, it'll displays the incorrect characters:

ÁÃÄÆÇÈÉ

I've tried switching to code page 1251 using the CHCP command like below, but the result is the same. e.g.

chcp 1251
cscript test.vbs

I also found out about the `//CP` command line switch to specify a code page, but it's not clear to which/what part(s) does that command line switch applies to. Anyone know?

Anyway... I've also tried using that switch like below, but still same result.

cscript //cp:1251 test.vbs

And combine it with the `chcp` command. e.g.

chcp 1251
cscript //cp:1251 test.vbs

I've also tried other Cyrillic code pages 21866 and 866, but same thing.

So, how to properly run the script so that it'll display the correct Cyrillic characters?Without changing the script file encoding to UTF16, or modifying it in any way.

How to use logical "OR" operator in batch script

$
0
0

Hi,

Please can i know how to make use of logical OR operator in a batch script?

For ex: When i want to check for a particular condition in "IF" statement how should i use it?

if a==1 or b==1

(     )

how do i achieve this in batch script?

Thanks in advance

Get-ClientWSUSSetting is not working. Nothing happends when running

$
0
0
When I am trying to run a cript (WS 2012 R2) nothing happends. No errors.

Why am I only getting 1 row in export-csv output

$
0
0

I have a need to verify if a list of IPs are found in a CIDR block.  The script I created is only outputting the 1st IP address and 1st CIDR Block (there are two CSVs).  I can see in the screen output that the script is looping thru each IP for each CIDR Block.  The export-csv is not catching output of each instance.

#Import the script used to validate if an IP address is in a CIDR block
Import-Module "C:\psscripts\Cidrv3.ps1"

#IMPORT List of CIDRs
$csv1 = Import-Csv -Path "C:\psscripts\input\CIDRBlock.csv"

#IMPORT List of IP Addresses
$csv2 = Import-Csv -Path "C:\psscripts\input\ipaddresses.csv" | Select IP_Address 

$cidr = @()
$ipaddress= @()

#Loop thru SendingIP to see if found in CIDR block
foreach ($cidr in $csv1)
{
    foreach ($ipaddress in $csv2)
    {
        $IPResult = IS-InSubnet -ipaddress $($ipaddress.IP_Address) -Cidr $cidr.CIDR
        #Build OUTPUT OBJ
        $outputObj += $ipObject = New-Object -TypeName PSObject -Property @{
           SendingIP = $ipaddress.IP_Address
           Found_In_CIDR_Block = $IPResult
           CIDR_Block = $cidr.CIDR
           }
    Write-Host "SendingIP               : $($ipObject.SendingIP)"
    Write-Host "Found_In_CIDR_Block     : $($ipObject.Found_In_CIDR_Block)"
    Write-Host "CIDR_Block              : $($ipObject.CIDR_Block)"
    }
}

#EXPORT DOMAINS TO CSV
Write-Host "Exporting CSV file..." -ForegroundColor White -BackgroundColor DarkGreen
$outputObj | Select SendingIP,Found_In_CIDR_Block,CIDR_Block | Export-CSV -Path C:\psscripts\output\test.csv -NoTypeInformation


Batch script: echo array data back using for loop

$
0
0

How do I echo all the values back?


Thanks.

@ECHO OFF SETLOCAL EnableDelayedExpansion SET i=0 FOR %%d IN ( "abc" "xyz""123""456""abcdef""123xyz" ) DO ( SET /A i=i+1 SET DATA[!i!]=%%d ) for /L %%i in (1,1,6) do ( ECHO A: %%DATA[%%i]%% ) echo X: %DATA[1]%

A: %DATA[1]%
A: %DATA[2]%
A: %DATA[3]%
A: %DATA[4]%
A: %DATA[5]%
A: %DATA[6]%
 X: "abc"


Error Connect-PNPOnline with app password

$
0
0

Hello,

I am trying to log on to a SharePoint site with a user and app password using Connect-PnPOnline and I get the following error:

PS C:\WINDOWS\system32> Add-PnPStoredCredential -Name PnPProv -Username sp.systemuser@xxx.com -Password (ConvertTo-SecureString -String "app password" -AsPlainText -Force)
PS C:\WINDOWS\system32> Connect-PnPOnline -Url https://xxx.sharepoint.com/sites/XX-... -Credentials PnPProv
Connect-PnPOnline : The partner returned a bad sign-in name or password error. For more information, see Federation Error-handling Scenarios.
In Zeile:1 Zeichen:1
+ Connect-PnPOnline -Url https://xxx.sharepoint.com/sites/XX- ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-PnPOnline], IdcrlException
    + FullyQualifiedErrorId : Microsoft.SharePoint.Client.IdcrlException,SharePointPnP.PowerShell.Commands.Base.ConnectOnline


Authentication normally works with an app password and this user.

Kind regards

BeKel

How to query event logs which has 5 million records?

$
0
0

Our server has 4GB size setting of security log. I tried to use vbscript to dump them all into a database. The script is as simple as following

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

arrComputers = Array("MyServer")
For Each strComputer In arrComputers
   WScript.Echo
   WScript.Echo "=========================================="
   WScript.Echo "Computer: " & strComputer
   WScript.Echo "=========================================="

   Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
   Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NTLogEventLog Where Logfile=Security", "WQL", _
                                          wbemFlagReturnImmediately+ wbemFlagForwardOnly)

   For Each objItem In colItems


     'DB action

   Next
Next

But the problem is I found the script can only dump the first 480K records and then quit without any error. It seems the recordset was generated successfully and enumerated.

The actual number of events is more than 5 million.

So the question is, how could I enumerate those?

Thanks!

5145 events,

$
0
0

How get all 5145 events, that Access to shares G (RRHH) o H (ADMINISTRACION)?


How to query event logs which has million records?
Our server has 3-4GB size setting of security log. 

Sample:

Nombre de registro:Security

Origen:        Microsoft-Windows-Security-Auditing

Fecha:         25/02/2020 11:32:38

Id. del evento:5145

Categoría de la tarea:Recurso compartido de archivos detallado

Nivel:         Información

Palabras clave:Auditoría correcta

Usuario:       No disponible

Equipo:        AlcorconFSRV01.xxxxxxx.es

Descripción:

Se comprobó un objeto de recurso compartido de red para averiguar si se puede conceder el acceso deseado al cliente.

               

Sujeto:

                Id. de seguridad:                             xxxxxxxxxx\marc.almendros

                Nombre de cuenta:                        marc.almendros

                Dominio de cuenta:                        xxxxxxxxxxxxxx

                Id. de inicio de sesión:                   0x2EA141A90

Información de red:       

                Tipo de objeto:                File

                Dirección de origen:                       10.103.133.207

                Puerto de origen:                            53806

               

Información de recurso compartido:

                Nombre de recurso compartido:                             \\*\RRHH

                Ruta de acceso de recurso compartido:                \??\G:\Shares\RRHH

                Nombre de destino relativo:       8. PRL\Investigación de incidentes_90\BCN


We need know which access to G: shares

Why do the outputs differ?

$
0
0
Hello, is there any reason, why there is different output of the second command in these two examples?

(1)
(Get-ADComputer -Filter 'Name -eq "[my computer name]"' -Properties Name).Name
@'+==================+


'@
[datetime]::FromFileTime((Get-ADComputer -Filter 'Name -eq "[my computer name]"' -Properties *).lastLogonTimestamp)

(2)

(Get-ADComputer -Filter 'Name -eq "[my computer name]"' -Properties Name)
@'+==================+


'@
[datetime]::FromFileTime((Get-ADComputer -Filter 'Name -eq "[my computer name]"' -Properties *).lastLogonTimestamp)

In the first case I received:
2020-02-23 15:11:59 

The second output is :

Date        : 2020-02-23 00:00:00
Day         : 23
DayOfWeek   : Sunday
DayOfYear   : 54
Hour        : 15
Kind        : Local
Millisecond : 244
Minute      : 11
Month       : 2
Second      : 59
Ticks       : 637180675192447834
TimeOfDay   : 15:11:59.2447834
Year        : 2020
DateTime    : 2020-02-23 15:11:59


ThanX for explanation,

Murphy



Powershell - Easiest way to get output from different data structures

$
0
0

Hello, I have one list of objects

[Collections.Generic.List[PSObject]]$computerArray = @()


where I store some info about computers:

       $computerObject = [PSCustomObject][ordered]@{

            ComputerName        = $computerName
            ManagedBy           = $ManagedBy
            lastActivity        = $lastActivity
            Virtual             = $Virtual
            IPAddress           = $IPAddress
            VPN                 = $VPN
            Pinging             = $Pinging
            WinRMconnected      = $WinRMconnected
            AV                  = $AV                 
            TamperProt          = $TamperProt         
            AntiMalware         = $AntiMalware        
            AntiSpyware         = $AntiSpyware        
            BehavMon            = $BehavMon           
            OfficeAV            = $OfficeAV           
            NIS                 = $NIS                
            AccessProt          = $AccessProt         
            RealTimeProt        = $RealTimeProt       
            Finished            = $Finished
        }

Is there easy and elegant way to get output consisting of NAME and LAST_LOGON_TIME

    $computername = ($computerArray | Where-Object {($_.WinRMConnected -ne 'True') -and ($_.Managed -ne 'True')}).ComputerName
    $lastActivity = [datetime]::FromFileTime((Get-ADComputer -Filter 'Name -eq [COMPUTER NAME FROM ABOVE]' -Properties *).lastLogonTimestamp)

, one by one?

The best way I figured is to create hash table (using foreach - going through all computers in array) of these two values and then print it. 

TahnX a lot for any idea.

Murphy


Install-Script in startup script?

$
0
0

Anyone had trouble installing scripts via startup script?

I am simply doing

Install-Script -Name Get-WindowsAutoPilotInfo -Force

It doesn't error or anything, but isn't there in program files so I cant use it in the next few lines of codes , have run some checks to make sure it's running elevated and it seems fine , which I thought would be the only requirement

Powershell script executes differently from the registry

$
0
0

I'm trying to use HKLM\Software\Microsoft\Active Setup\Installed Components\ to run a powershell script once for any user that logs on to a Windows 10 standalone machine.

Here's an example of how I've set up the registry.

I created a key at the "Installed Components" level and added:

StubPath = %SystemRoot%\system32\WindowPowerShell\v1.0\powershell.exe -file “c:\ops\bin\run_once_logon_script.ps1”

Version = 1,0,0,0

I know this is working correctly as it creates the key and version at HKCU with the same path and in early testing it was executing part of the script.

I've written a simple version of a script for testing.  Where I seem to be having issues is getting it to drop a log.  This may be the result of variable substitution or calling a 2nd script.  When I run the script manually from a powershell prompt it executes correctly.  When it runs from the registry its not creating a log file.  My assumption is that when I login with the user, it executes that script from the registry as that user? 

Here's the test script.  I had to add the "cd c:\ops\bin" when executing from the registry. 

##################################
# call environment variable script
##################################
cd C:\ops\bin
. ./set_opsenv.ps1
# sets $strOpsRoot, $strOpsBin, $strOpsData, $strOpsLog, $strOpsTmp, $strOpsTools, $strHst

###########################
# variables used by script
###########################
$strScriptName = $MyInvocation.MyCommand.Definition
$strDate1 = Get-Date                # used in header lines in logfile
$strDate2 = Get-Date -format s           # used by FuncLogWrite
$strLog = “$strOpsLog\run_once_logon_script_$env:UserName.log”

#troubleshooting variable expansion from registry
Write-Host $strOpsLog
Write-Host $strOpsBin
Write-Host “this is ops bin $strOpsBin”
Write-Host “this is scriptname $strScriptName”
Write-Host “this is the log $strLog”

Write-Output $strOpsLog | Out-File -Append -FilePath $strLog
Write-Output $strOpsBin | Out-File -Append -FilePath $strLog
Write-Output “this is ops bin $strOpsBin” | Out-File -Append -FilePath $strLog
Write-Output “this is scriptname $strScriptName” | Out-File -Append -FilePath $strLog
Write-Output “this is the log $strLog” | Out-File -Append -FilePath $strLog
exit

Any insight would be appreciated. 

Need help modifying a value in XML

$
0
0

Hi Scripting Guy,

    I am trying to figure out how to resolve a problem with an XML file used for configuring some software. Here is a snip of the XML:



My goal is to read the Value of AutoLogin and if it is set to "True" the value needs to be changed to "False". I would also like to look at the Value of "ServerName" and if it isn't set to the correct server, it should update based on what it is set to.

I started with the following code to detect but I cannot figure out how to modify and write the updated XML back:

I appreciate any assistance you can provide.

Making this change will help reduce excess Autodesk Vault license consumption by the add-ins associated with applications like AutoCAD.

Powershell to set Not configured to a GPO

$
0
0

Hi,

I want to set a GPO "configure windows automatic update" to "Not configured". I tried to delete the regkey but it generates again.

Thanks

.bat script runs fine but hangs via scheduled task

$
0
0

have a .bat script which runs perfectly when manually running or calling via command line. The script calls a foxpro exe which outputs 10 csv files from a system then calls a powershell script to rename and move files to another server

When running through scheduled task the exe is called, it runs fine and outputs 7 csv files as normal and always hangs on the 8. cpu activity for the exe drops to 0 and no activity again until its killed in task manager. The task continues then and calls the powershell script and it completes. 

Scheduled task is set to run with the correct user with highest priviledges and whether they are logged in or not.

Any ideas would be greatly appreciated. Thanks

Viewing all 15028 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>