Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

PS Script Help - Remove Trailing spaces from DisplayName attribute

$
0
0

Good day,

Looking for a little help here. We had a cross forest domain user migration (from .local to proper domain). Many (not all) User Accounts' DisplayName attribute has 3 - 7 trailing spaces behind them. Can anyone help this infant PS user with a script that we can run that will fix / remove these trailing spaces? Any help would be greatly appreciated.


ConvertTo-Html shows "*" in HTML table column header

$
0
0

I have an array, gathered from a previous function, that lists all servers that fail a WMI query (for example, FW is blocking DCOM).  I then want to format this array as HTML to send in a nice looking email.  I have done this in the past, but for reason it is not working for this particular script.  It is putting a "*" as the header name of the column in the HTML table.

I tried forcing a column name in the array but the convertto-html still fails to pick this up.  Here is an example:

$Header = "<style>"
$Header = $Header + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$Header = $Header + "TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:#DBE5F1;Text-Align:Left;font-family: Calibri;font-size: 11pt}"
$Header = $Header + "TD{border-width: 1px;padding-right: 30px;border-style: solid;border-color: black;font-family: Calibri;font-size: 10pt}"
$Header = $Header + "</style>"

$Servers = "server1", "server2", "server3"

$Servers = $Servers | Select-Object @{Name="Server Name";Expression={$_}} | ConvertTo-Html -Head $Header

However, the output of $Servers still shows "*" in the table column header.

Like I said, I know I have gotten this to work before, but I can't seem to this get it going this time.

Any suggestions?

Thanks

NK

Issue getting gwmi queries to format for Excel

$
0
0

I've been pulling what little hair I have left on this issue. I am trying to gather info on our PCs at work in order to build replacements for ones that need to be upgraded, but I am having a heck of a time getting it to work. I'm using standard gwmi queries, adding to them an object, then outputting them to a module I downloaded from the Gallery (PSExcel). The part I'm having trouble with is gathering installed printers and apps for a PC. I want to separate each printer/app with a character because I have to import the spreadsheet into an Access db so we can print out build sheets for the new PCs, but I can't get it to work right. I will post the function below. The data looks right but when I run it, a System.Object[] shows up in the spreadsheet. I was able to add a".\" after each printer port name in order to make sure Access doesn't ignore the new line characters, but I'm still not getting how to get the data to show up in the spreadsheet correctly. The previous version of this script used a cfg script we used for a MS Print Server we used, but we have now moved to VPSX, which installs all necessary printers as local ones, even for Network printers. I don't know if this makes much sense, so let me know if you need clarification.

The other issue is similar - I need to grab a list of the installed programs and then compare it to our master list of available programs, then output the matches to the spreadsheet so we know what apps to install on the replacement PC. I can't get that to work either. It appears by the Debug statements that the data is correct in the variables, but it can't find any matches, or just shows the first one and no more. It might be my logic but there is something else I'm missing. I just can't figure I tout.

function Get-printerInfo ($computerName)
{
	$printerList = @()
	try
	{
		$printers = gwmi Win32_Printer -ComputerName $computerName -Property * | Where-Object { $_.Name -like "*secvpsx*" } | Sort-Object { $_.Default } -Descending | select *
		$printerList = $printers | ForEach-Object { "$($_.PortName)$(".\")" }
		Write-Debug "Printers= $printerList"
	}

	catch
	{
		Write-Debug "Error: $_.Exception.Message"
	}

	return $printerList
}

Here is the code for gathering app list:

function Get-Apps ($computerName)
{
	#$programList = @()
	$programList = gwmi Win32Reg_AddRemovePrograms -ComputerName $computerName | Sort-Object { $_.DisplayName } | select *

	return $programList.DisplayName
}

Powershell String editing

$
0
0

I'm looking for a way to automate editing dynamic distribution group filter properties.  I'm having a hard time editing the string due to the special characters.

Here is an example of the entire string that I have to start with:

 ( ( customAttribute1 -eq '5' ) -and ( ( customAttribute2 -eq 'a' ) -or ( customAttribute2 -eq 'b' ) ) -and -not  ( Name -like 'SystemMailbox{*' ) -and -not  ( Name -like 'CAS_{*' ) -and -not  ( RecipientTypeDetailsValue -eq '16777216' ) -and -not  ( RecipientTypeDetailsValue -eq '536870912' ) -and -not  ( RecipientTypeDetailsValue -eq '68719476736' ) -and -not  ( RecipientTypeDetailsValue -eq '8388608' ) -and -not  ( RecipientTypeDetailsValue -eq '4398046511104' ) ) 

