Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Reverse-engineering a PS script

$
0
0

So, I'm reverse-engineering a PS script to add users to AD.

 

I see the script is organized like an old Pascal, or C program.

Some global variables at the top, (actually, that is what I want to ask you about).  Followed by some number of functions,and finally a main body.

What I would like to inquire about are the first two lines of code, they are:

 

ReadExtendedAttributes,  WriteExtendedAttributes

WriteAttributes, Write, Delete, ReadPeremissions, Read,

 

So, what am I looking at?    They don't look like variables, or booleans.   As a group, they look like permissions?

But, what does it mean for these "permissions" to be listed as the first two lines of a script?

 

Thank You.

Regards,

-DW


Script msg-ing list of PCs fails on some

$
0
0

Hi, I'm using PowerShell from my Microsoft System Center Configuration Manager server (SCCM) to message a group of machines via pop-up. The following script works except for the machines that are powered off...and others...for some reason.

$ComputerList=Get-WmiObject-ComputerNameSCCMSERVERNAME-Namespace"ROOT\SMS\site_XXX"-Query"SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID='XXXXXXXX' order by name"|selectName

 

ForEach

 

 

 

($ComputerObjectIn$ComputerList){

icm

 

 

-computername$ComputerObject.Name -scriptblock {msg*"This is a test. Click OK."}

}

There are 110 computers in the collection. The script works perfectly with a smaller collection, say 5 PCs. But when I Try a larger one, some boxes don't display the pop-up. And these boxes work perfectly when I use a smaller collection (and the same script). Is there a limitation here I'm unaware of? Any thoughts? Advice?

Combine and arrange text files

$
0
0

I am using the get-content and sort-object -unique cdmlets to combine text log files via:

(Get-Content .\*ninite.txt) | sort -unique | Set-Contentinstallreport.txt

Example text files are uploaded here.  The unique switch removes duplicates but it also rearranges the text lines.  I would like to have the single OK string be at the top of the lest in the final exported text file.  Do I need to save each line to a hash and rearrange that way first?

saving to WMI fails

$
0
0

Hi folks. i'm trying to make a change to a WMI table but it seems to not save. Can someone please give me insight to what is going wrong? I suspect it has to do with the line that is in bold below. Thanks a bunch

 

$SiteServer = "server1234.site.com"

$SiteCode = "ABC"

$AppName = "WinZip"

 

try {

    Add-Type -Path (Join-Path -Path (Get-Item $env:SMS_ADMIN_UI_PATH).Parent.FullName -ChildPath "Microsoft.ConfigurationManagement.ApplicationManagement.dll")

    Add-Type -Path (Join-Path -Path (Get-Item $env:SMS_ADMIN_UI_PATH).Parent.FullName -ChildPath "Microsoft.ConfigurationManagement.ApplicationManagement.Extender.dll")

    Add-Type -Path (Join-Path -Path (Get-Item $env:SMS_ADMIN_UI_PATH).Parent.FullName -ChildPath "Microsoft.ConfigurationManagement.ApplicationManagement.MsiInstaller.dll")

}

catch {

    Write-Error $_.Exception.Message

}

 

$Applications = Get-WmiObject -Namespace "root\SMS\site_ABC" -Class "SMS_ApplicationLatest" -ComputerName server1234.site.com -Filter "LocalizedDisplayName like 'WinZip'"

foreach ($Application in $Applications) {

    $LocalizedDisplayName = $Application.LocalizedDisplayName

    $CurrentApplication = [wmi]$Application.__PATH

    $ApplicationXML = [Microsoft.ConfigurationManagement.ApplicationManagement.Serialization.SccmSerializer]::DeserializeFromString($CurrentApplication.SDMPackageXML, $true)

    foreach ($DeploymentType in $ApplicationXML.DeploymentTypes) {

        $DeploymentType.Installer.EnhancedDetectionMethod.Rule.Expression.Operands[1].Value = "7.1.1.9" 

 

        # Re-serialize the ApplicationXML object

        $UpdatedXML = [Microsoft.ConfigurationManagement.ApplicationManagement.Serialization.SccmSerializer]::SerializeToString($ApplicationXML, $true)

        # Update WMI object

        $CurrentApplication.SDMPackageXML = $UpdatedXML

        $CurrentApplication.Put()

    }

}

