Powershell - InputObject error message when piping a get-disk variable - windows

I put get-disk into a variable and when I want to pipe it with clear-disk I get an InputObject is null error message. But if I run the two lines of code individually in the Powershell console it works. the variable $USB_Drive is not used anywhere else than in these two lines. Any idea what this could be?
Here the two lines:
$USB_Drive = Get-Disk | Where-Object BusType -eq USB | Out-GridView -Title 'Select USB Drive' -OutputMode Single
$Results = $USB_Drive | Clear-Disk -RemoveData -RemoveOEM -Confirm:$false -Passthru | New-partition -UseMaximumSize -IsActive -AssignDriveLetter | Format-Volume -FileSystem NTFS
And the Error Message:
ERROR: Clear-Disk : Das Argument für den Parameter "InputObject" kann nicht überprüft werden. Das Argument ist NULL. Geben Sie einen gültigen Wert für das Argument
ERROR: an, und führen Sie den Befehl erneut aus.
ERROR: In C:\Users\jorisbieg\Documents\SAPIEN\PowerShell Studio\Projects\ISODRIVE\ISODRIVE.Run.ps1:196 Zeichen:17
ERROR: + ... USB_Drive | Clear-Disk -RemoveData -RemoveOEM -Confirm:$false -Passth ...
ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ERROR: + CategoryInfo : InvalidData: (:) [Clear-Disk], ParameterBindingValidationException
ERROR: + FullyQualifiedErrorId : ParameterArgumentValidationError,Clear-Disk
ERROR:

You are trying to store the output of out-gridview in your variable, this will be closer to what you are after:
# Store the usb drive
$USB_Drive = Get-Disk | Where-Object BusType -eq USB
# display the usb drive
$USB_Drive | Out-GridView -Title 'Select USB Drive' -OutputMode Single
$Results = $USB_Drive | Clear-Disk -RemoveData -RemoveOEM -Confirm:$false -Passthru | New-partition -UseMaximumSize -IsActive -AssignDriveLetter | Format-Volume -FileSystem NTFS

Thanks for the answer, however it was because the variable was not created globally. If I create the variable $global:USB_Drive Global everything works fine.

Related

Powershell UNC Path with credentials

