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

Organisational Unit Script

$
0
0

I'm almost there.... I think. Im just creating an OU batch file for class and I dont want to use the premade one here's what I have already can anyone just point out why it might not be working, im not sure I understand the not expression

$fileName = Read-Host -Promt 'Input File Name, Type Finished when completed';
while($fileName != "Finished")
{
$fileName = Read-Host -Promt 'Input File Name, Type Finished when completed';
$nestedOU = Read-Host -Promt 'Input Nested File, If it is not nested type No then Enter';
if ($nestedOU != "No")
{
New-ADOrganizationalUnit -Name "$fileName" -Path "OU=$nestedOU ,DC=eit,DC=co,DC=nz" -ProtectedFromAccidentalDeletion $False;
}
else 
{
New-ADOrganizationalUnit -Name "$fileName" -Path "DC=eit,DC=co,DC=nz" -ProtectedFromAccidentalDeletion $False;
}
Write-Host "Organisational Unit has been created."
}
Write-Host "Finished creating Organisational Units"

Many thanks


can we run powershell scripts in other OS languages ?

$
0
0

Hi ,

We have a requirement like , to execute powershell script in newly shipped laptops with OS language like Chinese, Japanese,spanish etc..

Basically the powershell script is used to perform registry changes, change the wallpaper ,rename computer and installs sccm client

Whether executing powershell script is supported in other langs ???

If not supported , what is the workaround ??

request for suggestions

Regards,

Kalaivani M

Unable to set ACL on Remote Registry -Kindly HELP

$
0
0

Hi All,
Tried to set ACL on remote registry but it doesn't work. Tested the same code on local computer which works fine. Please help
objective : Need to assign full permission to "Domain Users" on registry (HKLM\Software\Microsoft) of several remote computers.

Code :
Set-ExecutionPolicy unrestricted -Force
Import-Module -Name psrr -Force

$servers= Get-Content -Path 'D:\ServerList.txt'

foreach($pc in $servers)
{
write-host "Setting ACL Permission for $PC"
$RegSec = new-object system.Security.AccessControl.RegistrySecurity
$rule = New-Object System.Security.AccessControl.RegistryAccessRule("Domain users", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$RegSec.AddAccessRule($rule)

$RemoteKey = [microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $pc)
$RemoteAccess = $RemoteKey.OpenSubKey("Software\Microsoft", $true)

$RemoteAccess.SetAccesscontrol($RegSec)
}

***************

please let me know whats wrong here

This code works well on for the same computer from where this PS run.. but doesn't work for remote computer on same domain.


creating custom objects from array

$
0
0

I am using a script to create new objects with certain values given as below. This works in case where $Names returns a single string value, however get’s the following error when there is an array and before printing $newobj. Trying to find what is causing the error as I added a foreach statement for $Names. Also note that, the value of $x is same as "London" for both values John, Jake in the $names array.

In the current output, StudentName is printed as “John” both times, and when I use parameters –Force and -Passthru, the value of StudentName is overwritten to “Jake" both times. I would need to separate these values different in the output. Could someone help me please?

Add-Member:Cannot add a member with the name "StudentName" because a member with that name already exists.To overwrite the
member anyway, add the Force parameter to your command.At E:\test.ps1:93 char:14+             $newobj |Add-Member-MemberTypeNoteProperty-NameStudentName-Value $_

Script:

# $DCNames is an arrayForeach($x in $DCNames){ $newobj =New-Object psobject $newobj |Add-Member-MemberTypeNoteProperty-Name DC -Value $x###### $Names in most cases is a single string or it could be also an array. For example: it could be a value Adam or {John Jake….} and so I would need to Add each member in $Names as StudentName object below. $Names =@() $Names = $List |Where-Object{$_.Name-eq $x}|Select-ExpandPropertyName $Names | foreach { $newobj |Add-Member-MemberTypeNoteProperty-NameStudentName-Value $_# $ClassName is a single string $newobj |Add-Member-MemberTypeNoteProperty-NameClass-Value $ClassName $result += $newobj

$result | Export-Csv "E:\file.csv"}

Current output:

Name:VegasStudentName:AdamClass:10Name:LondonStudentName:JohnClass:12Name:LondonStudentName:John(the script should take the second value Jake here from $Names array, but is not happening for some reason)Class:11

Export users of multiple groups from import-csv or get-conent

$
0
0
Hi

I am running below PS command to get the users details of all users which are in groups.csv file with their attributes.

