Issue with get shortcut function not loading in separate script - function

So I have the following script I am trying to run which keeps erroring out
. .\stshortcut.ps1 |
Get-Shortcut . |
Where Target -eq "cmd.exe" |
%{$myPath, $myNewName = $null;
Write-Warning "Processing $($_.Link)";
If (-Not (Test-Path .\BadShortcuts -PathType Container)) {New-Item -
WhatIf -ItemType Directory BadShortcuts | Out-Null};
[string]$myPath = $_.Arguments.Split()[-1] -replace '"';
[string]$myNewName = $_.Link -replace "\.lnk$";
Rename-Item -WhatIf -Force -Path $myPath -NewName $myNewName;
(Get-Item -Force $myNewName).Attributes = '';
Move-Item -WhatIf $_.LinkPath .\BadShortcuts;}`
the error I get is as follows
The term 'Get-Shortcut' 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, verify that the path is correct and try
again.
At C:\Shared\APPS\FixShortcutX2.ps1:1 Char 13
+ Get Shortcut <<<<< . |
+ CategoryInfor : ObjectNotFound: (Get-Shortcut:String)[],
CommandNotFoundException
+ FullyQualifiedErrorID : CommandNotFoundException
the stshortcut.ps1 script has the get-shortcut and set-shortcut functions and are called to do such - I got this script from
https://www.reddit.com/r/PowerShell/comments/4su2jg/zeroday_malware_renamed_folders_on_a_shared_drive/
which is an answer script to fix a macro virus from a word doc attachment - sent from a spoofed email address -
Any assistance is GREATLY appreciated
EDITx2 after some further helpful advice and editing I now am receiving the following
Where-Object : Cannot bind parameter 'FilterScript' . Cannot convert the "Target" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
At C:\Shared\Apps\FixShortcutX2.ps1:3 char:6
+ Where <<<<< Target -eq "cmd.exe" |
+CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.WhereObjectCommand

You need to dot-source stshortcut.ps1 before you can use Get-Shortcut.
Change the first line:
.\stshortcut.ps1 |
To
. .\stshortcut.ps1

Related

JSON Powershell memory issue

I use a command to read a JSON file, this all works perfectly, until the file becomes large.
I currently have a JSON file of about 1.5GB. I read the file using Powershell using the following command:
get-content -Path C:\TEMP\largefile.json | out-string | ConvertFrom-Json
It returns the following error:
out-string : Exception of type 'System.OutOfMemoryException' was thrown.
+ ... oices = get-content -Path C:\TEMP\largefile.json | out-string | Conve ...
+ ~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Out-String], OutOfMemoryException
+ FullyQualifiedErrorId : System.OutOfMemoryException,Microsoft.PowerShell.Commands.OutStringCommand
I've increased the memory as shown here:
get-item wsman:localhost\Shell\MaxMemoryPerShellMB
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Shell
Type Name SourceOfValue Value
---- ---- ------------- -----
System.String MaxMemoryPerShellMB 8096
Any ideas on how to process this?
Edit (additions based on comments):
When I remove the out-string I get this error:
ConvertFrom-Json : Exception of type 'System.OutOfMemoryException' was thrown.
+ ... oices = get-content -Path C:\TEMP\largefile.json | ConvertFrom-Json ...
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Out-String], OutOfMemoryException
+ FullyQualifiedErrorId : System.OutOfMemoryException,Microsoft.PowerShell.Commands.OutStringCommand
The Powershell version that I have is: 5.1.17763.1490
The file contains multiple columns regarding PDF files. These files are exported via an API into a JSON so it contains the file metadata such as owner and when it was created but also the actual PDF file in the column Body which later will be decoded to an actual PDF file. The structure is as followed:
[{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
]
Thank for the details.
For this issue I would try to convert each line separately and stream that through your process:
Get-Content C:\TEMP\largefile.json | ForEach-Object {
$_ = $_.Trim().TrimStart('[').TrimEnd(']')
if ($_) { $_ | ConvertFrom-Json }
}
As already suggested, I wouldn't be surprised if these memory issues wouldn't appear in PowerShell core. if possible, I recommend you to also give that a try.

Calling Powershell function from another power shell script works with error prompt

Hi all I have the following script that calls another script which sends an email.The first script is :
#check status of scheduler
function Check_Scheduler{param([int]$filename)
if($filename -eq 33)
{
$Scheduler="Process_F33"
}
elseif($filename -eq 07)
{
$Scheduler="Process_F07"
}
$status=(Get-ScheduledTask | Where TaskName -EQ $Scheduler).State
#read from a text file
$startTime=(Get-Content -Path E:\AshimTest\time.txt)
$endTime = Get-Date -format HH:mm:ss
#calculate time difference
$TimeDiff = New-TimeSpan $startTime $endTime
if ($TimeDiff.Hours -lt 0) {
$Hrs = ($TimeDiff.Hours) + 23
$Mins = ($TimeDiff.Minutes) + 59
$Secs = ($TimeDiff.Seconds) + 59 }
else {
$Hrs = $TimeDiff.Hours
$Mins = $TimeDiff.Minutes
$Secs = $TimeDiff.Seconds }
$Difference = '{0:00}:{1:00}:{2:00}' -f $Hrs,$Mins,$Secs
if($status -eq "Running")
{
if ($Hrs -gt 2)
{
#Stop-ScheduledTask -TaskName $Scheduler
echo "Sending email"
. .E:\AshimTest\GroupEmail.ps1; Send-Mail -group "IT" -bodypath
"E:\AshimTest\Body.txt" -subject "$Scheduler scheduler Process Failed"
}
}
}
Everything runs fine, I get the email send as well but when I run it from powershell ISE i get following error, even though the script works fine and does what it has to do.
. : The term '.E:\AshimTest\GroupEmail.ps1' 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, verify that the path is correct and try again.
At E:\AshimTest\Check_Status.ps1:35 char:16
+ . .E:\AshimTest\GroupEmail.ps1; Send-Mail -group "IT" -
bodypath "E: ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound:
(.E:\AshimTest\GroupEmail.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I get this error in powershell ISE but still the scripts work fine, do I need to worry or is there something wrong that I am not picking.I am beginner to PowerShell.
Change
. .E:\AshimTest\GroupEmail.ps1
To
. .\GroupEmail.ps1
Make sure both scripts are in the same folder.

Importing Bulk user CSV file

Been trying all day to import my CSV file to my AD on Windows Server 2012.
But keep getting all kind of errors.
The error I get is this:
"New-ADUser : Cannot validate argument on parameter 'Name'. The argument is null
or empty. Provide an argument that is n ot null or empty, and then try the
command again.
At line:3 char:90
+ ... ipalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Dep ...
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUsery
Can't seem to find any solution to this, so some help would be great. Here is my files.
This is my script:
Import-Csv .\nb1.csv | ForEach-Object {
$userprincipalname = $_.SamAccountName + "#hirethistire.local"
New-ADUser -SamAccountName $_.SamAccountName -UserPrincipalName $userprincipalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Department $_.Department -Path "CN_Users,DC=HireThisTire,DC=local"-AccountPassword (ConvertTo-SecureString "Microsoft~1;" -AsPlainText -force) -Enabled $true -PasswordNeverExpires $true -PassThru
}
Sample Of the CSV File:

New-ADUser is not working properly when bulk loading via .csv file

I'm running into an error where this is not picking up the password field at all... I ran the import command manually to make sure it was grabbing all of the correct data, but it errors out on the password and group info...
$Users = Import-Csv -Path "C:\NewUsers.csv"
foreach ($User in $Users)
{
$Displayname = $User.'Firstname' + " " + $User.'Lastname'
$UserFirstname = $User.'Firstname'
$UserLastname = $User.'Lastname'
$OU = $User.'OU'
$SAM = $User.'SAM'
$UPN = $User.'Firstname' + "." + $User.'Lastname' + "#" + $User.'Maildomain'
$Password = $User.'Password'
$Description = $User.'Description'
$Group = $User.'Group'
$Account = New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false -PasswordNeverExpires $true -server esg.intl -PassThru
Add-ADGroupMember -Identity $Group -Members $Account
}
And here are the errors I'm getting even though I know the passwords are ok:
New-ADUser : The password does not meet the length, complexity, or history requirement of the domain.
At C:\Users\A-Shane.Johnson\Desktop\Bulk Add Domain Users.ps1:24 char:13
+ ... $Account = New-ADUser -Name "$Displayname" -DisplayName "$Displaynam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (CN=ESGAP PMOInt...,DC=esg,DC=intl:String) [New-ADUser], ADPasswordComplexi
tyException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1325,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Add-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Users\A-Shane.Johnson\Desktop\Bulk Add Domain Users.ps1:26 char:46
+ Add-ADGroupMember -Identity $Group -Members $Account
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Add-ADGroupMember], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.AddADGrou
pMember
Depending on how that CSV is generated you might try double checking that there isn't an extra space in the Password column header? i.e. 'Password '. Sometimes that trips me up because it doesn't show in the excel or cmd line view easily.
I found the problem and answer. Apparently our domain has an issue when part of the username is in the password. I misunderstood that error thinking that the conversion is what was causing the issue...
I fixed the passwords and now the script runs beautifully!

Powershell - Where-Object : A positional parameter cannot be found that accepts argument 'System.Object[]

I want to add the profile pictures of the exchange to our users in Active Directory.
I tried to do this in Powershell, but cause I'm pretty new to Powershell i'm already stucking.
My Script:
$Name = #()
$Photo = #()
Import-Csv C:\temp\adusers.csv |
ForEach-Object {
$Name += $_.DisplayName
}
Import-Csv C:\temp\photolinks.csv |
ForEach-Object {
$Photo += $_.PSChildName
}
$Name | ForEach-Object {
Where $Photo -Like "*$Name*" {
Set-UserPhoto "$Name" -PictureData ([System.IO.File]::ReadAllBytes("F:\1 path\" + $Photo))
}
}
I created a ps script to get all our AD Users before and I created a list of our userphotos with gci before as well. I exported those results in a csv and I now want to import thos data and tell Powershell add for every User in the List adusers a photo with Set-UserPhoto.
The error message I got is the following:
Where-Object : A positional parameter cannot be found that accepts argument 'System.Object[]'.
At C:\Users\user1\Desktop\setuserphoto.ps1:14 char:13
+ Where $Photo -Like "*$Name*" {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WhereObjectCommand
Can anyone help me here?