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

foreach not working

$
0
0

Hi all, Iam running the powershell script below, but I get an error. I can't figure out why it doesn't work, other than that the output of the earlier get in $users gives the wrong output format. I don't know how to get this right. 

$users = get-msoluser -all | where-object {$_.validationstatus -eq 'error'} | select ObjectId
foreach ($user in $users) {
$errors = (Get-Msoluser -ObjectId $user).Errors
$errors | foreach-object {"`nService: " + $_.ErrorDetail.Name.split("/")[0]; "Error Message:"+ $_.ErrorDetail.ObjectErrors.ErrorRecord.ErrorDescription}

}

Error:

Get-MsolUser : Cannot bind parameter 'ObjectId'. Cannot convert the "@{ObjectId=009f1ee5-f9a4-4dee-b513-4487cdca043e
}" value of type "Selected.Microsoft.Online.Administration.User" to type "System.Guid".
At C:\temp\AdSyncError.ps1:3 char:36
+     $errors = (Get-Msoluser -ObjectId $user).Errors
+                                       ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-MsolUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Online.Administration.Automation.GetUser

You cannot call a method on a null-valued expression.
At C:\temp\AdSyncError.ps1:4 char:28
+ ... ach-object {"`nService: " + $_.ErrorDetail.Name.split("/")[0]; "Error ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull


Automate copying emails to a offline folder via powershell

$
0
0

I'm looking to see if there is a way through powershell to copy emails from a folder within an Exchange online Outlook email to a offline folder.

From what I've researched, copy-items is only folder to folder. I looked into a MS article, which shows using a moveitems command, but only works within the mailbox.

Stumped on what commands could be used to do this, copying to .pst cannot be done since I need the messages themselves copied to an offline folder.

Any pointers would be appreciated.

Using application function return values in xml

$
0
0

A 3rd party application (written in c++) has two functions shown bellow:

int func1 ()

void func2 (string , int , int)

The application has an XML configuration file of which the two lines portion is shown bellow,

<element1name="first-element"> {function1()} </element1><element2> function2("Hello World", 5, 10) </element2>

element1 gets value from function1 return value and shows it, no problems.

element2 includes the function to be called in the application when “F1” is pressed.

Problem is,

When i use hard coded parameters for function2 in element2

<element2> function2(“somestring”, 5,10) </element1>

Works ok.

But , When i use

<element2> function2(“somestring”, 5, { function1() }) </element2>

It does not work.

So the question simply is how to code elemet2 line as to include a function return value as a hard coded paramater in order to be correctly parsed by the application .

Thank You.

Note : element1 is #PCODE , element2 is #PCODE


Our motto ist bonum Facimus.

Retrieving a list of DCOM application identifiers using Foreach loop and automatically formatting result array using Format-Table

$
0
0

Howdy,

I want to obtain information about registered DCOM applications using Get-WMIObject and then loop through the collection of obtained object to obtain specific properties.

Then I create a PowerShell object and add obtained properties to this object. This is only to format the obtained list into a table.

That's what I come with:

Function Get-AppID {

$strComputer = "."  
$colItems = Get-WmiObject -class "Win32_DCOMApplication" -namespace "root\CIMV2" -computername $strComputer  
$DCOM = @()
$DCOM = foreach ($objItem in $colItems) {

New-Object -TypeName PSObject -Property @{

        Name = $objItem.Name     
        AppID = $objItem.AppID 
        Caption = $objItem.Caption 
        Description = $objItem.Description
        }
    }
} 

Now I want this to be formatted by using:

Get-AppID | Format-Table -AutoSize

Looks like what I am doing is completely wrong because I end up with an empty array.

Could somebody please help me to fix this script?

Thanks.


Well this is the world we live in And these are the hands we're given...

Script to Logoff a Session (Moving Parts)

$
0
0

Is it possible to script out logging of a user's session when it meets the following crtiera?

  1. The user has been logged in for X amount of time, let's say 3 days. If so....
  2. The system has become idle for X amount of time, let's say 60 minutes.
  3. Log the user off.

We've worked on tasks that will logoff after idle, but, we want it to only take place after a user has been logged into a Windows session for a set amount of time. We're having trouble trying to daisy chain these 2 variables together. Is something simple out there that we're simply overlooking?

Changing a UPN to GivenName.SurName@Domain.com

$
0
0

Hi, 

I see plenty of posts regarding changing the domain suffix of a UPN from something like @domain-name.local to @public-domain.com, and thats fine. I've got a client whose logon names are 'firstname lastname' (WITH A SPACE IN THEM)

They need to do a directory sync with a third party vendor, and their UPNs need to be first name.lastname@public-domain.com

Question 1

If I change their login name from 'pete long' to 'pete.long', when they logon to their client machines, will they successfully logon with their SAMaccountName (which will still be 'pete long') will this continue to work? Or will it logon with a temporary profile, (so the user assumes they've lost all their data).

Question 2

As I said I can change the domain portion of the UPN easily, how can I script changing all the 'User Logon Names' that contain a space. (some don't annoyingly!) To first name.lastname?

Regards,

Pete


Regards Pete Long http://www.petenetlive.com


Powershell Message Event Log Search FilterHashTable

$
0
0


I am using PowerShell to sift through my event log in event viewer. The challenge is to locate specific character sets inside the message detail and to display both the events with those character sets and the individual character sets themselves. Right now, I have the following:

Get-WinEvents -FilterHashTable @{LogName="Application", id=1035} -MaxEvents 10 | where {$_.message -like "*Visual C++*"}

This script will return the events that have messages with Visual C++ inside, however, there are sets of about 7 characters after that ranging in letter and number. I need to extract those 7 characters and print them exclusively. Thank you for all help.

Extracting Data from KB Articles

$
0
0

Does anyone know what to navigate through all the JavaScript that Microsoft KB articles use via PowerShell and extract text.

For simpler pages I'm able to use tags but I have not been unable to understand the design of these pages. I know since there are probably of hundreds of thousands articles these pages are probably just render from some database with this info.

The use case is be able to add beneficial KB article information (i.e. Known Issues text) to a customized report so that patches can be highlight for known issues and support teams can then access KBs for more details.

Example article with known issue section: https://support.microsoft.com/en-us/kb/3177725

$uri = 'https://support.microsoft.com/en-us/kb/3177725'
$html = Invoke-WebRequest -Uri $uri
$html.ParsedHtml
Above is how it general starts for these types of scripts but having trouble navigating. Any help or guidance will be appreciated!

Powershell to export Access 2010 query to CSV file

$
0
0

I  am trying to use Powershell to connect to a query within an Access database and dump its contents to a CSV file. I am trying to use the Get-DatabaseData function I found on Technet

$FilePath = "\\Fileserver\Share\Database.accdb"
$connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$FilePath;"
$query = "SELECT * FROM [qry QueryName]"

Get-DatabaseData -verbose -connectionString $connect -query $query

When I run the above, I just get a 0 back for results. When I execute the query command within Access, it returns the expected results (i.e. there is actual data to return). Can anyone point me in the right direction? I have worked with Powershell but not with Access all that much.

How to Combine results for Get-WmiObjects into a single CSV file (Powershell)

$
0
0

I need to take the output from multiple WmiObjects and pipe them to a single CSV file. I've read a 'Foreach' loop might be a plausible solution. Any help would be appreciated. Thank you

#####################################

# Collect system profile information for MySQL database.

#####################################

$today = get-date -UFormat "%Y-%m-%d"
$ExportFilename = "Discovery__" + $today + ".csv"
$Path = 'C:\scripts\inventory\'

$Computer_System_Discovery = @('Manufacturer', 'Model', 'OEMStringArray', 'SystemType', 'TotalPhysicalMemory')
$BIOS_Discovery = @('Status', 'Name', 'Biosversion', 'Description', 'Manufacturer', 'Serialnumber')
$Motherboard_Discovery = @('Description', 'Manufacturer', 'Model', 'Product', 'SerialNumber')

Echo 'Computer System Discovery'
Get-WmiObject win32_ComputerSystem  | Select $Computer_System_Discovery | Export-Csv -Path ($Path + 'ComputerSystem_' + $ExportFilename)  -Encoding UTF8

Echo 'BIOS Discovery'
Get-WmiObject -Class win32_bios | Select $BIOS_Discovery | Export-Csv -Path ($Path + 'BIOS_' + $ExportFilename)  -Encoding UTF8

Echo 'Motherboard Discovery'
Get-WmiObject win32_baseboard  | Select $Motherboard_Discovery | Export-Csv -Path ($Path + 'MotherBoard_' + $ExportFilename)  -Encoding UTF8

Powershell

$
0
0

Hi All,

I am trying to convert few .CMD scripts into Power-shell scripts.

In my .CMD scripts I am using perl scripts and SQL queries also.

I am new to power-shell so need help for the conversion.

Below is the .CMD script--

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp" New_Sales.dbo.newload in d:\ftphome\NewSales\NewTrk.dat -c -t~ -o d:\ftphome\NewSales\bcp.out -S%1 -U%2 -P%3 -h "TABLOCK"
Perl d:\ftphome\NewSales\check_status.pl d:\ftphome\NewTruckSales\bcp.out 

Thanks..

Create a Powershell script to automatically email all the groups for PNR Windows OS Security Patching

$
0
0

Hello all!

I'm very new to powershell scripting. I was working on a issue to try and speed up our patching process.  I'm trying to create a script that can be executed at the end of the Windows OS Security patching for the Patch & NoReboot groups to send the reboot needed emails.  The script should take the list of patched servers from the current run and then email the owners that the patching is complete and they need to reboot. We usually have to send out many many emails one at a time, that can sometimes take a couple hours, just to ask people to reboot their servers. Any help on this topic would be greatly appreciated. 

Thanks!

Create Shortcut In My Network Places Using PowerShell

$
0
0
Hello!  How can one create a shortcut in My Network Places using PowerShell? I found a method described using VB at http://blogs.technet.com/heyscriptingguy/archive/2005/05/09/how-can-i-create-a-shortcut-in-my-network-places.aspx, but it does not create the shortcut in the same way that the native Windows GUI creates it.  Unfortunately, Group Policy Preferences does not help either since it does not create a proper shortcut in the NetHood folder (it simply creates a shortcut instead of creating a folder with target.lnk and desktop.ini). 

I found another VB solution at http://bartdesmet.net/blogs/bart/archive/2005/09/23/3554.aspx that does correctly create the network location the same way the native Windows GUI does. Is there an easier method to accomplish this using PowerShell?

Thanks.

Add a Network Location via Script

$
0
0

I am looking to script some office standard "Network Locations" which happen to also be DFS shares. We have some software (AutoCAD & Revit) that really doesn't like accessing DFS shares directly, but will work happily with a Network Location that points at a DFS share. But I can find no automated way to roll these out, just going machine to machine manually right clicking Computer in Windows Explorer and choosing Add a Network Location. Five Network Locations, multiple clicks each, and 30 users, makes this a lot of work. Hopefully there is a PowerShell or WindowsScriptHost alternative.

All machines are Windows 7 x64 if that makes a difference.

 

Thanks!

Gordon

Combining two scripts to send an email for inactive AD accounts

$
0
0

Hi

I need some help in getting the following scripting an email to be sent when an AD account is found to be inactive. I have two scripts which 1) finds the inactive accounts and 2) sends an email, but I need help in passing the results of query one into the email. Queries are as below:

Find AD USERS

get-aduser -SearchBase “OU=xxx,DC=xxx,DC=LOCAL” -filter * -Properties lastlogondate, passwordlastset | Where-Object {($_.lastlogondate -le $30days -or $_.lastlogondate -notlike “*”)-AND ($_.passwordlastset -le $90days) -AND ($_.Enabled -eq $False)} | Select-Object name, lastlogondate, passwordlastset

Send an email

function sendMail{

     Write-Host “Sending Email”

     #SMTP server name
     $smtpServer = “smtp.xxxx.com”

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure
     $msg.From = “fromID@xxxx.com“
     $msg.ReplyTo = “replyto@xxxx.com“
     $msg.To.Add(“toID@xxxx.com“)
     $msg.subject = “My Subject”
     $msg.body = “This is the email Body.”

     #Sending email
     $smtp.Send($msg)
 
}

#Calling function
sendMail


Any help would be greatly appreciated!!



WQL-Statement to check an application's event log

$
0
0

Hello,

I would like to analyze the event log of a special windows application (Windows 7 Enterprise, 64Bit).

I need a special event which is logged some seconds ago.

Here is my VBScript code, which produces a completely wrong result (wrong number of events):

strComputer = "." ' Dieser Computer

' Retrieving Specific Events from an Event Log

Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Const CONVERT_TO_LOCAL_TIME = True

Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
Set dtmEndDate = CreateObject("WbemScripting.SWbemDateTime")

dtmStartDate.SetVarDate dateadd("s", -10, now())	' CONVERT_TO_LOCAL_TIME
dtmEndDate.SetVarDate now()							' CONVERT_TO_LOCAL_TIME

dim var_wql

var_wql = "SELECT *  FROM  Win32_NTLogEvent WHERE Logfile =  '< ... >' AND SourceName = '< ... >' AND EventCode = '< ... >' AND  (TimeWritten >= '" & dtmStartDate & "') AND (TimeWritten < '" & dtmEndDate & "')"

Set colLoggedEvents = objWMIService.ExecQuery(var_wql)

...





  

The number of rows (anzahl = colLoggedEvents.count) must be 0 or 1, anything else is impossible.

What is wrong with the wql statement? I would like to check the last seconds in the past (from now).

Thanks.

Tommy


How to get a list of Domain Admin users from a windows 2003 DC

$
0
0
I'm trying to get a list of domain admin users from a Windows Server 2003 domain controller. I am unable to obtain it with powershell because the ActiveDirectory module is not installed.

I need to obtain it from CMD, or even VBScript

I have tried net group /domain "Domain Admins" and while this returns all the Domain Admin users I need the following format which I don't know how to obtain. Any ideas?

The list should contain:

User name (Baker, John for example)
sAMAccountName (`I can obtain this with net /group`)
Account creation date
Last logon date
If the account is enabled or not

Change Wi-Fi profile order to domain computers in manage wireless networks

$
0
0

Hi,

i want to change the profile order in manage wireless networks and change the connection properties for particular wireless profile setting as uncheck the 1.connect to more preferred network available ,2. connect even if the network is not broadcasting its SSID . this should be done to all domain computers.

Script to restart Service of a Remote Server

$
0
0

Hi

I am starting Patrol Agent service of a server "xxxxxx" from the random server.

while I Run the below CMDlet from the random server:

PS C:\Windows\system32> Get-Service PatrolAgent -ComputerName <random server> | restart-service
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish stopping...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish starting...
WARNING: Waiting for service 'BMC Patrol Agent (PatrolAgent)' to finish starting...

PS C:\Windows\system32> Get-Service PatrolAgent -ComputerName <random server>

Status Name DisplayName
------ ---- -----------
Running PatrolAgent BMC Patrol Agent

It clearly shows that everything is OK and the service is restarted.

But when I login to the server xxxxxx to check the service is restarted or not. There I get no log in the event viewer and the service doesn't restarted in actual as well.

What could be the reason..??

Passing variable as parameter from one batch file to another

$
0
0

Hi,

I'm new to scripting and have been playing around with things today and just encountered something I'd like to understand better. I think it's more of a terminology/semantics question than anything. Hoping someone here can shed some light on this for me.

I have created two batch files: test.bat and test2.bat. 

test.bat has the following code:

@echo off
cls

set /p "_result=Enter 'c' for capture or 'd' for deploy:"
test.bat %_result%

As you can see, I am simply asking for a some basic user input, saving it to variable _result and then passing it onto my test2.bat file. 

First question, is %_result% still considered a variable at the point it is being passed to test2.bat? Or is it more technically sound to refer to it as a parameter? Or is it both a parameter and a variable?

Here is the code from my second batch file test2.bat:

@echo off
cls

if "~%1" == "c" goto :capture
if "~%1" == "d" goto :deploy

:capture
echo _result is %_result%
echo You are in the capture label!!
goto :eof

:deploy
echo _result is %_result%
echo You are in deploy label!!
goto :eof

It seems that when I pass %_result% it is assigned the %1 parameter and thus the above code works fine. However, if I ECHO _result in my second batch file test2.bat it returns the value assigned to it in the previous batch file test.bat. So it appears that my _result variable holds the previously assigned value from test.bat.

I am curious as to why _result variable is still valid in test2.bat when it was declared and assigned its value in test.bat? The only reason I can think of is if when I call test2.bat and pass %_result% it retains its attributes as a variable. 



Viewing all 15028 articles
Browse latest View live


Latest Images