Way in powershell to put "ipconfig /all" into a file

$
0
0

Is there a way in powershell to put "ipconfig /all" into a file say: "c:\Documents\file1.txt"?

Powershell DSC installing applications from SCCM Software Catalogue

$
0
0

Hello,

Currently I am involved in a project to configure and deploy DSC (using the Pull method) for one of our RDS farms.

My question is, is it possible to use SCCM Software Center in conjuction with DSC? E.g. if DSC is configured to install an application is it possible for that installation to come from applications available to the machine via SCCM?

I've searched online and can't find any relevant custom resources.

I think OneGet would be the best method but that is not suitable at this moment in time, instead we would like to manage all of our applications using SCCM.

Thanks for the help,

Ricky.

Broadcast Message with PowerShell ??

$
0
0

We still have over 1,000 Windows XP machines.  We are rolling out Windows 7 workstations but it will take a few months before XP is gone.   For broadcast messages to all systems NET SEND is used. this of course went away in Win7 replaced with the command MSG.     A tech who's no loner with our company wrote a custom .EXE that when run will prompt you for your "Message" and then NET SEND it out to all workstations.  Now that we have about 15% of our company running Win7 this is no longer a usable tool.    So I wanted to solve this problem with PowerShell.

 

I found this code online.

 

$Comp =  

"MG11706" 

$msg = "Place your message here" 

Invoke-WmiMethod -Path Win32_Process -Name Create -ArgumentList $msg -ComputerName $Comp

 

My problem with this is you need all machines in a .TXT file that you read and it would take a long time to cycle through it.  I don't know the inner workings of NET SEND but it would send the message all all machines within a 15 seconds.   

 

Can PowerShell mimic a NET SEND without reading a .TXT file of machine names?   Can it do what NET SEND used too and if so how?

 

 

 

 

use test-connection against all DNS Suffix Search List

$
0
0

So I'd like to ping a list of computer but if I choose test-connection -computername PC01, it will only reply if it's lan connected.

Is there a way, I can use test-connection against all of our 15+ lists?

so our lan computers are on

pc01.lan.dc.companyname.net
or
pc01.lan.dc1.companyname.net

our wireless will spit back

pc02.wlan.dc.companyname.net
or
pc02.wlan.dc1.companyname.net

so on and so forth throughout our domain


SET-ACLs | Double Loop ?

$
0
0


Hello,
I´m still writing on my "Create Network Shares and Security Groups Script
The Script Creates Security Groups in Active Directory based on Folder Names, Servername, ou ..ect.

Folder             Sec Groups in AD
01_Test            Server-OU-01-RO
                       Server-OU-01-RW 
02_Service       Server-OU-02-RO
                       Server-OU-02-RW

This part works well, thanks for your help so far.

What I´m trying to do next is, set this security Groups for each Folder on the Network Share (Folders are created)

So each Folder has two security Groups in Active Directory and I want to match them and set the acl.

My Problem is not the acl or inheritence thing. I dont know how to match them in a Loop (double Loop?)
say ...
foreach ($Folder in $Folders){match These two security Groups (only these two, not all of them)  and set acl..}

 

Can you help me with this? Please let me know, if you Need more Information...

 thanks in advance..

Thomas

 

The file so far..

(Please visit the site to view this media)

 

 

 

Get-CIMInstance Question

$
0
0

All 3 of these lines of code work as expected.

Get-CimInstance CIM_ComputerSystem
(Get-CimInstance CIM_ComputerSystem).Name
(Get-CimInstance CIM_ComputerSystem -Property*).Name