Background:
we created a script was watch our timestamp of the files and when it detect a file that last longer as 10 min in the hotfolder, the script automaticly restart the service.
Thats actually the powershell working powershell script:
#Variablen ausfüllen
$watchfolder = '\\dcsrv\public\Scanner-Eingang'#UNC Pfade funktionieren
$CurTimeStamp = Get-Date
$FileAge = 10 #in Minuten
#Er prüft die Zeit der Dokumente
$Files = Get-ChildItem -Path $watchfolder | Where-Object{($_.LastWriteTime -le
$CurTimeStamp.AddMinutes(-1 * $FileAge))}
#Für jedes Dokument
ForEach ($File in $Files) {
Write-Host " " $File " - " $File.LastWriteTime
## Damit wir der Dienst neugestartet
Restart-Service -Name Spooler
## Sobald er eine Datei gefunden hat stopt er
break
}
The service is running on a server out of the domain and need to reach the hotfolders. The hotfolders are on a domaincontroller with other credentials.
Now i need to connect in my powershell script with the right credentials, some examples i tried you can see here:
#Variablen ausfüllen
$watchfolder = '\\dcsrv\public\Scanner-Eingang'#UNC Pfade funktionieren
$CurTimeStamp = Get-Date
$username = 'user'
$password = '1234'
$FileAge = 10 #in Minuten
#Er prüft die Zeit der Dokumente
$Files = Get-ChildItem -Path $watchfolder $username $password | Where-Object{($_.LastWriteTime -le
$CurTimeStamp.AddMinutes(-1 * $FileAge))}
#Für jedes Dokument
ForEach ($File in $Files) {
Write-Host " " $File " - " $File.LastWriteTime
## Damit wir der Dienst neugestartet
Restart-Service -Name Spooler
## Sobald er eine Datei gefunden hat stopt er
break
}
didnt worked then i tried something else
#Variablen ausfüllen
$watchfolder = '\\dcsrv\public\Scanner-Eingang'#UNC Pfade funktionieren
$CurTimeStamp = Get-Date
$FileAge = 10 #in Minuten
#Er prüft die Zeit der Dokumente
$Files = Get-ChildItem -Path $watchfolder /user:user password:1234 | Where-Object{($_.LastWriteTime -
le $CurTimeStamp.AddMinutes(-1 * $FileAge))}
#Für jedes Dokument
ForEach ($File in $Files) {
Write-Host " " $File " - " $File.LastWriteTime
## Damit wir der Dienst neugestartet
Restart-Service -Name Spooler
## Sobald er eine Datei gefunden hat stopt er
break
}
also without success
Now i hope somebody can help me.
Thanks you!
I think the main question is how do you authenticate to the remote domain, in order to watch the file share. Get-ChildItem doesn't have a -credential parameter.
You can try creating a mapped drive or path first, but you'll need to establish a credential object to use with the New-PSDrive command.
$Pwd = ConvertTo-SecureString -String "password" -AsPlainText -Force
$Cred = [System.Management.Automation.PSCredential]::New('UserName', $pwd)
New-PSDrive -Root '\\dcsrv\public\Scanner-Eingang' -PSProvider FileSystem -Name "ShareToMonitor" -Credential $Cred
...
Note For Powershell 4.0, change:
$Cred = [System.Management.Automation.PSCredential]::New('UserName', $pwd)
to:
$Cred = New-Object System.Management.Automation.PsCredential('UserName',$Pwd)
You can read about New-PSDrive here.
However, it's usually a bad idea to write a password directly into a script. You can store it securely in a file
There are many guides and/or blog articles on the Internet to help with that. Here's the first Google result. Once you establish the secure file you'll have to add code to the script to retrieve it. Then use it to create the credential object as demonstrated above.
Note: The file can only be decoded on the computer and under the account from which it was created.

Invoke command error, trying to get linked GPO's from specific OU from dc by script

i have a line in PS script which goes to DC and try to do this:
$SWITCH = Invoke-Command -session $s -ScriptBlock {Get-ADOrganizationalUnit -filter * -Property CanonicalName | Where-Object {$_.CanonicalName -eq $using:listBox2.SelectedItem}}
here are the the variables:
$switch = "OU=office,DC=shahar,DC=local"
$s = credentials to enter the DC with an admin account.
if i run this line on the DC without the invoke command it works. if i run other code lines with invoking commands using these credentials it works as well.
if i run this line on powershell (not as a part of script) it works.
if i replace $switch with the actual string ("DC=...") it still doesnt work.
here is the error and i just cannot figure out whats the problem:
Cannot bind parameter 'Identity'. Cannot convert value "OU=Office,DC=shahar,DC=local" to type
"Microsoft.ActiveDirectory.Management.ADOrganizationalUnit". Error: "Cannot convert the "OU=Office,DC=shahar,DC=local"
value of type "Deserialized.Microsoft.ActiveDirectory.Management.ADOrganizationalUnit" to type
"Microsoft.ActiveDirectory.Management.ADOrganizationalUnit"."
+ CategoryInfo : InvalidArgument: (:) [Get-ADOrganizationalUnit], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADOrgani
zationalUnit
+ PSComputerName : dc01
any help would be much appriciated!
by the way the point of this is to get from the DC the GPO's names that linked to that OU.
try this:
ipmo ActiveDirectory,GroupPolicy
$OU = 'OU=office,DC=shahar,DC=local'
(Get-ADOrganizationalUnit $OU).DistinguishedName
$LinkedGPOs = Get-ADOrganizationalUnit $OU | select -ExpandProperty LinkedGroupPolicyObjects
$LinkedGPOGUIDs = $LinkedGPOs | % {$_.Substring(4,36)}
$LinkedGPOGUIDs | % {Get-GPO -Guid $_ | select -ExpandProperty Displayname}

New-ADUser unable to concatanate name and domainname