I want to remove the default  filters (everything after and including the "SystemMailbox" filter)   that get added by Exchange so that all I have left is the actual recipient filter properties listed

Below is what I would want the end string result to be:

 ( customAttribute1 -eq '5' ) -and ( ( customAttribute2 -eq 'a' ) -or ( customAttribute2 -eq 'b' ) )

This is just one example, others would have variations of CustomAttribute filters and combinations thereof.


Unable to execute GetSharedDefaultFolder method using MAPI

$
0
0

I am trying to access GetSharedDefaultFolder method using MAPI on top of Office 2016 and outlook version is 16.0.0.7369.

$outlook = new-object -com outlook.application;
$mapi = $outlook.GetNameSpace("MAPI");
$myRecipient = $mapi.CreateRecipient("testme")
$myRecipient.Resolve
$myFolder = $mapi.GetDefaultSharedFolder($myRecipient,6)

but it throws following error 

Cannot find an overload for "GetSharedDefaultFolder" and the argument count: "2".

Am I missing something?


RaghuM


no tls12

$
0
0

I thought that .net framework 4.6 was able to use tls12 by default.

But I get this.

[system.environment]::version = 4.0.30319.42000

[servicepointmanager]::securityprotocol = ssl3, tls

Is my powershell stuck on whatever it was build with?

Exiting the script if NOT member of group ...possible?

$
0
0
Hi guys,

We have a domain with 250 users.

I have written a very simple PS script - The script runs at login (as a Group policy login script - bit its only aimed at two departments only) the script checks for the existence of a "flag file" in a user share - if it doesn't exist, then it copies some files and folders from an "application" share down to the users local drive, and then creates a flag file into the users network share)

It all works fine, but the only snag is, it runs for everyone, and if the person doesn't have permission to the network share (not in the right security group, it still runs the script, and creates the flag file - but cant copy the files.

Now, although its not a massive problem, it would be great if the script could do a check as it launches, checking the users security group permission, to dictate if the script runs or not, something like, IF NOT MEMBER OF "domain\tax" then QUIT else proceed...

Is this easily achievable?

Many thanks for reading.

Copy files to the destinations sub-folders only while excluding specific sub-folders. PS or batch

$
0
0

So I have danced with this off and on throughout the day and the timeless phrase "There's more than one way to skin a cat" keeps coming to mind so I decided to take to the community.

Scenario:

Source folder "C:\Updates" has 100 files of various extensions that need to be copied to the sub-folders only of "C:\Prod" overwriting the duplicate files if they exist.  (Sub-folders only - rather than the destination folder and it's sub-folders)

The Caveats:

  1. The destination folder names in "C:\Prod" are quite dynamic and change frequently.
  2. A naming convention is used to determine which sub-folders in the destination need to be excluded when the source files are being copied (retaining the original version of the files).  For ease of explanation lets say any folder names starting with"!stop" should be excluded from the copy process. (!stop* if wildcards considered)

So, here I am wanting the input of those greater than I to tackle this in PS if I'm lucky.  I've tinkered with Copy-Item and xcopy today so I'm excited to hear other's input.

Thanks!

-Chris


Changing bulk filesname + extension + copy to new folder

$
0
0

Hello

can anyone help me how can i change bulk filesname + extension and copy to new folder with ps ise?!

Regards

Not able to send email thru Outlook

$
0
0

Hello

I am using following code to send email thru Outlook.  I want to send it thru Outlook Client only. I am working on 64 bit machine with OutLOok 2010. I know that I can send it thru smtpserver option in a diferent way, but my client wants to send it thru OutLook client.

$outlook = New-Object -comObject  Outlook.Application  
$mail = $outlook.CreateItem(0)  
$mail.Recipients.Add($recipientEmail)  
$mail.Subject = $subject  
$mail.Body = $body         
$mail.Send()  
Write-Host "Email sent!"

I am getting following error, can anyone tell me what wrong I am doing

New-Object : Retrieving the COM class factory for component with CLSID

{0006F03A-0000-0000-C000-000000000046} failed due to the following error:

80080005 Server execution failed (Exception from HRESULT: 0x80080005

(CO_E_SERVER_EXEC_FAILURE)).

At line:1 char:12

+ $outlook = New-Object -comObject  Outlook.Application

+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ResourceUnavailable: (:) [New-Object], COMExcept

   ion

    + FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman

   ds.NewObjectCommand

You cannot call a method on a null-valued expression.

At line:2 char:1

Results table from powershell script

$
0
0

I am working on a script which runs a SQL query against a table in the SQL database and returns two values, GUID and Yes or No.

I'm trying to run this as part of an orchestrator runbook, and it depends on having the GUID and the YES or NO Value.

I need the GUID as a published string, the YES or no as a published string. Its so that the next step in the Orchestrator runbook looks for GUID + YES and continues or GUID + NO and ignores. The next step then needs the GUID only that matches the YES value.

Any thoughts as to how this could be accomplished?

Here's the script as it stands

Import-Module sqlps
#Connect to SQL Database
$sqlserver = "MYSQLDB"
$approvaldatabase = "Software Approval GUID"
$UserSqlQuery = "DECLARE @DUP VARCHAR(MAX)
SET @DUP = '00D3B213-05E9-4D09-BD3C-549916656276'

SELECT TOP 50 [RequestGUID], ""DUP"" =
CASE
WHEN RequestGUID = @DUP THEN 'YES'
--WHEN RequestGUID != @DUP THEN 'NULL'
ELSE 'NO'
END
  FROM [Software Approval GUID].[dbo].[RequestGUID]
  --where RequestGUID = @DUP"

$conn = New-Object System.Data.SqlClient.SqlConnection("Server = $sqlserver; Database = $approvaldatabase; Integrated Security = True")
$conn.Open()
$sqlcmd = $conn.CreateCommand()

$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $sqlserver $approvaldatabase $UserSqlQuery

function ExecuteSqlQuery ($sqlserver, $approvaldatabase, $SQLQuery) {
    $Datatable = New-Object System.Data.DataTable

    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Connection.ConnectionString = "server='$sqlserver';database='$approvaldatabase';trusted_connection=true;"
    $Connection.Open()
    $Command = New-Object System.Data.SQLClient.SQLCommand
    $Command.Connection = $Connection
    $Command.CommandText = $SQLQuery
    $Reader = $Command.ExecuteReader()
    $Datatable.Load($Reader)
    $Connection.Close()

    return $Datatable
}

That gives me an output like this:

RequestGUID                                                              DUP
-----------                                                              ---
00D3B213-05E9-4D09-BD3C-549916656276                                     YES
2F4800E8-27BD-4004-AE38-AE3B56E70FB4                                     NO  


Run IE and open a htm file via PS

$
0
0

Hello

I want to run IE from a PS script and open a local file.

New to PS and scripting)