yet this fails.

$machine='m342014' # this is my PC.  Not a remote box
Get-CimInstance CIM_ComputerSystem -ComputerName$machine

-ComputerName is a supported switch for this yet I get this error.  

Get-CimInstance : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests.

 

IF statement with combined comparison not works

$
0
0

Hello everybody,

I try to filter a csv file with the following statement:

get-qaduser -disabled -searchroot "kl.int/KL-Group" | select-object DN,samaccountname  | Export-Csv -Encoding UTF8 -NoTypeInformation $AllDeaktUser
import-csv $AllDeaktUser | ForEach-Object {
if ( ($_.DN -notlike "*,OU=Services,*") -or ($_.DN -notlike "*CN=Phone*") ) {
Add-Content -path $DeaktUser2Move -value $_.DN
 }

The purposeof the scriptisthat alllines with the text",OU=Services,"and"CN=Phone*"will be filtered outandwill not be addedto theadjustedlist.

If I use an IF statement with one filter, the script works: if ($_.DN -notlike "*,OU=Services,*")

Have I maybe a wrong syntax? Please help...

test-connection help..

$
0
0

Hi I'm trying to write a simple script that will pull from DNS a specific set of records then go on to ping the hostnames retrieved.   

 

$hostname=Get-DnsServerResourceRecord -ZoneName dmz.root -Computername DNSSERVER -RRType A | ?{$_.hostname -like "*XYZ*" -or $_.hostname -like "*zyx*"} | select @{name="ComputerName";expression={$_.hostname}} 

foreach ($computername in $hostname)

{(Test-Connection -computername $computername -BufferSize 16 -count 1)}

 

The error I get is 

"Testing connection to computer '@{ComputerName=acomputer}' failed: A non-recoverable error occurred during a database lookup"

I guess this is because "computername=acomputer" is passed along for each object, if I look at the contents of $hostname it all looks correct only the computer names exist, but if I look at whats being passed into $computername I see "@{ComputerName=acomputer}" .  I thought by creating the custom property "computername" only that would be passed along.  How do I get round this with test-connection.  

How does $hostname only contain a single object yet when I look at whats passed on to $computername it has the original records format  @{ComputerName=acomputer}  ?

 

Registry check in logon script

$
0
0

Hi,

We have group policy which adds registry value to HKCU and powershell script as logon script. Problem is that logon script starts before registry is updated.

I need some advice how to check registry using powershell. Timer or something in the beginning of the logon script and script goes on when registry value is ok. Maybe something like below? 

Logon.ps1:

-------------------------------------------------------------------

do
         check registry
while

script continues....

-------------------------------------------------------------------

I'm quite rookie so i need rookie compatible advice :)

Thanks

~ Jukka ~ 

 

If Else Statement

$
0
0

I am this If Else statement that is giving me some trouble. 

     If (($User.Activate -eq 'Y') -and ($User.employeeType -eq 'Student')) {Set-ADUser $User.sAMAccountName -AccountExpirationDate $Null}
   

    Elseif (($User.Activate -eq 'Y') -and ($User.employeeType -eq 'Employee')) {Set-ADUser $User.sAMAccountName -AccountExpirationDate $Null}
   

 Else {Write-Host "Nothing Happened"}
}

I am trying to match to variables and that is not working.  I am just getting the "Nothing Happened".  I've searched and from what I can find the variable matching should be correct.  

Any ideas?

Parse log files using context

$
0
0

Hello,
I am new to Powershell and am trying to parse data from multiple log files.  I was wondering if you gurus could help me.  The data of interest is contained in two successive lines and interspersed throughout the files. 

 There may be no hits on some log files and hundreds of hits on other log files:
 Line-1 has date and time
 Line-2 has the data.

