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

"Microsoft.XMLDOM" vs "Msxml2.DOMDocument.3.0"

$
0
0
Hello,
I am new to the Win32 scripting env (coming from UNIX env).
I have been reviewing info on MSDN for Microsoft's XML Parser and I am very confused. I am working with VBScript and JScript under WSH.
I see different ways to initiate XML Parser but I don't understand what is the difference between them?
I see examples such as:
Code:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
var xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
Set xDoc = New MSXML.DOMDocument
var srcTree = new ActiveXObject("Msxml2.DOMDocument.5.0");
Dim xmldom As MSXML2.DOMDocument
xmldom = New MSXML2.DOMDocument

Does XLMDOM access the XML Parser in msxml.dll and Msxml2.DOMDocument.5.0 and also MSXML2.DOMDocument?
Why are there so many different versions?
Is one better than the other? I have been told to only use XMLDOM and other people have told me I have to use "Msxml2.DOMDocument.3.0". I am doing simple xml doc load and parsing.
Thanks if someone can un-confuse me!

Styx

Collecting CPU, GPU and operating logs

$
0
0

I would like to write a windows script, but I don't know where to start.  My goal is to log my cpu, cores, and GPU temps to a database that resides in a different machine.  I have tried using WMIC commands, but apparently functionality with WMIC is mobo dependent and my ASUS board doesn't play nice with temp queries.  

ASUS has some software that provides all of the data that I want and more, but there doesn't seem to be any way to export it.

Using CoreTemp or RealTemp is a start, either of those are capable of outputting the cpu temps at the intervals that I specify into a CSV.  In the case of CoreTemp, at least, the CSV that contains the data is updated with the new data at the interval specified, and the file name is changed to a  name containing the timestamp.  

Questions:

1. CoreTemp, RealTeamp and NZXT Cam are all capable of reaching in to a lower level and pulling  out the data that I want, regardless of the mobo manufacturer.  How can I do it too?

2. If I use the the CSV that CoreTemp logs, how would that script look?  I was thinking of duplicating the csv and then renaming the duplicate to a constant name, so that it is constantly updated with new info.  Then using PSCP to transfer the file to my db host.    

Is there a better way?

3. It would be really nice if I could use a message protocol like MQTT or STOMP or something to send the data to the db host machine.  Is this possible?

This is my first time trying windows scripting, All ideas and input are welcome!

Using credentials with script

$
0
0

Hi

We are using a script and has to pass different credentials for each server, we use below method to collect the credentials 

$PWD1=Read-Host -assecure 
$PWD1 | ConvertFrom-SecureString

With a CSV file we use header Server,Username,Password and then mention each server name, user name and Credential from $PWD1 for each accounts. With the script below are the main section that uses these credentials

                          

$Computers=Import-csv "D:\PSS\Systems.csv"