Import-Csv .\groups.csv | % { Get-ADGroupMember $_.group | Get-ADUser -Properties * | select name,SamAccountName,enabled,title,department,@{l='Manager';e={$_.manager -replace 'CN=(.+?),OU=.+','$1'}}} | Export-Csv users.csv -NoTypeInformation -Encoding UTF8

I have got desired result as well.


But I need to segregate all users to belong their groups which mentioned in group.csv file. Also can i export users of groups in csv files each new sheet with group name?

In other way, 

Is this possible that i have around 200 groups name and i want to export group's users with their attribute (user’s name, SamAccountname, status, title, department and their manager’s name/SamAccoutName) in individual csv file 

Get-ADGroup, starts with the following.

$
0
0

hi,

This should be a quick one. I need to get a list of Groups in AD that start with ABC and others that start with HIJ.

I can do the first part:

Get-ADGroup-Filter{Name-like"ABC*"}

but do not know how to do the second part.

I've tried

Get-ADGroup-Filter{Name-like"ABC*" - and "HIJ*"}

Any ideas?

Thanks!

Powershell script only works in ISE

$
0
0

Hi forum, I have a problem with my powershell. It works great in the ISE, but doesn't work when I start it in CMD oder Powershell-Command-Window. 

The script has a filewatcher for a folder, that checks edited or renamed xlsx files. If found, it checks the printing area and renames it to the german version of printing area.

I need this for a solution, that runs only with the german printing area name.

Before it renames the area, it makes a backup of the xlsx with 7zip to a defined folder. Definitions are at the top area of the script. It needs an istallation of the 7zip. but this part, could easily be deleted if you want to run it.

When I start the ps1 file, I don't get any information, only that the 3 filewatchers have been started.

After I copy a new xlsx file to the folder, the Filewatcher "file.Changed" has a "Failed" state

Thank you very much for your answers.

Mike----------------------------------------------------------------------------

          

#7zip must be installed on the computer

$globBackuppath = 'C:\temp\backup\'
$globPath='C:\temp\' #folder to watch
$globLogfile = $globPath+"$(gc env:computername).log"
$globDoLog =$True
$LogLevel=2 #0=off 1=low 2=high
[int]$logLevelOff=0
[int]$logLevelLow=1
[int]$logLevelHigh=2

#function to change the printing area name

Function ChangeDruckbereich{
Param (

  [parameter()]

  $Item2
  )


  Function Write-Log {
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$False)]
    [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
    [String]
    $Level = "INFO",

    [Parameter(Mandatory=$True)]
    [string]
    $Message,

    [Parameter(Mandatory=$False)]
    [string]
    $logfile,

    [Parameter(Mandatory=$False)]
    [int]
    $logLevelSet = 0,

    [Parameter(Mandatory=$False)]
    [int]
    $logLevelMsg = 0
    )

    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
    $Line = "$Stamp $Level $Message"
    If($logfile -and $globDoLog -and ($logLevelSet -ge $LogLevelMsg)) {
        Add-Content $logfile -Value $Line
    }
    Else {
        Write-Output $Line
    }
}


Write-Log 'INFO' 'Start ChangeDruckbereich' $globLogfile $LogLevel $logLevelHigh

# The zip file to be changed
$file = $Item2.name #'D:\Temp\ChangePrintAreaTest\print-area.xlsx'