I'm trying to create userprincipalname as combination of username and hardcoded domainname
csv file:
name,displayname,givenname,surname
dhall,Don Hall,Don,Hall
Code:
Import-csv "c:\output.csv" | ForEach-Object {new-aduser -name $_.name -UserPrincipalName ("{0}#{1}" -f $_.name,"Dev.domain.Net") -DisplayName "$($_.givenname $_.surname)" -givenName $_.givenname -surname $_.surname -path "OU=Workspaces,DC=Dev,DC=domain,DC=Net" -AccountPassword (convertto-securestring passs -asplaintext -force) -Enabled [System.Convert]::toboolean($true)) -ChangePasswordAtLogon ([system.convert]::ToBoolean($true))}
And getting:
At line:1 char:159
+ ... -f $_.name,"Dev.domain.Net") -DisplayNa
+
Unexpected token '$_' in expression or stateme
+ CategoryInfo : ParserError: (:)
+ FullyQualifiedErrorId : UnexpectedToken
Tried also -UserPrincipalName ([string]::Concat($_.name,"#dev.domain.net"))
but same error
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 14393 1944
Windows server 2016
Not sure what's causing that error (don't have an AD controller to test against at the moment so can't validate) but in cases where I'm going to need to reuse a property multiple times I tend to assign it to a temporary variable (makes it slightly easier to write the code and don't run into issues with the pipeline variable getting updated).
Import-CSV "c:\output.csv" | ForEach-Object {
$name = $_.name
$upn = "{0}#{1}" -f $name,"dev.domain.net"
New-ADUser -Name $name -UserPrincipalName $upn #...
}

powershell networkinterface convert bytes to kilobytes

I want to convert unit that bytes to kilobytes.
powershell command of bellow entered :
Get-WmiObject -class Win32_PerfFormattedData_Tcpip_NetworkInterface |
select BytesReceivedPersec , BytesSentPersec , name |
Where-Object {$_.name -cnotmatch "isatap"} |
Where-Object {$_.name -cnotmatch "Teredo"} |
Where-Object {$_.name -cnotmatch "로컬"} |
% { '{0,10} {1,20} {2,20}' -f $_.BytesReceivedPersec, $_.BytesSentPersec , $_.name}
output :
627975 483072 Intel[R] 82575L Gigabit Network Connection
But output unit is Bytes
I want to convert unit that bytes to kilobytes.
Add /1kb to the BytesReceived expression and surround them with parentheses:
Get-WmiObject -class Win32_PerfFormattedData_Tcpip_NetworkInterface |
select BytesReceivedPersec , BytesSentPersec , name |
Where-Object {$_.name -cnotmatch "isatap|Teredo|로컬"} |
% { '{0,10} {1,20} {2,20}' -f ($_.BytesReceivedPersec /1kb), ($_.BytesSentPersec /1kb) , $_.name}
Also you can use -cnotmatch {"isatap|Teredo|로컬"} to short the code

how to display the length of a FULLNAME

how can i get the length of the full path of a filename?
I am getting all the files recursively in a directory structure succesfully, and now I am trying to get the length of the fullpath:
get-childitem y:\ -rec | where {!$_.PSIsContainer} |
select-object FullName, LastWriteTime, $($_.fullname).length | export-csv -notypeinformation -delimiter '|' -path file.csv
my issue is with this: $($_.fullname).length:
Select-Object : Null parameter. Expecting one of the following types: {System.String, System.Management.Automation.Scri ptBlock}. At line:2 char:14
+ select-object <<<< FullName, LastWriteTime, $($_.fullname).length | export-csv -notypeinformation -delimiter '|' -pa th file.csv
+ CategoryInfo : InvalidArgument: (:) [Select-Object], NotSupportedException
+ FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand
how would i get the length of the fullname of the file?
Create a custom expression in the select cmdlet. Like this:
get-childitem y:\ -rec | where {!$_.PSIsContainer} |
select-object FullName, LastWriteTime, #{n="FullNameLength";e={ $_.fullname.length }} |
export-csv -notypeinformation -delimiter '|' -path file.csv
n = name and e = expression. You can also use their full name. l or label is an alternative to name. No mather which way you write them, you end up with a custom property. : )

Resources