The log format is like this:
Line-1    2015-09-11 01:29:24.13 "System data"                        [EXEC]
Line-2    'CODES'           EXEC   1234ABCD 5678ABCD 9012ABCD 3456ABCD 1234ABCD -1234 A ABC-Dataset-A 1  I

I would like the output in a CSV format with individual columns and titles looking something like this:
Date             time     code-1   code-2   code-3    code-4   code-5     Code-6       dataset  code
2015-09-11 01:29:24 1234ABCD 5678ABCD 9012ABCD 3456ABCD 1234ABCD   ABC   Dataset   A

I've searched the internet and have found several scripts that I was able to modify and get me started but, I have a long way to go!  Any assistance and guidance would be greatly appreciated!

$logfile = Get-Content c:\Tool_Files-Logs\*.log
for ($i = 0; $i -lt $logfile.count; $i++) {
    if ($logfile[$i] -match "'CODES'") {
        if ($logfile[$i - 1] -match "\d{4}-\d{2}-\d{2}" ) {
            $logfile[($i - 1)..($i + 0)] | Out-File  'C:\scripts\Logfile_Parsed.CSV'
        }
    }
    }


Thanks in advance,
Tiago


Obtain directory listing of powershell scripts ... then execute powershell scripts in directory

$
0
0

I'ver been banging my head on this powershell script I am working on, not sure what it is I am missing.

What I'm trying to do is get a directory listing of powershell scripts I created and then execute them.

So far I have tried the following:

# Titanium Graph Generation
$TitaniumGraphUpdates = Resolve-Path ..\*.ps1

foreach ($Name in $TitaniumGraphUpdates)
    {
    Write-Host executing the following .. $Name.Path  

    Invoke-Expression (start powershell (($Name.Path )))
    }

 

What am I missing? another option I was trying was to export the directory to csv import but still unable to execute those scripts.

Any advice or pointers would be greatly appreciated.

Radio buttons handle

$
0
0

Good morning to all, 

I have a created a GUI that looks like Putty. The user may choose between Serial, Telnet and SSH to connect to a host. What I am trying to do is when the user choose the Serial radio button, to disable the group box that I have to input box field for host name or IP, live. I may perform this only once. When the user clicks on Serial Radio button, the group box is disabled, but when the user click on SSH button again is not enabled and vice versa. I also tried to create an infinite loop that checks the status but with no luck. 
Any ideas? 

 

Below is the code I use:

 

 

 

$groupBox = New-Object System.Windows.Forms.GroupBox 

$groupBox.Location = New-Object System.Drawing.Size(3,20) #location 

$groupBox.size = New-Object System.Drawing.Size(220,80) #size 

$groupBox.text = "Hostname or IP adress:" #labeling the box

$Form.Controls.Add($groupBox) #activate the group box

 

 

####################group box type of connection#############################

 

 

$groupBox2 = New-Object System.Windows.Forms.GroupBox 

$groupBox2.Location = New-Object System.Drawing.Size(230,20) #location 

$groupBox2.size = New-Object System.Drawing.Size(250,80) #size 

$groupBox2.text = "Type of Connection" #labeling the box

$Form.Controls.Add($groupBox2) #activate the group box

 

###############Define choise for Serial#########

$Button1 = New-Object System.Windows.Forms.RadioButton 

$Button1.Location = New-Object System.Drawing.Size(15,15) 

$Button1.Size = New-Object System.Drawing.Size(51,20) 

$Button1.Text = "Serial" 

$Button1.Checked = $true

$groupBox2.Controls.Add($Button1)

 

###########Define Drop List for selecting COM port#########

 

$ListBox = New-Object System.Windows.Forms.ComboBox

$ListBox.Location = New-Object System.Drawing.Size(75,15) 

$ListBox.Size = New-Object System.Drawing.Size(60,50) 

$ListBox.Height = 80

$ListBox.DropDownStyle = "DropDownList"

 

[array]$ListBoxArray = "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8"

 

 

ForEach ($Item in $ListBoxArray) {

$ListBox.Items.Add($Item) | Out-Null # 

}

 