Here is the code, but I wont open it, not sure how I can get it to open.

Any suggestions?

 

Function MyIE

{
$file = "C:\Temp\test.htm"
$IE=new-object -com internetexplorer.application
$IE.navigate2("$file")
$IE.visible=$true
 }

Rgds Dee


Dee

How to create powershell cmdlet and use it in SCCM or Group POlicy

$
0
0

Hello

I have some script, i want to share it with my colleagues for testing purpose. Insteaf of sharing the script, I want to compile the script and share it as cmdlet. I dont want people should be able to see the code or modify the code. What is the best way to compile it?

Once it is compiled, then want t use compiled ode with SCCM or Group Policy. How this can be achieved?

Regards

Avian

Problem when invoked PS scripts remotely

$
0
0

Hi,

I have a batch script which invokes a PS script as a domain user (Start-Process -Credential). Although this script works fine when I run it locally (logged in as Local Administrator), when I trigger the same batch script through PsExec.exe or PS remoting options specifying the Local Admin credentials certain parts of the PS script don't execute. The PS process is executed as the correct domain user according to the Task Manager. But for some reason it gives errors when run Remotely.

For example I try to copy some files through a network share. This logic never works when remotely executed. 

I tried Invoke-Command instead of Start-Process but same issue pops up.

Is this a known security restriction for remote script execution?

/Menuwan

CMDLET vs PowerShell compiled exe

$
0
0

Hello

I want to share my script with end users, but I dont want user shuld be able to see the code or able to reverse engineer. So I want to understand which process is better i.e. CMDLET or PowerShell compiled exe? Which is more secure and easily to understand and what is the pros and cons of each approach.

Avian


Powershell encoding or...?

$
0
0

Please move this thread where you suppose to.

Problem: trying to execute powershell command:

icm -computername hr-pc -scriptblock {wecutil qc}

Is this an another PS bug which MS won't fix or...? Changing like 10 code pages don't help.


Windows makes me mad!


Executing powershell script from php

$
0
0

i have server 2012 r2 with iis v 8.5

iis have php v5.5 (x86) + php manager

i need to know how to setup iis and php in order to run powershell from a php code

i will really appreciate every help i can get

Help in parsing with Regex - Alpha numeric with Hyphen

$
0
0

Hi,

Need help in creating regex for the following situation