# Load ZipFile-related assemblies (Compression.FileSystem) if not present already
try { $null = [IO.Compression.ZipFile] }
catch { [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') }

# Open zip file with update mode (specify Read for readonly mode)
$fileZip = [System.IO.Compression.ZipFile]::Open( $file, 'Read' )##mike Update auf Read geändert

# select the specific file within the zip file
$fileZip.Entries | Where-Object { $_.FullName -match 'xl/workbook.xml' }

Write-Log 'INFO' 'Start open the file with streamreader and store its contents in $text' $globLogfile $LogLevel $logLevelHigh
# open the file with streamreader and store its contents in $text
$desiredFile = [System.IO.StreamReader]($fileZip.Entries | Where-Object { $_.FullName -match 'xl/workbook.xml' }).Open()
$text = $desiredFile.ReadToEnd()
$desiredFile.Close()
$desiredFile.Dispose()

Write-Log 'INFO' 'Start Druckbereich nur ersetzen wenn gefunden' $globLogfile $LogLevel $logLevelHigh
#Druckbereich nur ersetzen wenn gefunden
$chkContains=$text.Contains('_xlnm.Print_Area')
if($chkContains -eq $True)
{
    Write-Log 'INFO' "Druckbereich _xlnm.Print_Area in $file gefunden, wird ersetzt." $globLogfile $LogLevel $logLevelLow
    $fileZip.Dispose() ##
    Write-Log 'INFO' 'Zip-Close' $globLogfile $LogLevel $logLevelHigh
    Start-Sleep -m 1000

    #Backup des Files
    try{
    $tempTime=(Get-Date -Format yyyyMMddhhmmss)
    $tempText="Copy-Item -Path '$globPath$file' -Destination "+"'$globBackuppath$tempTime$file'"
    Write-Log 'INFO' $tempText $globLogfile  $LogLevel $logLevelHigh
    #Copy-Item -Path "'$globPath$file'" -Destination "'$globBackuppath$tempTime$file'" 
    #Copy-Item "'$globPath$file'" "'$globBackuppath$tempTime$file'"
    #start 'C:\Program Files (x86)\7-Zip\7z.exe' a "'$globBackuppath$tempTime$file.zip'" '$globPath$file'
    #



#PS script to run 7z command line tool to back up the contents of the specified folder
#
###############################################################################
#$temppath=$env:temp+"\"
$sourcepath="$globPath$file"
$curdate=Get-Date
$destfilename=$curdate.ToString("yyyy-MMM-dd-HH-mm-ss")+".zip"
$destfilepath=$globBackuppath
$destfilepath
$7zexe="C:\Program Files\7-Zip\7z.exe"
#$finaldest="\\someserver\backups"
###############################################################################
#
#execute the command line 7zip, skip the file types that you do not want using the -x option
#
write-host "Executing 7z.exe from the location $7zexe for archiving files into the ZIP $destfilepath$destfilename from the source folder $sourcepath"
& $7zexe a -tzip $destfilepath$destfilename -r $sourcepath "-x!*.pdb" "-x!*.obj" "-x!*.dll" "-x!*.cache" "-x!*.suo" "-x!TestResults"
    Write-Log 'INFO' 'ENDE- Backup des Files erfolgreich' $globLogfile $LogLevel $logLevelHigh
    }
    catch{
    $ErrorMessage = $_.Exception.Message
    Write-Log 'ERROR' $ErrorMessage $globLogfile $LogLevel $logLevelOff #fehler immer loggen
    }
    $fileZip = [System.IO.Compression.ZipFile]::Open( $file, 'Update' )##

    # If needed, manipulate $text however for the update
    $text = $text -replace '_xlnm.Print_Area', 'Druckbereich'

    # Re-open the file this time with streamwriter
    $desiredFile = [System.IO.StreamWriter]($fileZip.Entries | Where-Object { $_.FullName -match 'xl/workbook.xml' }).Open()

    # zero out the file -- in case the new file is shorter than the old one
    $desiredFile.BaseStream.SetLength(0)

    Write-Log 'INFO' 'Start- Insert the $text to the file and close' $globLogfile $LogLevel $logLevelHigh
    # Insert the $text to the file and close
    $desiredFile.Write($text -join "`r`n")
    $desiredFile.Flush()
    $desiredFile.Close()

    Write-Log 'INFO' 'Start- Write the changes and close the zip file' $globLogfile $LogLevel $logLevelHigh
    # Write the changes and close the zip file
    $desiredFile.Dispose()
    Write-Log 'INFO' 'End- $desiredFile.Dispose()' $globLogfile $LogLevel $logLevelHigh

}
$fileZip.Dispose()
Write-Log 'INFO' 'End- Function' $globLogfile $LogLevel $logLevelHigh
}









Function Start-FileSystemWatcher  {

  [cmdletbinding()]

  Param (

  [parameter()]

  [string]$Path,

  [parameter()]

  [ValidateSet('Changed','Created','Deleted','Renamed')]

  [string[]]$EventName,

  [parameter()]

  [string]$Filter,

  [parameter()]

  [System.IO.NotifyFilters]$NotifyFilter,

  [parameter()]

  [switch]$Recurse,

  [parameter()]

  [scriptblock]$Action

  )

  #region Build  FileSystemWatcher

  $FileSystemWatcher  = New-Object  System.IO.FileSystemWatcher

  If (-NOT $PSBoundParameters.ContainsKey('Path')){

  $Path  = $PWD

  }

  $FileSystemWatcher.Path = $Path

  If ($PSBoundParameters.ContainsKey('Filter')) {

  $FileSystemWatcher.Filter = $Filter

  }

  If ($PSBoundParameters.ContainsKey('NotifyFilter')) {

  $FileSystemWatcher.NotifyFilter =  $NotifyFilter

  }

  If ($PSBoundParameters.ContainsKey('Recurse')) {

  $FileSystemWatcher.IncludeSubdirectories =  $True

  }

  If (-NOT $PSBoundParameters.ContainsKey('EventName')){

  $EventName  = 'Changed','Created','Deleted','Renamed'

  }

  If (-NOT $PSBoundParameters.ContainsKey('Action')){

  $Action  = {

  Switch  ($Event.SourceEventArgs.ChangeType) {

  'Renamed'  {

  $Object  = "{0} was  {1} to {2} at {3}" -f $Event.SourceArgs[-1].OldFullPath,

  $Event.SourceEventArgs.ChangeType,

  $Event.SourceArgs[-1].FullPath,

  $Event.TimeGenerated

  }

  Default  {

  $Object  = "{0} was  {1} at {2}" -f $Event.SourceEventArgs.FullPath,

  $Event.SourceEventArgs.ChangeType,

  $Event.TimeGenerated

  }

  }

  $WriteHostParams  = @{

  ForegroundColor = 'Green'

  BackgroundColor = 'Black'

  Object =  $Object

  }

  Write-Host  @WriteHostParams

  }

  }

#endregion  Build FileSystemWatcher
    #region  Initiate Jobs for FileSystemWatcher

  $ObjectEventParams  = @{

  InputObject =  $FileSystemWatcher

  Action =  $Action

  }

  ForEach  ($Item in  $EventName) {

  $ObjectEventParams.EventName = $Item

  $ObjectEventParams.SourceIdentifier =  "File.$($Item)"

  Write-Verbose  "Starting watcher for Event: $($Item)"

  $Null  = Register-ObjectEvent  @ObjectEventParams

  }

  #endregion  Initiate Jobs for FileSystemWatcher

  return $FileSystemWatcher












$FileSystemWatcherParams = @{

  Path = $globPath #'P:\_Shared\_Departments\IT_TEAM_AM_Intern\TM1-Excel-Fix\Sourcen\Testdaten\}Externals\defekt'

  Recurse =  $False #keine Subdirectories

  NotifyFilter =  'FileName','LastWrite'#lastwrite=mike zusätzlich möglich(LastAccess , DirectoryName)

  Verbose =  $True

  Action=  {

  $Item  = Get-Item $Event.SourceEventArgs.FullPath

  $WriteHostParams  = @{

  ForegroundColor = 'Green'

  BackgroundColor = 'Black'

  }            

  Switch  -regex ($Item.Extension) {

  '\.(xlsx)'  {
  $WriteHostParams.Object  = "Processing  Excel spreadsheet: $($Item.Name)"

  ChangeDruckbereich $Item

    #$Item  | Remove-Item
  }


  Default{$WriteHostParams.Object  = "Processing  File: $($Item.Name) nothing to do"}

  }   



  Write-Host  @WriteHostParams 

  }

}
@('Changed','Created','Renamed') | ForEach {

  $FileSystemWatcherParams.EventName = $_

  $retValue=Start-FileSystemWatcher  @FileSystemWatcherParams

}
  Get-Job

  #Stop-Job(nummer,nummer,nummer) zum stoppen 
  #Remove-Job(nummer,nummer,nummer) und entfernen


  Read-Host -Prompt "Press Enter to exit"


Not able to fetch the list of users of particular group

$
0
0

Hello

I am trying to get the list of user of a particular group, but it is not returning anything. There are 3 users inMyO365 group.

$group="MyO365"
get-aduser -filter { memberOf -RecursiveMatch $group } -SearchBase "dc=lc,dc=local"  -searchscope subtree | select userPrincipalName | export-csv "D:\users.csv" -notypeinformation -force

Please let me know what I am missing

Avian




Edit the Directory physical path Location for Applications Under Default Website

$
0
0

Hi,

I'm currently looking for a way to amend applications physical paths through power-shell instead of manually going into every application.

I have a number of applications under the default website which have applications under them that need to be changed. 

Is there a way of changing them through power-shell , so that I can possibility eventually run the powershell through SQL. 

this is a snippet of what exactly I'm trying to do. Making amendments to the physical Path. 

Help will be appreciated 


Retrieving proceses and owner from remote servers

$
0
0

Hello TechNet

I am trying to retrieve a list of process from several remote servers. The goal of this is to determine is there are process or services that run on user credentials instead of service accounts.

My script looks like this:

$Credential = Get-Credential -UserName domain\admin-Message "password" $pc = get-adcomputer -filter * -properties operatingsystem | where {$_.operatingsystem -like "Windows Server *"} foreach ($Computer in $pc) {     Invoke-Command -ComputerName $Computer.Name -ScriptBlock {Get-Process -IncludeUserName} -Credential $Credential }

Here I have some problems. On some servers it is working, but not on many;

One error I receive is "Connecting to remote server .... failed with the following error message: WinRM cannot complete the operation. Verify that the specified computer name is valid(it is), that the computer is accessible over the network (it is), and that a firewall exception for the WinRM service is enabled and allows access from this computer. (remoting is enabled By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.     + CategoryInfo          : OpenError: (ServerName:String) [], PSRemotingTransportException"

 

How could I retrieve processes and owners from remote servers?

 

 

 

 

 

 

 

 


Using a predefined list

$
0
0
I have a csv file (docs.csv) of file names for an NT volume that I created from a database software that is storing the files on that volume. The database does NOT keep track of any other file properties other than the name. I need to pull the size of the files based on the list of names in the CSV file using powershell and pipe that to another csv file which has the file name and size. I attempted to use Get-Content and Import-csv without success. 

Retrieving processes and owner from remote servers

$
0
0

Hello TechNet

I am trying to retrieve a list of process from several remote servers. The goal of this is to determine if there are process or services that run on user credentials instead of service accounts.

My script looks like this:

$Credential = Get-Credential -UserName domain\admin-Message "password"

$pc = get-adcomputer -filter * -properties operatingsystem | where {$_.operatingsystem -like "Windows Server *"}

foreach ($Computer in $pc)

{    

Invoke-Command -ComputerName $Computer.Name -ScriptBlock {Get-Process -IncludeUserName} -Credential $Credential

Here I have some problems. On some servers it is working, but not on many;

One error I receive is "Connecting to remote server .... failed with the following error message: WinRM cannot complete the operation. Verify that the specified computer name is valid(it is), that the computer is accessible over the network (it is), and that a firewall exception for the WinRM service is enabled and allows access from this computer. (remoting is enabled By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.     + CategoryInfo          : OpenError: (ServerName:String) [], PSRemotingTransportException"

 

How could I retrieve processes and owners from remote servers?

How to pass multiple quoted strings as a single argument to a job

$
0
0

Hi,

I can't figure out how to do this. A simple version of what I am trying to do is supply a list of files to be concatenated as an argument for DOS cmd that I am going to run as a job. The number of files to concat is variable so passing each as a separate arg does work.

For example using Notepad to simulate:

$inFiles='"c:\file(0).txt""c:\file(1).txt"'

start-job-scriptblock{param($ff);notepad.exe $ff}-args$inFiles

Resulting cmdline is (as seen in Process Monitor): "C:\WINDOWS\system32\notepad.exe" ""c:\file(0).txt" "c:\file(1).txt""

I get an extra set of dblQoutes around the entire arg which is causing my exe grief. Looking for a way to do this and not get the extra dblQoutes.

Thanks,

-Wes

Not able to add/remove user from group and not able to set litigation in Office 365 a/c

$
0
0

Hello

I am migrating mailbox from Exchange to O365 using following code, user mailbox is migrated properly, but when I try to remove/add user from different group and try to enable litigation, I am getting following error. Can anyone please advise what I am missing here

GET-ADUSER : Cannot find an object with identity: 'Test-Mailbox888@domain.com' under: 'DC=lc,DC=local'.
At D:\pscript\mig0365new.ps1:113 char:28
+             $usergroups = (GET-ADUSER -Identity $_.userPrincipalName -Properties ...
+                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Test-Mailbox888@domain.com:ADUser) [Get-ADUser], ADIdentityNotFoundE
   xception
    + FullyQualifiedErrorId : Cannot find an object with identity: 'Test-Mailbox888@domain.com' under: 'DC=lc,DC=lo
   cal'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser

assigning license for @{UserPrincipalName=Test-Mailbox888@domain.com}.userPrincipalName ...
WARNING: If you want to change LitigationHoldEnabled and LitigationHoldDuration on an inactive mailbox, please add the
InactiveMailbox switch.
The operation couldn't be performed because object 'Test-Mailbox888@domain.com' couldn't be found on
'domain.PROD.OUTLOOK.COM'.
    + CategoryInfo          : NotSpecified: (:) [Set-Mailbox], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=asdasdROM,RequestId=187adsd1a1f6-1060-407a-888d-f6basdasd6c28a8,TimeStamp=31/08/201
   6 5:24:46 PM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 7858EA80,Microsoft.Exchange.Management.Re
  cipientTasks.SetMailbox
    + PSComputerName        : outlook.office365.com

Import-Csv  "D:\pscript\users.csv" | foreach {
        $Mailbox = Get-Mailbox -Identity $_.userPrincipalName -ErrorAction SilentlyContinue
        If ($Mailbox) {
            Write-Host $_.userPrincipalName "Mailbox exists"
        }
        Else {
            Write-Host $_.userPrincipalName "Mailbox does not exists"
            New-MoveRequest -Identity $_.userPrincipalName -Remote -RemoteHostName webmail2.myconnect.com -TargetDeliveryDomain mycom.mail.onmicrosoft.com -RemoteCredential $msol -BadItemLimit 50 -LargeItemLimit 50 -AcceptLargeDataLoss -warningaction "SilentlyContinue"

            Write-Host $_.userPrincipalName "Mailbox Migration is started"
            #Check the status of each user request and once the status is commpleted move user from
            #Once completed move user from one group to other
            $usergroups = (GET-ADUSER –Identity $_.userPrincipalName –Properties MemberOf).MemberOf |
            if ($usergroups -match 'Usergroup')
            {
                Remove-ADGroupMember -Identity "O365_New_Starter" -Members $_.userPrincipalName -Confirm:$false
                Add-ADGroupMember -Identity "O365_Completed" -Members $_.userPrincipalName
            }


            #Settingup Litigation & Hold
            Set-Mailbox -Identity $_.userPrincipalName -LitigationHoldEnabled $true

                Write-Host "------------------------------------------------------------------------------"
                Start-Sleep 60
        }

}



Powershell command to get the Windows Update

$
0
0

i run this powershell command to get when the server was last pactch.

Get-Hotfix –cn ServerName| Select HotfixID, Description, InstalledOn | sort InstalledOn

the result is

KB3168965                               Security Update                         8/7/2016 12:00:00 AM
KB3170106                               Security Update                         8/7/2016 12:00:00 AM
KB3170455                               Security Update                         8/7/2016 12:00:00 AM

is there a syntax we can get the correct time as you can see it always shows 12:00:00.

Thanks,

ZxR


Invoking PowerShell.exe with "-Command -" (reading input from StdIn) broken in Windows 10 14393?

$
0
0

I have a C# app that contains an embedded PowerShell script.  Not that this matters, it could be external--the important point is that I execute the script by invoking powershell.exe with "-Command -".  That is, using the -Command parameter followed by a hyphen, which allows you to then provide the body of the script to execute through StdIn.

I like this technique, and I've been using it for over a year as, among other reasons, the script doesn't have to be a single command, it can span many lines, declare functions etc, all the while without ever having the script written to disk in plain text or base64-encoded.

After having installed the Anniversary Update of Windows 10 (1607 aka build 14393), this appears to be broken; the captured StdErr shows it complains about missing function bodies, while StdOut shows--and I find this part rather mind-blowing--the script got mangled in such a way that *all* lines that contain a function declaration, and the following opening *and* closing curly braces, are gone.  The rest of the script appears intact.  Obviously that would cascade into all sorts of errors.

I managed to write a short(-ish) sample that demonstrates this problem.  The same EXE demonstrates that it's broken on Windows 10 14393 (all 3 machines I have that run this version exhibit the same behavior), but it works perfectly fine on Windows 10 10586 as well as Windows 7.

One thing I've discovered is that if I substitute the CR/LF characters from the script with a single space, the error goes away, but what happens then is that the StdOut stream I capture comes back empty--even on other OSes that otherwise previously managed to handle the unmodified script just fine--rather than containing the expected output, which comes from one of the script's functions (which simply does a Write-Host).

Another thing I've discovered is that if I add "-version 2.0" as an argument when invoking powershell.exe, everything reverts back to normal behavior.  While this works around the immediate problem, obviously I'd like to remain version-agnostic, so even though I tend to write my scripts so they can run against the "lowest common denominator", I'd rather not explicitly restrict myself in this fashion, as I may eventually need to write a script that relies on some features that have only been introduced in more recent versions.  So I don't view this as a long-term or permanent solution.

If anyone with a compiler cares to try this out, here's my sample cut-down C# program.  It just needs to be built as a console EXE.

Is anyone else getting the same results?  Any workaround that doesn't require me to change the script itself (as I won't necessarily have any knowledge of what the scripts provided to me actually do, other than the fact that they're all expected to end with a single Write-Host as the final output value I'm interested in)...

using System;
using System.Text;
using System.Diagnostics;

namespace PsTest
{
	class Program
	{
		static void Main( string[] args )
		{
			string strMyScript = @"
function GetFunctionValue()
{
	# This comment is in the GetFunctionValue function
	return $true
}

function ShowValue( [string] $theValue )
{
	# This comment is in the ShowValue function
	Write-Host $theValue
}

# This comment is at the script level, before the function call
ShowValue( GetFunctionValue )

# This comment is at the script level, after the function call
";
			//strMyScript = strMyScript.Replace( "\n", " " ).Replace( "\r", " " );
			//strMyScript = strMyScript.Replace( Environment.NewLine, " " );
			RunScript( strMyScript );
		}

		private static string RunScript( string strScriptBody )
		{
			var stdOutBuilder = new StringBuilder();
			var stdErrBuilder = new StringBuilder();

			int nExitCode = 0;
			using ( var p = new Process() )
			{
				p.StartInfo = new ProcessStartInfo( "powershell.exe" )
				{
					Arguments = " -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -Command -",
					// The following line makes the problem go away, even on Win10 14393, unlike the line above
					//Arguments = " -version 2.0 -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -Command -",

					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden,
					UseShellExecute = false,
					RedirectStandardInput = true,
					RedirectStandardOutput = true,
					RedirectStandardError = true,
					Verb = "runas" // Elevate
				};

				p.OutputDataReceived += ( sender, e ) =>
				{
					if ( !String.IsNullOrEmpty( e.Data ) )
						stdOutBuilder.AppendLine( e.Data );
				};
				p.ErrorDataReceived += ( sender, e ) =>
				{
					if ( !String.IsNullOrEmpty( e.Data ) )
						stdErrBuilder.AppendLine( e.Data );
				};

				try
				{
					p.Start();
				}
				catch ( System.ComponentModel.Win32Exception x )
				{
					Console.WriteLine( "Process.Start() threw a Win32Exception:  " + x.Message + Environment.NewLine + x.StackTrace );
					return String.Empty;
				}
				catch ( Exception x )
				{
					Console.WriteLine( "Process.Start() threw an exception:  " + x.Message + Environment.NewLine + x.StackTrace );
					return String.Empty;
				}
				p.BeginOutputReadLine();
				p.BeginErrorReadLine();

				var sw = p.StandardInput;
				sw.WriteLine( strScriptBody );
				sw.Close();

				p.WaitForExit();
				nExitCode = p.ExitCode;
				p.Close();
			}

			string strError = stdErrBuilder.ToString().TrimEnd();
			if ( !String.IsNullOrEmpty( strError ) )
			{
				Console.WriteLine( $"stderr contains the following" + Environment.NewLine + ">>>>>" + Environment.NewLine + strError + Environment.NewLine + "<<<<<" );
				Console.WriteLine( Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine );
			}

			string strOutput = stdOutBuilder.ToString().TrimEnd();
			Console.WriteLine( "stdout contains the following" + Environment.NewLine + ">>>>>" + Environment.NewLine + strOutput + Environment.NewLine + "<<<<<" );

			return String.Empty;
		} // RunScript()
	} // class
}


Here's the expected output on a working machine:

stdout contains the following>>>>>
True<<<<<

...and here's the output on 14393.  Notice the very messed up script body in stdout, at the very end:

stderr contains the following>>>>>
At line:1 char:28+ function GetFunctionValue()+                            ~
Missing function body in function declaration.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordExce
ption+ FullyQualifiedErrorId : MissingFunctionBody

At line:1 char:41
+ function ShowValue( [string] $theValue )+                                         ~
Missing function body in function declaration.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordExce
ption+ FullyQualifiedErrorId : MissingFunctionBody

GetFunctionValue : The term 'GetFunctionValue' is not recognized as the name of
a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, ver
ify that the path is correct and try
again.
At line:1 char:12
+ ShowValue( GetFunctionValue )+            ~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (GetFunctionValue:String) [], Comm
andNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException<<<<<





stdout contains the following
>>>>>
        # This comment is in the GetFunctionValue function
        return $true
        # This comment is in the ShowValue function
        Write-Host $theValue<<<<<


Why Powershell opens a second PSSession when there is already one open

$
0
0

Hi there,

here is my situation:

My script gets mailboxes properties etc so I need to establish a remote session to our Exchange server.

I have: get-credential, then  New-Pssession...
and then
Import-Pssession...

As you would expect I am asked for credentials and then the script works fine.

If the PS window stays open overnight, and this happens frequently, the next day Get-PSSession tells me that the session is broken. To avoid closing the PS window and reopening (as I used to do before)  I added a check in my script - if the session is not open, to close it (actually close all sessions), 

$MySessions=Get-PSSession;
$NumSessions=$MySessions.count

if (($NumSessions -eq 0) -or ($MySessions[$NumSessions-1].state -ne "Opened") ) {
          foreach ($BrokenSession in $MySessions){Remove-PSSession $BrokenSession}

Then the usual get-credential,  new-pssession and import-pssession follow.

This works almost fine. When the script is run subsequent times in the same PS window, the same day - it does not ask for credentials and does not open new PS sessions.  When ran the next day, when the PS session is in broken state it removes the broken one, asks for credentials, creates and imports a new session. So far so good.

The problem is - the moment the script comes to the first Exchange commandlet e.g. get-mailbox it automatically asks for credentials again and opens a second session which has a weird name:
"Session for implicit remoting module at C:\Users\mario\AppData\Local\Temp\13\tmp_22mavgt1.ttj\tmp_22mavgt1.ttj.psm1"
That session will get created and the script will work fine even if I do not enter credentials (click "cancel")

so now I have two opened sessions:

PS C:\Scripts\> Get-PSSession

 Id Name            ComputerName            State         ConfigurationName     Availability
 -- ----            ------------            -----         -----------------     ------------
  1 Session1        exchange.contoso.com    Opened        Microsoft.Exchange       Available
  2 Session for ... exchange.contoso.com    Opened        Microsoft.Exchange       Available

I would like to understand why is this happening and how to avoid it i.e. to prevent opening a second PS session and being asked for credentials for the second time just seconds after I already entered credentials and created a new PS session.

Just to clarify - this happens only the first time the script is run (in the same console) on the second day. All is good in a fresh window and all is good after the first run on the second day.

Thank you very much!

Detect if BitLocker Protection Status is 0, enable

$
0
0

Hi,

I tested each command separately and it works.

1. Use Enter-PSSession -ComputerName DCBLT222

2. manage-bde.exe -status c:

Protection Status: Protection Off

3. manage-bde.exe –protectors –enable c:

Protection Status: Protection ON

I would like to run this against 100 laptops. Script below shows error:

a. .\manage-bde.exe-protectors-enable C:

ERROR: An error occurred (code 0x8004100e):
Invalid namespace

b. Resume-BitLocker -MountPoint "C:"

Get-CimInstance : Invalid namespace

At C:\windows\system32\windowspowershell\v1.0\Modules\BitLocker\BitLocker.psm1:

146 char:13

+             Get-CimInstance `

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

    + CategoryInfo          : MetadataError: (root\cimv2\Secu...cryptableVolum

   e:String) [Get-CimInstance], CimException

    + FullyQualifiedErrorId : HRESULT 0x8004100e,Microsoft.Management.Infrastr

   ucture.CimCmdlets.GetCimInstanceCommand

Get-Win32EncryptableVolumeInternal : C: does not have an associated BitLocker

volume.

At C:\windows\system32\windowspowershell\v1.0\Modules\BitLocker\BitLocker.psm1:

358 char:35

+ ... bleVolume = Get-Win32EncryptableVolumeInternal -MountPoint $MountPoin ...

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

    + CategoryInfo          : NotSpecified: (:) [Write-Error], COMException

    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Get-

   Win32EncryptableVolumeInternal

__________________________________________________________________

SCRIPT:

   $Computer="DCBLT222"


If(Test-Connection-ComputerName$computer-Quiet) {

       

If($encryption_check_all=Get-WMIObject-ComputerName$computer-Namespace"root/CIMV2/Security/MicrosoftVolumeEncryption"`

       

-query"SELECT * FROM Win32_EncryptableVolume WHERE DriveLetter='C:'"|Select-Object*){

     

$protection_check=$encryption_check_all.ProtectionStatus

     

$protection_check

        }

If($protection_check-eq"0"){

           

.\manage-bde.exe-protectors-enableC:


           

#Resume-BitLocker -MountPoint "C:"


            }

           }

else{}

         





Move files from one local folder to another local folder and use parameters

$
0
0

Hi,

I am new to powershell. Do not know anything. If I want to learn very basic commands, please suggest best resource.

I need to create a powershell script in a note pad and save it and need to call it from ETL (SSIS) package by passing parameters. what is the code for that.

Source and Destination directory already exist. All I need is to move all csv extention files from source to target like

Move-item sourceparameterPath to DestinationparameterPath. These parameter values come from outside.

After creating this powershell script file, if I want to test it by executing, how to execute this file ?

Thank You

Get cpu information from a list of computers

$
0
0

Hello,

I can't remember where I got this script, but I am having an issue with it.  The only computer that is imported is the first one in the computers.csv.  In fact, it is shown up twice.  Also,  how would I output to a CSV file in the same directory?

$computers=import-csv"c:\scripts\computers.csv"

foreach

($compin$computers){Get-WmiObject–classWin32_processor |ftsystemname,Name,DeviceID,NumberOfCores,NumberOfLogicalProcessors,Addresswidth}

Thanks in advance.

Mark

Viewing all 21975 articles
Browse latest View live