$ListBox.SelectedIndex =  # Select the first item by default

 

#$Form.Controls.Add($ListBox)

 

 

 

$groupBox2.Controls.Add($ListBox) 

 

###############Define bchoise for Telnet#########

$Button2 = New-Object System.Windows.Forms.RadioButton 

$Button2.Location = New-Object System.Drawing.Size(15,35) 

$Button2.Size = New-Object System.Drawing.Size(54,20) 

$Button2.Text = "Telnet" 

$groupBox2.Controls.Add($Button2)

 

 

###############Define choise for SSH#########

$Button3 = New-Object System.Windows.Forms.RadioButton 

$Button3.Location = New-Object System.Drawing.Size(15,55) 

$Button3.Size = New-Object System.Drawing.Size(51,20) 

$Button3.Text = "SSH" 

$groupBox2.Controls.Add($Button3)

Compare-Object not working as expected

$
0
0

Hello All Smile

I am using PowerShell v5 on Windows 7

if i do the following

$AA = @{

Name = "Fred Smith"

DOB = [datetime]"1/June/1966"

guid = 222222

}

 

$AB = @{

Name = "Fred Smith"

DOB = [datetime]"1/June/1966"

guid = 111111

}

 

Compare-Object $AA $AB  -IncludeEqual

the result is as follows

InputObject       SideIndicator

-----------       -------------

{guid, Name, DOB} ==

 

but they are no == as the GUID is different in both

Can anyone explain this please?

Thanks

AAnotherUser__

 

 

 

install print queue on pc

$
0
0

hi all,

if I go on my test computer and try this script, it works and the print queue is set in windows:

 

$Printer = "\\PrintServer\Queue"

$net = new-object -com wscript.network

$net.AddWindowsPrinterConnection($Printer)

 

now if I try the same remotely, using the next script, it says that the printer name is not valid. 

 

$sb = {$Printer = "\\PrintServer\Queue"

$net = new-object -com wscript.network

$net.AddWindowsPrinterConnection($Printer)}

invoke-command -computername PCName -scriptblock $sb

 

can someone tell me what is wrong here? I'm using a domain user account and I have access to the print queue.

thanks!

Simple ForEach Combined with If Statment brings wrong results

$
0
0

Im fairly new to PS, im trying to perform a simple task, get list of computers by using the get-content, than though a foreach loop perform a wmi query to each device in the list and get the OS type, than with a IF statment check perform a different task depends on the OS, everntually win vista 7 8 10 needed to be seperated from xp. I wrote the following PS script :

$computers=Get-Content C:\ComputerList\Computers.txt 
$OSType=Get-WmiObject -Class Win32_operatingsystem -namespace "root\CIMV2" -ComputerName $computers

ForEach ( $compdevice in $computers ) {

if ( $OSType.buildnumber -eq "2600*" ) {

Write-Host $compdevice"'s OS type is XP" }

Else {

Write-Host $compdevice"'s Os type is Newer than xp"

}

in this case i get the same result for all computers ( im running the secret againt 2 win xp 1 win 7 and 1 win 8 in a domain envierment.

i've tried a different variation also :

 

$computers=Get-Content C:\ComputerList\Computers.txt $OSType=Get-WmiObject -Class Win32_operatingsystem -namespace "root\CIMV2" -ComputerName $computers

ForEach ( $compdevice in $computers ) {

if ( $OSType.buildnumber -eq "2600*" ) {

Write-Host $compdevice"'s OS type is XP" }

Else {

Write-Host $compdevice"'s Os type is Newer than xp"

} }

in both cases i get the ecxact same results ( all goes to one option of the IF statment )

I wonder, what am I doing wrong ? Note - I was trying to filter by caption, buildnumber and version. and even wild card in the IF statment, it doesnt work well :). thx in advance :)

Viewing all 10624 articles
Browse latest View live


Latest Images