ForEach ($system in $computers) 
{
$server = $computer.server
$username = $computer.username$passwd = $system.password | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential -argumentlist $username,$passwd
$NICs = GWMI -comp $server Win32_networkadapterconfiguration -Credential $cred -ErrorAction Stop | Where-Object {$_.IPEnabled -eq $TRUE -and $_.DHCPEnabled -eq $False}

Here we want to know whether this is the secured way of passing credentials or there a better option available for doing this?

Thanks in advance


LMS

A better way to do this?

$
0
0

Hey everyone.

I've been using a powershell script I pieced together to dump systems from AD and determine if they are 'stale'.

This script has worked perfectly fine for a few years, but not I'm running into the 'invalid enumeration context' error with get-adcomputer.

My script is now taking over 30 minutes to run and thus producing the above error.

Here is the code:

$d = (Get-Date).AddDays(-90)
$default_log = $env:userprofile + '\Documents\AD_Computer_Report.csv'

Foreach($domain in (get-adforest).domains){
Get-ADComputer  -Filter {(isCriticalSystemObject -eq $False)} -Properties UserAccountControl,`
PwdLastSet,WhenChanged,samAccountName,Name,LastLogonTimeStamp,Enabled,admincount,IPv4Address,`
operatingsystem,operatingsystemversion,serviceprincipalname,description  -server $domain |
select @{name='Domain';expression={$domain}}, `
Name,operatingsystem,operatingsystemversion,Enabled,IPv4Address, `
@{Name="Stale";Expression={if((($_.pwdLastSet -lt $d.ToFileTimeUTC()) -and ($_.pwdLastSet -ne 0)`
 -and ($_.LastLogonTimeStamp -lt $d.ToFileTimeUTC()) -and ($_.LastLogonTimeStamp -ne 0)`
  -and ($_.admincount -ne 1) -and ($_.IPv4Address -eq $null)) -and `
  (!($_.serviceprincipalname -like "*MSClusterVirtualServer*"))){$True}else{$False}}}, `
@{Name="ParentOU";Expression={$_.distinguishedname.Substring($_.samAccountName.Length + 3)}},description `
| export-csv $default_log -append -NoTypeInformation}

I'm trying to build a new script that uses adsisearcher instead, but I'm not able to figure out how to pull the IP address, enabled status, or parent OU.

Here is that script:

$default_log = $env:userprofile + '\Documents\Updated_AD_Comp_Report.csv'
$searcher = ([adsisearcher]"(&(objectclass=computer))")
$searcher.PageSize = 200
#$searcher.SizeLimit = "5"
$searcher.PropertiesToLoad.AddRange(('UserAccountControl','PwdLastSet','WhenChanged','samAccountName','Name','LastLogonTimeStamp','Enabled','admincount','IPv4Address','operatingsystem','operatingsystemversion','serviceprincipalname','description'))
$output = 
Foreach ($ComputerAccount in $searcher.FindAll()){
    New-Object -TypeName PSObject -Property @{
        UserAccountControl = $ComputerAccount.properties.useraccountcontrol -as [string]
        PwdLastSet = $ComputerAccount.properties.pwdlastset -as [string]
        WhenChanged = $ComputerAccount.properties.whenchanged -as [string]
        samAccountName = $ComputerAccount.properties.samaccountname -as [string]
        Name = $ComputerAccount.properties.name -as [string]
        LastLogonTimeStamp = $ComputerAccount.properties.lastlogontimestamp -as [string]
        Enabled = $ComputerAccount.properties.enabled -as [string]
        admincount = $ComputerAccount.properties.admincount -as [string]
        IPv4Address = $ComputerAccount.properties.IPv4Address -as [string]
        operatingsystem = $ComputerAccount.properties.operatingsystem -as [string]
        operatingsystemversion = $ComputerAccount.properties.operatingsystemversion -as [string]
        serviceprincipalname = $ComputerAccount.properties.serviceprincipalname -as [string]
        description = $ComputerAccount.properties.description -as [string]
    }
}
$output | export-csv $default_log -append -NoTypeInformation

Ideally I would be able to get my original script working using get-adcomputer, but I'm open to any recommendations.

Thanks for any help!


Powershell Export is not displaying records in CSV export file

$
0
0

$PRDATA = Import-CSV C:\Users\xxx\Documents\HR_List.csv $output=@(); ForEach ($user in $PRDATA) {

#build employeeid correctly if ($user.EmployeeID.Length -eq "7") { $EmployeeID = "0" + $user.EmployeeID } ELSE { $EmployeeID = "00" + $user.EmployeeID } #build emailid correctly $FirstFilter = $user.Firstname $FirstFilter = $FirstFilter.replace(' ','') $SecondFilter = $user.Lastname $SecondFilter = $SecondFilter.replace(' ','') $NewEmailID = $FirstFilter + "." +$SecondFilter + "@abc.co.uk"; if ($user.SamAN_Created -gt "1") { $SamAN_Created = $user.SamAN_Created.replace(' ','') +"@abc.co.uk" } ELSE { $SamAN_Created = $FirstFilter + "." + $SecondFilter +"@abc.co.uk" } Write-Host " EmployeeID exists: " + "$EmployeeID" + " " + "Email ID Exists" + "$SamAN_Created"; $output += "$EmployeeID" + "," + "$SamAN_Created"; } $output | Export-CSV -Path "H:\MyDATA\PowerShellScripts\HRList_vs_AD\MatchingList.csv" -NoTypeInformation

Any suggestions are highly appreciated.  The Write-Host list the formatted data on the screen but the csv is not showing any data or sometimes is just disaplying  column title as "length" nothing else.

learner


How to rename files from format xxxxxx-n-yyyyyy.ext to yyyyyy-n-xxxxxx.ext

$
0
0

Hello, scripting guys

Is there any script that I can use to rename all files in a folder from xxxxxx-n-yyyyyy.ext to yyyyyy-n-xxxxxx.ext? 

Thanks

Advanced function Pipeline parameters

$
0
0

I want to use a CSV file to feed the parameters of powershell cmdlet

Role, email, fname, lname
Admin, a@b.com, John, Smith

I want to process a cmdlet as follows:

import-csv myFile| mycmdlet | export-csv myresults

I also want to be able to call the cmdlet like this

mycmdlet -role x -email j@b.com -fname John -lname Smith

and see a result as an object like:

lname: "Smith"
fname: "John"
email: "j@b.com"
role: "X"
ResultData: "something else"

I didn't want to have to do this:

import-csv X.txt | foreach-object { mycmdlet -email $_.email } 

In the powershell I wanted to do something line this:

function global:test-Pipeline{
param(  
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][String[]]$role, 
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][String[]]$email, 
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][String[]]$fname, 
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][String[]]$lname ) 

$result = new-object psobject

process {
   foreach($address in $email)
   {
       Do something with each role, email, fname lname
       Add output to $result
   }
}

End {
    return $result
}

}

I'm sure this must be possible, how do i do it? Can it be done without having to process the CSV in the cmdlet?



Error in PS Script

$
0
0

Hello,

Getting started with PS scripting and putting together few scripts that helps in my day to day work. I am receiving the below error when I try and pass few parameters in the below script. The details are as below. What am I doing wrong ?

Script I am running is below. 

Param (
[Parameter(Mandatory=$True)]
[string]$Name,

[Parameter(Mandatory=$True)]
[string]$Description)

New-CMAntimalwarePolicy -Name -Policy ExclusionSettings -Description -Verbose

It asks me to enter Name and Description just fine but when I hit enter again I get the below error.

New-CMAntimalwarePolicy : Missing an argument for parameter 'Name'. Specify a parameter of type 'System.String' and 
try again.
At line:9 char:25
+ New-CMAntimalwarePolicy -Name -Policy ExclusionSettings -Description  ...
+                         ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-CMAntimalwarePolicy], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.ConfigurationManagement.Cmdlets.EP.Commands.NewAntimalwarePoli 
   cyCommand


Naga Sai Jonnavithula


Automatically Enable or Disable Jobs Based on HADR Role

$
0
0

Hi,

I have implemented alwayson availablity group. I want to jobs to be run on primary server. So how will we enable and disable jobs. Please provide step by step implementation.

Thanks

Find ManagedObjects from user

$
0
0

Hi All

I am trying to find if a particular user is owns any Distribution list as part of the managed objects. I was able to get the list of the DL's the user owns but I am getting the DL with the Distinguished name and i am unable to select only the Distribution List Display Name.

$Managedgrp = Get-ADUser -Identity 'Samaccountname' -Properties managedObjects
Write-Host $Managedgrp
$Groups = $Managedgrp.managedObjects -split(',') | Select-String -Pattern "CN=\"
Write-Host $Groups

I am unable to get the string which starts with CN=\ and I want to trim these characters to get the display name of the DL


Justin

Self-signed certificates sha256 iis 8.5

$
0
0

Hi.I hope you can help me.
I have no idea about windows commands.


I have a problem with a .net web application.I have it hosted in iis 8.5 and windows 8.1 pro.The problem is that self-signed certificates of iis 8.5 by default use sha1 and I need a self-signed certificate sha256.


I was looking at this post (
https://gallery.technet.microsoft.com/scriptcenter/Self-signed-certificate-5920a7c6) and I really do not know how to use it less for iis 8.5
Any step by step that you can give me?


Thank you.-

Trying to get this to work: "Move and Disable inactive computer accounts from Active Directory"

$
0
0

Hello,

I've been trying to get the Powershell script "Move and Disable inactive computer accounts from Active Directory" working in my environment. http://gallery.technet.microsoft.com/scriptcenter/Move-and-disable-inactive-b1cf86c3

I have been unable to make this script work. I receive the below error. Any ideas? I have the Quest AD Management Shell 1.6.0 installed.


Get-QADComputer : Cannot bind parameter 'InactiveFor'. Cannot convert value "60-SizeLimit" to
type "System.Int32". Error: "Input string was not in a correct format."
At C:\Utilities\MoveInactiveComputers.ps1:30 char:30
+ Get-QADComputer -InactiveFor $NumOfDaysInactiveFor-SizeLimit 0-SearchRoot $searc ...
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-QADComputer], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Quest.ActiveRoles.ArsPowerShellSnapI
   n.Powershell.Cmdlets.GetComputerCmdlet

Powershell Script to reset Local Administrator password

$
0
0

Hi,

I have a script which is to reset local administrator password of remote machines and I have mentioned the host list in the script.But just would like is there any way, so that we can add line in my script, so that this will reset the administrator password of all machine which is there in a specific set of subnet(example :10.241.1.0 and 10.241.2.0) in a domain ?

Can anyone help me with that ?

$computers = Get-Content -path C:\hosts.txt
$user = "Administrator"
$pass = "password1"

Foreach($computer in $computers)
{
 $user = [adsi]"WinNT://$computer/$user,user"
 $user.SetPassword($pass)
 $user.SetInfo()

800704A6 a system shutdown has already been scheduled vbscript

$
0
0

I'M trying to luanch .vbs file located on a shared drive.  It works on my friend machine ,but when i try to launch it , I get below error :

a system shutdown has already been scheduled  

code:800704A6

source:null 

upload a file to SFTP Filezilla

$
0
0

I will like upload a file to SFTP Filezilla but I have an error message and I can not solve my problem

$ftp = "Address"
$Username = "username" 
$Password = "password" 
$Localdir = "address\test.docx"

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)

foreach ($item in (dir $Localdir "*.docx")) {"Uploading $item..."
    $uri = New-Object System.Uri($ftp+$item.Name) 
    Write-Output $uri,$item.FullName
    $webclient.UploadFile($uri, $item.FullName)  
}

When I execute my script, I have an error message :

Exception when calling "UploadFile" with "2" argument (s): "An exception occurred during a WebClient request.

To the character C: \ Users \ PCA \ Downloads \ powershell \ test4 - to see.ps1: 15: 5

+ $ webclient.UploadFile ($ ftp, $ item) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException

How resolve this problem ? (I execute this script with on windows 10 and the version powershell is 5.1)


Set-FSRMFileGroup fails

$
0
0

All,
I’m trying to run a simple bit of Powershell to automate a task. Here’s the Powershell.

$safe_list = Get-Content C:\Scripts\Malware\Safelist.txt
$block_list = Get-Content C:\Scripts\Malware\Blocklist.txt
Set-FsrmFileGroup -Name "Anti-Ransomware File Groups" -IncludePattern ($block_list) -ExcludePattern ($safe_list)

Nothing clever there, right? So here’s my problem. If I launch Powershell on the server2012R2 as administrator, it prompts for UAC and runs, no problem. The problem comes when I try to run the script as a scheduled task. Even run as NT_Authority\System and “Run with highest privledge”s ticked, the command

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

With parameters

-Execution-policy Unrestricted -file C:\Scripts\Malware\SetFSRMGroup.ps1

fails to actually run (it gives every impression of running but terminates with a code of 2147942401 (0x80070001) and doesn’t update the FileGroup). Now, I’m not sure if this is because of UAC or that the SYSTEM account doesn’t have authority to the location that FSRM stores its file groups (I’ve also tried this as the local machine administrator and NT_Authority\LOCAL SERVICE accounts with the same results). I’ve done a quick trawl of the registry to see if FSRM stores the file groups there but it seems not.

Now, if I can’t get this to run as a scheduled task, then this is of no practicable use to me; running it manually is not a path I’m going down (nor is disabling UAC). I'd assume that having provided the Powershell Command-lets MS would expect this sort of thing to be scripted. The question is how to elevate the script to run unattended without trying to bypass UAC. Any insights?

Pete

PS I don't think I'm trying to bypass UAC, I very much want this to work with UAC.

Resetting Local Admin Passwords with PowerShell

$
0
0

Hello,

So I've been following along with an article I found on these forums to reset the password of a local account.  However the cmd's used appear to be a little dated, as PS seems to not recognize them from any module. However I kept digging and seem to have found that this "Reset-ComputerMachinePassword" may be my best bet. However I don't see how to:

A: Specify that I want a specific local account password reset (not just the Win Admin account)

B: Specify the exact password I want it reset to

The cmd I'm using is:

Invoke-Command -ComputerName "COMPUTER1" -ScriptBlock {Reset-ComputerMachinePassword -Credential adminaccount}
it works as expected, prompts me for signing in to my admin account and I get no output or anything like that. However when I go to sign on to our local IT account the password is the same and there is no difference. Any help is greatly appreciated!

How to use foreach to load xml content for multiple servers

$
0
0

Hi,

there is a list of servers and I want to use foreach loop to load xml data from each server and produce an output. below is sample script:

$serverlist = gc ".\list.txt"

foreach ($server in $serverlist)

{

$xml = New-object xml

$xml.load (\\$server\c$\xmlfile)

write-host $server: $xml.hardwaretype

}

VBScript Error: Invalid procedure call or argument

$
0
0

I have the below code. I am getting an invalid call or procedure at this statementfiletxt_Risk_Details.WriteLine(All_Record_Risk_Details).

I am reading from the excel file and converting it into Risk_Details.csv file
Can someone please tell me what's wrong with below script.

Header_Risk_Details
="Risk_No"&delimter&"Project_Number"&delimter&"Risk_Description"&delimter&"Risk_Owner"&delimter&"Risk_Management_Plan"&delimter&"Risk_Full_Impact_For_Open"&delimter&"Risk_Category"dim filesys_Risk_Details, filetxt_Risk_Details Set filesys_Risk_Details = CreateObject("Scripting.FileSystemObject")Set filetxt_Risk_Details = filesys_Risk_Details.OpenTextFile(Save_Projects_Risk_Details, ForWriting ,True,True) filetxt_Risk_Details.WriteLine(Header_Risk_Details) c=24DoWhile c <300 Risk_No=Replace(objXLWs.Cells(c,"B").Text,vbLf,"<br>") Risk_Description=Replace(objXLWs.Cells(c,"C").Text,vbLf,"<br>") Risk_Owner=Replace(objXLWs.Cells(c,"D").Text,vbLf,"<br>") Risk_Management_Plan=Replace(objXLWs.Cells(c,"E").Text,vbLf,"<br>") Risk_Full_Impact_For_Open=Replace(objXLWs.Cells(c,"F").Text,vbLf,"<br>")if Risk_Description="Risk Description for Contractual Penalties (CP)"and Risk_Full_Impact_For_Open="Full Impact for open CP Risks"then Risk_Category="Risks Contractual Penalties"endifif Risk_Description="Risk Description for ALL OTHERS"and Risk_Full_Impact_For_Open="Full Impact for open Other Risks"then Risk_Category="Risks All Others"endif All_Record_Risk_Details= Risk_No&delimter&Project_Number&delimter&Risk_Description&delimter&Risk_Owner&delimter&Risk_Management_Plan&delimter&Risk_Full_Impact_For_Open&delimter&Risk_Category filetxt_Risk_Details.WriteLine(All_Record_Risk_Details)'Error c = c +1Loop

thanks

Bhavesh

Powershell: change default datetime format in script?

$
0
0
Hi,

I have an html report in which I include dates.
Now these dates appear in month/day/year. I want to prevent to need to change every date to format dd/mm/yyyy.
Practical example in SCCM:(Get-CMDeployment -CollectionName $CollectionX).deploymenttime gives 11/15/2017 09:15:33
whereas it should be 15/11/...

Is there a way to set it in beginning of script so dates are in correct format?
Tried
Set-Culture -CultureInfo de-de but that does not work.

Please advise.
J.

Jan Hoedt

Viewing all 15028 articles
Browse latest View live


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