1. 4 digit codes are listed in a file [ each code is in a separate line

2. I am reading the contents like $codes = Get-Content $FileContainingCodes. This works OK

3. I have another file that i need to search for lines with pattern something like

" a. First 4 chars will be either ABCD or IJKL or WXYZ ,next 4  chars will be any word [a-z0-9A-Z], followed by a hyphen -, then next 4 chars will be again  ABCD or IJKL or WXYZ , next 4 chars will be any word [a-z0-9A-Z], next 6 chars will be a number, next 4 chars will be the $code, then a hyphen and then a C

For e.g. if my $code is 0800 then my pattern should search

ABCD23RT-WXYZFG4D-1234560800-C - will match the pattern

ABDC4567-XYZW9000-1234560801-C - will not match

I tried the following regex patterns and none would work

$str = "ABCD23RT-WXYZFG4D-1234560800-C"

$code = 3920

$pattern = "[ABCD|IJKL|WXYZ]\w{4}-[ABCD|IJKL|WXYZ]\w{4}-\d{6}$code-C"

$str -match $pattern =====> This returns False

$pattern = "[ABCD|IJKL|WXYZ]\w{4}\W[ABCD|IJKL|WXYZ]\w{4}\W\d{6}$code-C"

$str -match $pattern =====> This returns False

However, the following partial patterns work

$pattern = "[ABCD|IJKL|WXYZ]\w{4}-[ABCD|IJKL|WXYZ]\w{4}"

$str -match $pattern =====> This returns True

$pattern = "-\d{6}$code-C" =====> This returns true

$pattern = "[ABCD|IJKL|WXYZ]\w{4}-[ABCD|IJKL|WXYZ]\w{4}-"

$str -match $pattern =====> This returns False ( see the last hyphen?)

I am not sure why my pattern "[ABCD|IJKL|WXYZ]\w{4}-[ABCD|IJKL|WXYZ]\w{4}-\d{6}$code-C" would not work. Note that the string that i am searching is not in the begining of the line or end of line that would warrant the use of ^ or $. Its somewhere in the middle of a line of a csv file.

Thanks in advance.

Arun

Question regarding conditional branch.

$
0
0

Hi all, I have a question regarding conditional branch sample code. I am running some scripts in O365, "Running script" as below. I want to do when a PSSession enters a "Broken" state, it will pause the script, and remove broken session (Remove-PSSession <broken session ID>) and re-connecting PSSession (following "Re-connecting code" as below), then restart the script. It's perfect if it could catch the session broken at which user and log them to text. (Server 2008 R2 SP1/PowerShell)
Any help would be appreciated!

Runing Script-------------
Import-Csv D:\work\users.csv | ForEach {
Grant-CsConferencingPolicy $_.UserPrincipalName -PolicyName BposSAllModalityNoFT
}

Import-Csv D:\work\users.csv | ForEach {
Grant-CsExternalAccessPolicy $_.UserPrincipalName -PolicyName FederationOnly
}
--------------------------


Re-Connecting code----
$sfboSession = New-CsOnlineSession -Credential $credential
Import-Pssession $sfboSession -AllowClobber
--------------------




Lookup Bitlocker recovery key with Key ID in Powershell?

$
0
0

https://gist.github.com/anonymous/fa0ab4769ecaf1abef2f5068239d4f9c

This code below is working. The input is WIN7X86PC01 but I want to have the input be the Key ID (E59D69FF-6A3B-42A6-89C0-57A0DA0E302A) instead. And then return the associated msFVE-RecoveryPassword. How can I achieve this?

# Get Computer Object
> $computer = Get-ADComputer -Filter {Name -eq 'WIN7X86PC01'}

# Get all BitLocker Recovery Keys for that Computer. Note the 'SearchBase' parameter
> $BitLockerObjects = Get-ADObject -Filter {objectclass -eq 'msFVE-RecoveryInformation'} -SearchBase $computer.DistinguishedName -Properties 'msFVE-RecoveryPassword'

# How can this be modified to take the Bitlocker Key ID as input? i.e."{E59D69FF-6A3B-42A6-89C0-57A0DA0E302A}" instead of "WIN7X86PC01"

# Output the results!
> $BitLockerObjects
DistinguishedName : CN=2014-10-20T13:10:38-06:00{E59D69FF-6A3B-42A6-89C0-57A0DA0E302A},CN=WIN7X86PC01,OU=swCompute
rs,DC=swansong,DC=com
msFVE-RecoveryPassword : 465762-121880-049797-598411-533643-549890-128436-549736
Name : 2014-10-20T13:10:38-06:00{E59D69FF-6A3B-42A6-89C0-57A0DA0E302A}
ObjectClass : msFVE-RecoveryInformation
ObjectGUID : d0a15cc8-5f86-42ed-8942-633cec25b6b1
Sign up for free

Viewing all 21975 articles
Browse latest View live


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